@canton-network/core-wallet-store-sql 1.14.0 → 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.
package/dist/index.cjs CHANGED
@@ -22,10 +22,11 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  }) : target, mod));
23
23
  //#endregion
24
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");
25
27
  let kysely = require("kysely");
26
28
  let better_sqlite3 = require("better-sqlite3");
27
29
  better_sqlite3 = __toESM(better_sqlite3, 1);
28
- let _canton_network_core_wallet_store = require("@canton-network/core-wallet-store");
29
30
  let pg = require("pg");
30
31
  pg = __toESM(pg, 1);
31
32
  let umzug = require("umzug");
@@ -257,7 +258,7 @@ const toApiKey = (apiKey) => {
257
258
  };
258
259
  };
259
260
  //#endregion
260
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/typeof.js
261
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/typeof.js
261
262
  function _typeof(o) {
262
263
  "@babel/helpers - typeof";
263
264
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -267,7 +268,7 @@ function _typeof(o) {
267
268
  }, _typeof(o);
268
269
  }
269
270
  //#endregion
270
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/toPrimitive.js
271
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPrimitive.js
271
272
  function toPrimitive(t, r) {
272
273
  if ("object" != _typeof(t) || !t) return t;
273
274
  var e = t[Symbol.toPrimitive];
@@ -279,13 +280,13 @@ function toPrimitive(t, r) {
279
280
  return ("string" === r ? String : Number)(t);
280
281
  }
281
282
  //#endregion
282
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/toPropertyKey.js
283
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPropertyKey.js
283
284
  function toPropertyKey(t) {
284
285
  var i = toPrimitive(t, "string");
285
286
  return "symbol" == _typeof(i) ? i : i + "";
286
287
  }
287
288
  //#endregion
288
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/defineProperty.js
289
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/defineProperty.js
289
290
  function _defineProperty(e, r, t) {
290
291
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
291
292
  value: t,
@@ -360,6 +361,13 @@ var StoreSql = class StoreSql {
360
361
  rights: rightRows.map(({ right }) => fromPartyRight(right)).filter((right) => right !== void 0)
361
362
  };
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
+ }
363
371
  async getPrimaryWallet() {
364
372
  return (await this.getWallets()).find((w) => w.primary === true);
365
373
  }
@@ -556,9 +564,9 @@ var StoreSql = class StoreSql {
556
564
  const userId = this.assertConnected();
557
565
  const token = this.authContext?.accessToken;
558
566
  const onboardingSessionId = this.authContext && !this.authContext.isApiKey ? this.authContext.sessionId : void 0;
559
- if (!token && !onboardingSessionId) throw new Error("No session found");
567
+ if (!token && !onboardingSessionId) throw _canton_network_core_rpc_errors.providerErrors.unauthorized({ message: "No session found" });
560
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();
561
- if (!sessionRow) throw new Error("No session found");
569
+ if (!sessionRow) throw _canton_network_core_rpc_errors.providerErrors.unauthorized({ message: "No session found" });
562
570
  const networkId = toSession(sessionRow).network;
563
571
  if (!networkId) throw new Error("No current network set in session");
564
572
  const network = (await this.listNetworks()).find((n) => n.id === networkId);
@@ -582,6 +590,8 @@ var StoreSql = class StoreSql {
582
590
  async updateNetwork(network) {
583
591
  this.assertConnected();
584
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);
585
595
  const networkEntry = fromNetwork(network, void 0);
586
596
  this.logger.info(networkEntry, "Updating network table");
587
597
  await trx.updateTable("networks").set(networkEntry).where("id", "=", network.id).execute();
@@ -592,7 +602,9 @@ var StoreSql = class StoreSql {
592
602
  if (!(await this.listIdps()).find((idp) => idp.id === network.identityProviderId)) throw new Error(`Identity provider "${network.identityProviderId}" not found`);
593
603
  await this.db.transaction().execute(async (trx) => {
594
604
  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();
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();
596
608
  });
597
609
  }
598
610
  async removeNetwork(networkId) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["authSchema","PartyLevelRight","UserLevelRight","assertConnected","sql","Database","Kysely","SqliteDialect","CamelCasePlugin","PostgresDialect","Umzug","Command"],"sources":["../src/schema.ts","../src/store-sql.ts","../src/migrator.ts","../src/bootstrap.ts","../src/cli.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n authSchema,\n type Idp,\n type UserId,\n} from '@canton-network/core-wallet-auth'\nimport {\n type Wallet,\n type Transaction,\n type Session,\n type Network,\n type WalletStatus,\n type UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n type MessageRaw,\n type ApiKey,\n} from '@canton-network/core-wallet-store'\n\ninterface MigrationTable {\n name: string\n executedAt: string\n}\n\ninterface IdpTable {\n id: string\n type: 'oauth' | 'self_signed' | 'self_issued'\n issuer: string | null\n configUrl: string | null\n}\n\ninterface NetworkTable {\n id: string\n name: string\n synchronizerId: string | null // retrieved at runtime if null\n description: string\n ledgerApiBaseUrl: string\n identityProviderId: string\n userId: UserId | undefined // global if undefined\n\n auth: string // json stringified\n adminAuth: string | undefined // json stringified\n serviceAccountAuth: string | undefined // json stringified\n}\n\n/**\n * Wallet table schema\n * Primary key on (partyId, networkId, userId)\n * Unique constraint on (networkId, userId) for primary wallet per network per user\n */\ninterface WalletTable {\n primary: number\n partyId: string\n hint: string\n publicKey: string\n namespace: string\n networkId: string\n signingProviderId: string\n userId: UserId\n externalTxId: string | null\n topologyTransactions: string | null\n status: string | null\n disabled: number\n reason: string | null\n isAuthParty: number\n}\ninterface UpdateWalletProperties {\n primary?: number\n externalTxId?: string | null\n topologyTransactions?: string | null\n status?: string | null\n disabled?: number\n reason?: string | null\n isAuthParty?: number\n}\n\ninterface UserPartyRightTable {\n userId: UserId\n networkId: string\n partyId: string\n right: PartyLevelRight\n}\n\ninterface UserRightTable {\n userId: UserId\n networkId: string\n right: UserLevelRight\n}\n\ninterface TransactionTable {\n id: string\n status: string\n commandId: string\n networkId: string\n preparedTransaction: string\n preparedTransactionHash: string\n payload: string | undefined\n origin: string | null\n userId: UserId\n createdAt: string | null\n signedAt: string | null\n externalTxId: string | null\n}\n\ninterface MessageRawTable {\n id: string\n status: string\n partyId: string\n publicKey: string\n message: string\n origin: string | null\n userId: UserId\n networkId: string\n createdAt: string\n signedAt: string | null\n signature: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string | null\n userId: UserId\n}\n\ninterface ApiKeysTable {\n id: string\n digest: string\n name: string\n userId: UserId\n email: string | null\n networkId: string\n createdAt: string\n lastUsedAt: string | null\n}\n\nexport interface DB {\n migrations: MigrationTable\n idps: IdpTable\n networks: NetworkTable\n wallets: WalletTable\n userPartyRights: UserPartyRightTable\n userRights: UserRightTable\n transactions: TransactionTable\n messagesRaw: MessageRawTable\n sessions: SessionTable\n apiKeys: ApiKeysTable\n}\n\nexport const toIdp = (table: IdpTable): Idp => {\n switch (table.type) {\n case 'oauth': {\n if (!table.configUrl) {\n throw new Error(`Missing configUrl for oauth IdP: ${table.id}`)\n }\n if (table.issuer === null) {\n throw new Error(`Missing issuer for oauth IdP: ${table.id}`)\n }\n\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n configUrl: table.configUrl,\n }\n }\n case 'self_signed':\n if (table.issuer === null) {\n throw new Error(\n `Missing issuer for self_signed IdP: ${table.id}`\n )\n }\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n case 'self_issued':\n return {\n id: table.id,\n type: table.type,\n }\n }\n}\n\nexport const fromIdp = (idp: Idp): IdpTable => {\n switch (idp.type) {\n case 'oauth':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: idp.configUrl,\n }\n case 'self_signed':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: null,\n }\n case 'self_issued':\n return {\n id: idp.id,\n type: idp.type,\n issuer: null,\n configUrl: null,\n }\n }\n}\n\nexport const toNetwork = (table: NetworkTable): Network => {\n return {\n name: table.name,\n id: table.id,\n synchronizerId: table.synchronizerId ?? undefined,\n identityProviderId: table.identityProviderId,\n description: table.description,\n ledgerApi: {\n baseUrl: table.ledgerApiBaseUrl,\n },\n auth: authSchema.parse(\n typeof table.auth === 'string' ? JSON.parse(table.auth) : table.auth\n ),\n adminAuth: table.adminAuth\n ? authSchema.parse(\n typeof table.adminAuth === 'string'\n ? JSON.parse(table.adminAuth)\n : table.adminAuth\n )\n : undefined,\n serviceAccountAuth: table.serviceAccountAuth\n ? authSchema.parse(\n typeof table.serviceAccountAuth === 'string'\n ? JSON.parse(table.serviceAccountAuth)\n : table.serviceAccountAuth\n )\n : undefined,\n }\n}\n\nexport const fromNetwork = (\n network: Network,\n userId?: UserId\n): NetworkTable => {\n return {\n name: network.name,\n id: network.id,\n synchronizerId: network.synchronizerId ?? null,\n description: network.description,\n ledgerApiBaseUrl: network.ledgerApi.baseUrl,\n userId: userId,\n identityProviderId: network.identityProviderId,\n auth: JSON.stringify(network.auth),\n adminAuth: network.adminAuth\n ? JSON.stringify(network.adminAuth)\n : undefined,\n serviceAccountAuth: network.serviceAccountAuth\n ? JSON.stringify(network.serviceAccountAuth)\n : undefined,\n }\n}\n\nexport const toSession = (table: SessionTable): Session => {\n return {\n id: table.id,\n network: table.network,\n origin: table.origin,\n ...(table.accessToken ? { accessToken: table.accessToken } : {}),\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, isAuthParty, ...rest } =\n wallet\n void rights\n return {\n ...rest,\n primary: wallet.primary ? 1 : 0,\n userId: userId,\n disabled: wallet.disabled !== undefined && wallet.disabled ? 1 : 0,\n isAuthParty: isAuthParty ? 1 : 0,\n reason: wallet.reason ?? null,\n externalTxId: externalTxId && externalTxId !== '' ? externalTxId : null,\n topologyTransactions:\n topologyTransactions && topologyTransactions !== ''\n ? topologyTransactions\n : null,\n }\n}\n\n// only update fields that are explicitly provided to prevent data loss\nexport const toWalletUpdateProperties = (\n params: UpdateWallet\n): UpdateWalletProperties => {\n const {\n status,\n externalTxId,\n topologyTransactions,\n disabled,\n reason,\n primary,\n signingProviderId,\n publicKey,\n namespace,\n isAuthParty,\n } = params\n return {\n ...(status !== undefined && { status }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(topologyTransactions !== undefined && { topologyTransactions }),\n ...(primary !== undefined && { primary: primary ? 1 : 0 }),\n ...(disabled !== undefined && { disabled: disabled ? 1 : 0 }),\n ...(reason !== undefined && { reason }),\n ...(signingProviderId !== undefined && { signingProviderId }),\n ...(publicKey !== undefined && { publicKey }),\n ...(namespace !== undefined && { namespace }),\n ...(isAuthParty !== undefined && { isAuthParty: isAuthParty ? 1 : 0 }),\n }\n}\n\nexport const toWalletStatus = (status?: string | null): WalletStatus => {\n if (status === 'allocated') return 'allocated'\n if (status === 'removed') return 'removed'\n return 'initialized'\n}\n\nexport const toWallet = (table: WalletTable): Wallet => {\n return {\n primary: Boolean(table.primary),\n status: toWalletStatus(table.status),\n partyId: table.partyId,\n hint: table.hint,\n publicKey: table.publicKey,\n namespace: table.namespace,\n networkId: table.networkId,\n signingProviderId: table.signingProviderId,\n disabled: table.disabled === 1,\n isAuthParty: Boolean(table.isAuthParty),\n userId: table.userId,\n ...(table.externalTxId !== null && {\n externalTxId: table.externalTxId,\n }),\n ...(table.topologyTransactions !== null && {\n topologyTransactions: table.topologyTransactions,\n }),\n ...(table.reason !== null && {\n reason: table.reason,\n }),\n rights: [],\n }\n}\n\nexport const fromPartyRight = (right: string): PartyLevelRight | undefined => {\n if (Object.values(PartyLevelRight).includes(right as PartyLevelRight)) {\n return right as PartyLevelRight\n }\n return undefined\n}\n\nexport const fromUserRight = (right: string): UserLevelRight | undefined => {\n if (Object.values(UserLevelRight).includes(right as UserLevelRight)) {\n return right as UserLevelRight\n }\n return undefined\n}\n\nexport const fromTransaction = (\n transaction: Transaction,\n userId: UserId,\n networkId: string\n): TransactionTable => {\n return {\n ...transaction,\n networkId,\n payload: transaction.payload\n ? JSON.stringify(transaction.payload)\n : undefined,\n origin: transaction.origin || null,\n userId: userId,\n createdAt: transaction.createdAt?.toISOString() || null,\n signedAt: transaction.signedAt?.toISOString() || null,\n externalTxId: transaction.externalTxId ?? null,\n }\n}\n\nexport const toTransaction = (table: TransactionTable): Transaction => {\n const result: Transaction = {\n id: table.id,\n commandId: table.commandId,\n status: table.status as 'pending' | 'signed' | 'executed' | 'failed',\n preparedTransaction: table.preparedTransaction,\n preparedTransactionHash: table.preparedTransactionHash,\n payload: table.payload ? JSON.parse(table.payload) : undefined,\n origin: table.origin || null,\n userId: table.userId,\n networkId: table.networkId,\n }\n\n if (table.createdAt) {\n result.createdAt = new Date(table.createdAt)\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n\n if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n\n return result\n}\n\nexport const fromMessageRaw = (\n message: MessageRaw,\n userId: UserId,\n networkId: string\n): MessageRawTable => {\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n return {\n id: message.id,\n status: message.status,\n userId: message.userId,\n partyId: message.partyId,\n publicKey: message.publicKey,\n message: message.message,\n origin: message.origin || null,\n networkId,\n createdAt: message.createdAt.toISOString(),\n signedAt: message.signedAt?.toISOString() || null,\n signature: message.signature ?? null,\n }\n}\n\nexport const toMessageRaw = (table: MessageRawTable): MessageRaw => {\n const result: MessageRaw = {\n id: table.id,\n status: table.status as MessageRaw['status'],\n userId: table.userId,\n partyId: table.partyId,\n publicKey: table.publicKey,\n message: table.message,\n origin: table.origin || null,\n createdAt: new Date(table.createdAt),\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n if (table.signature) {\n result.signature = table.signature\n }\n\n return result\n}\n\nexport const fromApiKey = (table: ApiKeysTable): ApiKey => {\n return {\n id: table.id,\n digest: table.digest,\n name: table.name,\n userId: table.userId,\n email: table.email,\n networkId: table.networkId,\n createdAt: new Date(table.createdAt),\n lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : undefined,\n }\n}\n\nexport const toApiKey = (apiKey: ApiKey): ApiKeysTable => {\n return {\n id: apiKey.id,\n digest: apiKey.digest,\n name: apiKey.name,\n userId: apiKey.userId,\n email: apiKey.email,\n networkId: apiKey.networkId,\n createdAt: apiKey.createdAt.toISOString(),\n lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null,\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Logger } from 'pino'\nimport {\n type AuthContext,\n type UserId,\n type AuthAware,\n assertConnected,\n type Idp,\n} from '@canton-network/core-wallet-auth'\nimport type {\n Store as BaseStore,\n Wallet,\n PartyId,\n Session,\n WalletFilter,\n Transaction,\n MessageRaw,\n MessageRawStatusUpdate,\n Network,\n StoreConfig,\n UpdateWallet,\n CurrentNetworkWalletFilter,\n PartyLevelRight,\n TransactionStatusUpdate,\n UserLevelRight,\n ApiKey,\n ListTransactionsOptions,\n WalletUniqueConstraint,\n} from '@canton-network/core-wallet-store'\nimport {\n CamelCasePlugin,\n Kysely,\n PostgresDialect,\n SqliteDialect,\n sql,\n} from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n type DB,\n fromIdp,\n fromNetwork,\n fromTransaction,\n fromMessageRaw,\n fromWallet,\n fromPartyRight,\n fromUserRight,\n toWalletUpdateProperties,\n toIdp,\n toNetwork,\n toTransaction,\n toMessageRaw,\n toWallet,\n fromApiKey,\n toApiKey,\n toSession,\n} from './schema.js'\nimport pg from 'pg'\nimport type { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n private logger: Logger,\n authContext?: AuthContext\n ) {\n this.logger = logger.child({ component: 'StoreSql' })\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, this.logger, context)\n }\n\n private assertConnected(): UserId {\n return assertConnected(this.authContext).userId\n }\n\n // Wallet methods\n\n async getAllWallets(filter: WalletFilter = {}): Promise<Array<Wallet>> {\n const userId = this.assertConnected()\n const { networkIds, signingProviderIds } = filter\n const networkIdSet = networkIds ? new Set(networkIds) : null\n const signingProviderIdSet = signingProviderIds\n ? new Set(signingProviderIds)\n : null\n\n const wallets = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const userPartyRights = await this.db\n .selectFrom('userPartyRights')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const rightsByWallet = new Map<string, PartyLevelRight[]>()\n for (const row of userPartyRights) {\n const right = fromPartyRight(row.right)\n if (!right) continue\n const key = `${row.partyId}:${row.networkId}`\n const existing = rightsByWallet.get(key) ?? []\n rightsByWallet.set(key, [...existing, right])\n }\n\n return wallets\n .filter((wallet) => {\n const matchedNetworkIds = networkIdSet\n ? networkIdSet.has(wallet.networkId)\n : true\n const matchedSigningProviderIds = signingProviderIdSet\n ? signingProviderIdSet.has(wallet.signingProviderId)\n : true\n return matchedNetworkIds && matchedSigningProviderIds\n })\n .map((table) => {\n const wallet = toWallet(table)\n const rights = rightsByWallet.get(\n `${table.partyId}:${table.networkId}`\n )\n return {\n ...wallet,\n rights: rights ?? [],\n }\n })\n }\n\n async getWallets(\n filter: CurrentNetworkWalletFilter = {}\n ): Promise<Array<Wallet>> {\n const network = await this.getCurrentNetwork()\n return this.getAllWallets({\n ...filter,\n networkIds: [network.id],\n })\n }\n\n async getWallet(partyId: PartyId): Promise<Wallet | null> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const constraint: WalletUniqueConstraint = {\n partyId,\n networkId: network.id,\n userId,\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where((eb) => eb.and(constraint))\n .executeTakeFirst()\n\n if (!row) return null\n\n const rightRows = await this.db\n .selectFrom('userPartyRights')\n .select('right')\n .where((eb) => eb.and(constraint))\n .execute()\n\n return {\n ...toWallet(row),\n rights: rightRows\n .map(({ right }) => fromPartyRight(right))\n .filter((right) => right !== undefined),\n }\n }\n\n async getPrimaryWallet(): Promise<Wallet | undefined> {\n const wallets = await this.getWallets()\n return wallets.find((w) => w.primary === true)\n }\n\n async setPrimaryWallet(partyId: PartyId): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n const wallets = await this.getWallets()\n\n if (!wallets.some((w) => w.partyId === partyId)) {\n throw new Error(\n `Wallet with partyId \"${partyId}\" not found in network \"${network.id}\"`\n )\n }\n\n const primary = wallets.find((w) => w.primary === true)\n\n await this.db.transaction().execute(async (trx) => {\n if (primary) {\n // Unset primary for current network only\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', primary.partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n // Set new primary for current network\n await trx\n .updateTable('wallets')\n .set({ primary: 1 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async addWallet(wallet: Wallet): Promise<void> {\n this.logger.info('Adding wallet')\n const userId = this.assertConnected()\n\n const wallets = await this.getWallets()\n if (\n wallets.some(\n (w) =>\n w.partyId === wallet.partyId &&\n w.networkId === wallet.networkId\n )\n ) {\n throw new Error(\n `Wallet with partyId \"${wallet.partyId}\" networkId \"${wallet.networkId}\" userId \"${userId}\" already exists`\n )\n }\n\n if (\n !wallet.disabled &&\n wallet.status === 'allocated' &&\n !wallets.some((wallet) => wallet.primary)\n ) {\n // If there is no primary wallet yet, set current one as primary (unless disabled or not allocated).\n // In regular case it would be the first added wallet.\n wallet.primary = true\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (wallet.primary) {\n // If the new wallet is primary, set all others in the same network and for this user to non-primary\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('primary', '=', 1),\n eb('networkId', '=', wallet.networkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n await trx\n .insertInto('wallets')\n .values(fromWallet(wallet, userId))\n .execute()\n\n if (wallet.rights && wallet.rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n wallet.rights.map((right) => ({\n userId,\n networkId: wallet.networkId,\n partyId: wallet.partyId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n async updateWallet(params: UpdateWallet): Promise<void> {\n const { partyId, networkId, rights } = params\n this.logger.info('Updating wallet')\n const userId = this.assertConnected()\n\n const updates = toWalletUpdateProperties(params)\n\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n if (Object.keys(updates).length === 0 && rights === undefined) return\n\n await this.db.transaction().execute(async (trx) => {\n if (Object.keys(updates).length > 0) {\n await trx\n .updateTable('wallets')\n .set(updates)\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n\n if (rights !== undefined) {\n await trx\n .deleteFrom('userPartyRights')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId: targetNetworkId,\n partyId,\n right,\n }))\n )\n .execute()\n }\n }\n })\n }\n\n async removeWallet(partyId: PartyId): Promise<void> {\n this.logger.info('Removing wallet')\n const userId = this.assertConnected()\n\n // Remove wallet from current network only\n const network = await this.getCurrentNetwork()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('wallets')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async getUserRights(networkId?: string): Promise<Array<UserLevelRight>> {\n const userId = this.assertConnected()\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n const rows = await this.db\n .selectFrom('userRights')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', targetNetworkId),\n ])\n )\n .execute()\n\n return rows\n .map((row) => fromUserRight(row.right))\n .filter((right): right is UserLevelRight => right !== undefined)\n }\n\n async setUserRights(\n networkId: string,\n rights: Array<UserLevelRight>\n ): Promise<void> {\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('userRights')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', networkId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n // Session methods\n async getSession(accessToken: AccessToken): Promise<Session | undefined> {\n const userId = this.assertConnected()\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async listSessions(): Promise<Array<Session>> {\n const userId = this.assertConnected()\n const rows = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n return rows.map((row) => toSession(row))\n }\n\n async setSession(session: Session): Promise<void> {\n const userId = this.assertConnected()\n\n if (!session.origin) {\n throw new Error('Session origin is required')\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (session.accessToken) {\n // Regular session - one user can have only one session per origin.\n // Tokenless sessions are not replaced by duplicates.\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n eb('accessToken', 'is not', null),\n ])\n )\n .execute()\n this.logger.debug(deleted, 'Deleted old session')\n }\n\n const inserted = await trx\n .insertInto('sessions')\n .values({\n ...session,\n accessToken: session.accessToken ?? null,\n userId,\n })\n .execute()\n\n this.logger.debug(inserted, 'Inserted new session')\n })\n }\n\n async getOnboardingSession(\n sessionId: string\n ): Promise<Session | undefined> {\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async upgradeOnboardingSession(\n sessionId: string,\n accessToken: AccessToken\n ): Promise<Session> {\n const userId = this.assertConnected()\n\n return this.db.transaction().execute(async (trx) => {\n const row = await trx\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('userId', '=', userId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n if (!row) {\n throw new Error('Onboarding session not found')\n }\n\n await trx\n .deleteFrom('sessions')\n .where('userId', '=', userId)\n .where('origin', '=', row.origin)\n .where('id', '!=', sessionId)\n .execute()\n await trx\n .updateTable('sessions')\n .set({ accessToken })\n .where('id', '=', sessionId)\n .execute()\n\n return toSession({ ...row, accessToken })\n })\n }\n\n async removeSession(accessToken: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .execute()\n }\n\n /**\n * Lists all pending transactions across all users.\n */\n\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.or([\n eb('status', '=', 'pending'),\n eb('status', '=', 'awaiting-signature'),\n ])\n )\n .execute()\n\n return rows.map((row) => toTransaction(row))\n }\n\n // IDP methods\n\n async getIdp(idpId: string): Promise<Idp> {\n const idps = await this.listIdps()\n if (!idps) throw new Error('No IDPs available')\n\n const idp = idps.find((n) => n.id === idpId)\n if (!idp) throw new Error(`IDP \"${idpId}\" not found`)\n return idp\n }\n\n async listIdps(): Promise<Array<Idp>> {\n // All IDPs are global for now -- TO-DO: user-specific IDPs\n const query = this.db.selectFrom('idps').selectAll()\n\n const idps = await query.execute()\n return idps.map((table) => toIdp(table))\n }\n\n async updateIdp(idp: Idp): Promise<void> {\n // todo: check and compare userid of existing idp\n await this.db.transaction().execute(async (trx) => {\n const idpEntry = fromIdp(idp)\n this.logger.info(idpEntry, 'Updating idp table')\n await trx\n .updateTable('idps')\n .set(idpEntry)\n .where('id', '=', idp.id)\n .execute()\n })\n }\n\n async addIdp(idp: Idp): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n const idpAlreadyExists = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idp.id)\n .executeTakeFirst()\n if (idpAlreadyExists) {\n throw new Error(`IDP ${idp.id} already exists`)\n } else {\n await trx.insertInto('idps').values(fromIdp(idp)).execute()\n }\n })\n }\n\n async removeIdp(idpId: string): Promise<void> {\n const networks = await this.listNetworks()\n if (networks.some((n) => n.identityProviderId === idpId)) {\n throw new Error(\n `Cannot delete IDP ${idpId} as it is in use by existing networks`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const idp = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idpId)\n .executeTakeFirst()\n if (!idp) {\n throw new Error(`IDP ${idpId} does not exists`)\n }\n await trx.deleteFrom('idps').where('id', '=', idpId).execute()\n })\n }\n\n // Network methods\n async getNetwork(networkId: string): Promise<Network> {\n const networks = await this.listNetworks()\n if (!networks) throw new Error('No networks available')\n\n const network = networks.find((n) => n.id === networkId)\n if (!network) throw new Error(`Network \"${networkId}\" not found`)\n return network\n }\n\n async getCurrentNetwork(): Promise<Network> {\n const userId = this.assertConnected()\n const token = this.authContext?.accessToken\n const onboardingSessionId =\n this.authContext && !this.authContext.isApiKey\n ? this.authContext.sessionId\n : undefined\n if (!token && !onboardingSessionId) {\n throw new Error('No session found')\n }\n\n const sessionRow = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .where((eb) =>\n token\n ? eb('accessToken', '=', token)\n : eb.and([\n eb('id', '=', onboardingSessionId!),\n eb('accessToken', 'is', null),\n ])\n )\n .executeTakeFirst()\n if (!sessionRow) {\n throw new Error('No session found')\n }\n\n const session = toSession(sessionRow)\n const networkId = session.network\n if (!networkId) {\n throw new Error('No current network set in session')\n }\n\n const networks = await this.listNetworks()\n const network = networks.find((n) => n.id === networkId)\n if (!network) {\n throw new Error(`Network \"${networkId}\" not found`)\n }\n return network\n }\n\n async getNetworkForTokenVerification(\n networkId: string\n ): Promise<Network | undefined> {\n // Not scoped by userId: key id resolution happens during token\n // verification, before there is an authenticated user.\n const row = await this.db\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!row) return undefined\n\n const network = toNetwork(row)\n return network.auth.method === 'self_signed' ? network : undefined\n }\n\n async listNetworks(): Promise<Array<Network>> {\n let query = this.db.selectFrom('networks').selectAll()\n\n if (this.authContext) {\n const userId = this.assertConnected()\n query = query.where((eb) =>\n eb.or([\n eb('userId', 'is', null), // Global networks\n eb('userId', '=', userId), // User-specific networks\n ])\n )\n } else {\n query = query.where('userId', 'is', null) // Only global networks\n }\n\n const networks = await query.execute()\n return networks.map((table) => toNetwork(table))\n }\n\n async updateNetwork(network: Network): Promise<void> {\n // todo: check and compare idpId of existing network\n this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n // we do not set a userId for now and leave all networks global when updating\n const networkEntry = fromNetwork(network, undefined)\n this.logger.info(networkEntry, 'Updating network table')\n await trx\n .updateTable('networks')\n .set(networkEntry)\n .where('id', '=', network.id)\n .execute()\n })\n }\n\n async addNetwork(network: Network): Promise<void> {\n const userId = this.authContext?.userId\n const idps = await this.listIdps()\n const networkIdp = idps.find(\n (idp) => idp.id === network.identityProviderId\n )\n\n if (!networkIdp) {\n throw new Error(\n `Identity provider \"${network.identityProviderId}\" not found`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const networkAlreadyExists = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', network.id)\n .executeTakeFirst()\n if (networkAlreadyExists) {\n throw new Error(`Network ${network.id} already exists`)\n } else {\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\n }\n })\n }\n\n async removeNetwork(networkId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const network = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!network) {\n throw new Error(`Network ${networkId} does not exists`)\n }\n if (network.userId !== userId) {\n throw new Error(\n `Network ${networkId} is not owned by user ${userId}`\n )\n }\n await trx\n .deleteFrom('networks')\n .where('id', '=', networkId)\n .execute()\n })\n }\n\n private mergeTransactionStatusUpdate(\n existing: Transaction,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Transaction {\n const payload = updates.payload ?? existing.payload\n const signedAt = updates.signedAt ?? existing.signedAt\n const externalTxId = updates.externalTxId ?? existing.externalTxId\n const failureReason = updates.failureReason ?? existing.failureReason\n\n return {\n id: existing.id,\n commandId: existing.commandId,\n status,\n preparedTransaction: existing.preparedTransaction,\n preparedTransactionHash: existing.preparedTransactionHash,\n origin: existing.origin,\n ...(payload !== undefined && { payload }),\n ...(existing.createdAt !== undefined && {\n createdAt: existing.createdAt,\n }),\n ...(signedAt !== undefined && { signedAt }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(failureReason !== undefined && { failureReason }),\n }\n }\n\n // Transaction methods\n async setTransaction(transaction: Transaction): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n await this.db\n .insertInto('transactions')\n .values(fromTransaction(transaction, userId, network.id))\n .execute()\n }\n\n async setTransactionSigned(\n transactionId: string,\n signedAt: Date,\n externalTxId?: string,\n opts?: { expectedStatus: Transaction['status'] }\n ): Promise<boolean> {\n return await this.setTransactionStatus(\n transactionId,\n 'signed',\n {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n },\n opts\n )\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {},\n opts?: { expectedStatus?: Transaction['status'] }\n ): Promise<boolean> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getTransaction(transactionId)\n if (!existing) {\n throw new Error(`Transaction not found with id: ${transactionId}`)\n }\n if (opts?.expectedStatus && existing.status !== opts.expectedStatus) {\n return false\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n const res = await this.db\n .updateTable('transactions')\n .set(fromTransaction(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ...(opts?.expectedStatus\n ? [eb('status', '=', opts.expectedStatus)]\n : []),\n ])\n )\n .executeTakeFirst()\n\n return res.numUpdatedRows > 0n\n }\n\n async getTransaction(\n transactionId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async getLatestTransactionByCommandId(\n commandId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('commandId', '=', commandId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .executeTakeFirst()\n\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async transactionsCount(): Promise<number> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n const result = await this.db\n .selectFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .select((eb) => eb.fn.count<number>('id').as('count'))\n .executeTakeFirstOrThrow()\n\n return Number(result.count)\n }\n\n async listTransactions(options?: ListTransactionsOptions) {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const { cursor, limit } = options ?? {}\n const lim = limit ? Math.min(limit, 100) : 100\n\n let query = this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .orderBy('id', 'desc')\n .limit(lim + 1)\n\n if (cursor) {\n const split = cursor.split('::')\n const dateString = split[0] === 'null' ? null : split[0]\n const cursorId = split[1]\n\n query = query.where((eb) => {\n if (dateString === null) {\n return eb.and([\n eb('createdAt', 'is', null),\n eb('id', '<', cursorId),\n ])\n }\n\n return eb.or([\n eb('createdAt', '<', dateString),\n eb.and([\n eb('createdAt', '=', dateString),\n eb('id', '<', split[1]),\n ]),\n eb('createdAt', 'is', null),\n ])\n })\n }\n\n const rows = await query.execute()\n const txs = rows.map((r) => toTransaction(r))\n\n const hasNextPage = txs.length > lim\n if (hasNextPage) {\n txs.pop()\n }\n\n if (txs.length === 0) {\n return {\n transactions: [],\n nextCursor: null,\n }\n }\n\n const lastTx = txs[txs.length - 1]\n if (lastTx === undefined) {\n return {\n transactions: txs,\n nextCursor: null,\n }\n }\n\n //handle case for if timestamp is null\n if (lastTx.createdAt) {\n const d = new Date(lastTx.createdAt).toISOString()\n const nextCursor = hasNextPage ? `${d}::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n } else {\n const nextCursor = hasNextPage ? `null::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n }\n }\n\n async removeTransaction(transactionId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n private mergeMessageRawStatusUpdate(\n existing: MessageRaw,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): MessageRaw {\n const signedAt = updates.signedAt ?? existing.signedAt\n const signature = updates.signature ?? existing.signature\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n }\n }\n\n // Message signing request methods\n async setMessageRaw(message: MessageRaw): Promise<void> {\n const userId = this.assertConnected()\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n const network = await this.getCurrentNetwork()\n await this.db\n .insertInto('messagesRaw')\n .values(fromMessageRaw(message, userId, network.id))\n .execute()\n }\n\n async setMessageRawStatus(\n messageId: string,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getMessageRaw(messageId)\n if (!existing) {\n throw new Error(`MessageRaw not found with id: ${messageId}`)\n }\n\n const updated = this.mergeMessageRawStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('messagesRaw')\n .set(fromMessageRaw(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getMessageRaw(messageId: string): Promise<MessageRaw | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const message = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return message ? toMessageRaw(message) : undefined\n }\n\n async listMessageRaws(): Promise<Array<MessageRaw>> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const messages = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .execute()\n return messages.map((m) => toMessageRaw(m))\n }\n\n async removeMessageRaw(messageId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('messagesRaw')\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n // API keys\n async addApiKey(apiKey: ApiKey): Promise<void> {\n const userId = this.assertConnected()\n if (apiKey.userId !== userId) {\n throw new Error(\n `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`\n )\n }\n\n const network = await this.getCurrentNetwork()\n if (apiKey.networkId !== network.id) {\n throw new Error(\n `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`\n )\n }\n\n await this.db.insertInto('apiKeys').values(toApiKey(apiKey)).execute()\n }\n\n async listApiKeys(): Promise<Array<ApiKey>> {\n const query = this.db\n .selectFrom('apiKeys')\n .selectAll()\n .orderBy('createdAt', 'desc')\n\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const apiKeys = await query\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n\n return apiKeys.map(fromApiKey)\n }\n\n async getApiKey(digest: string): Promise<ApiKey | undefined> {\n const apiKey = await this.db\n .selectFrom('apiKeys')\n .selectAll()\n .where((eb) => eb('digest', '=', digest))\n .executeTakeFirst()\n\n return apiKey ? fromApiKey(apiKey) : undefined\n }\n\n async removeApiKey(apiKeyId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('apiKeys')\n .where((eb) =>\n eb.and([\n eb('id', '=', apiKeyId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n}\n\nexport const connection = (config: StoreConfig) => {\n let database\n switch (config.connection.type) {\n case 'sqlite':\n database = new Database(config.connection.database)\n // normally sqlite3 has foreign_keys = OFF for each connection,\n // but better-sqlite3 uses custom build with compile flag SQLITE_DEFAULT_FOREIGN_KEYS=1,\n // making it ON by default.\n // Set explicitly ON anyway as redundancy\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'postgres':\n return new Kysely<DB>({\n dialect: new PostgresDialect({\n pool: new pg.Pool(config.connection),\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'memory':\n database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Umzug, type MigrationMeta, type UmzugStorage } from 'umzug'\nimport type { Kysely } from 'kysely'\nimport type { DB } from './schema'\n\nclass KyselyStorage implements UmzugStorage {\n constructor(private db: Kysely<DB>) {}\n\n private async ensureTable() {\n await this.db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'text', (col) => col.primaryKey())\n .addColumn('executedAt', 'text', (col) => col.notNull())\n .execute()\n }\n\n async executed(): Promise<string[]> {\n await this.ensureTable()\n const rows = await this.db\n .selectFrom('migrations')\n .select('name')\n .execute()\n return rows.map((r) => r.name)\n }\n\n async logMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .insertInto('migrations')\n .values({ name, executedAt: new Date().toISOString() })\n .execute()\n }\n\n async unlogMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute()\n }\n}\n\nexport const migrator = (db: Kysely<DB>) => {\n const ext = import.meta.url.endsWith('.ts') ? 'ts' : 'js'\n const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname\n return new Umzug({\n migrations: {\n glob: glob,\n resolve: ({ name, path, context }) => {\n // Dynamic import for ESM\n return {\n name,\n up: async () => {\n console.log(path)\n const { up } = await import(path!)\n return up(context)\n },\n down: async () => {\n const { down } = await import(path!)\n return down(context)\n },\n }\n },\n },\n context: db,\n storage: new KyselyStorage(db),\n logger: console,\n })\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport type { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport type { Logger } from 'pino'\nimport type { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig,\n logger: Logger\n): Promise<void> {\n const store = new StoreSql(db, logger)\n\n // Load all IDPs from config into the store\n await Promise.all(config.idps.map((idp) => store.addIdp(idp)))\n\n // Load all networks from config into the store\n await Promise.all(\n config.networks.map((network) => store.addNetwork(network))\n )\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Command } from 'commander'\nimport { connection } from './store-sql.js'\nimport { migrator } from './migrator.js'\nimport type {\n StoreConfig,\n BootstrapConfig,\n} from '@canton-network/core-wallet-store'\nimport { pino } from 'pino'\nimport { bootstrap } from './bootstrap.js'\n\nconst logger = pino({ name: 'main', level: 'debug' })\n\nexport function createCLI(\n config: StoreConfig,\n bootstrapConfig?: BootstrapConfig\n): Command {\n const program = new Command()\n\n program\n .command('up')\n .description('Run all pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('down')\n .description('Rollback last migration')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.down()\n await db.destroy()\n })\n\n program\n .command('status')\n .description('Show executed and pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n const pending = await umzug.pending()\n\n console.log('Executed migrations:', executed)\n console.log('Pending migrations:', pending)\n\n await db.destroy()\n })\n\n program\n .command('reset')\n .description('Rollback all migrations and reapply them')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n\n // Rollback all executed migrations in reverse order\n for (const migration of executed.reverse()) {\n await umzug.down({ to: migration.name })\n }\n\n // Reapply all migrations\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('bootstrap')\n .description('Bootstrap DB from config')\n .action(async () => {\n if (!bootstrapConfig) {\n throw new Error(\n 'Bootstrap config (idps/networks) is required for the bootstrap command'\n )\n }\n const db = connection(config)\n await bootstrap(db, bootstrapConfig, logger)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAElE,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MAAM,iCAAiC,MAAM,IAAI;GAG/D,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,WAAW,MAAM;GACrB;EAEJ,KAAK;GACD,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MACN,uCAAuC,MAAM,IACjD;GAEJ,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;GAClB;EACJ,KAAK,eACD,OAAO;GACH,IAAI,MAAM;GACV,MAAM,MAAM;EAChB;CACR;AACJ;AAEA,MAAa,WAAW,QAAuB;CAC3C,QAAQ,IAAI,MAAZ;EACI,KAAK,SACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW,IAAI;EACnB;EACJ,KAAK,eACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW;EACf;EACJ,KAAK,eACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ;GACR,WAAW;EACf;CACR;AACJ;A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ACb,CAAC,CAAC,KAAK;EACjB,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,QACK,QAAQ,QAAQ,CAAC,CACjB,YAAY,sCAAsC,CAAC,CACnD,OAAO,YAAY;EAChB,MAAM,KAAK,WAAW,MAAM;EAC5B,MAAM,QAAQ,SAAS,EAAE;EACzB,MAAM,WAAW,MAAM,MAAM,SAAS;EACtC,MAAM,UAAU,MAAM,MAAM,QAAQ;EAEpC,QAAQ,IAAI,wBAAwB,QAAQ;EAC5C,QAAQ,IAAI,uBAAuB,OAAO;EAE1C,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,QACK,QAAQ,OAAO,CAAC,CAChB,YAAY,0CAA0C,CAAC,CACvD,OAAO,YAAY;EAChB,MAAM,KAAK,WAAW,MAAM;EAC5B,MAAM,QAAQ,SAAS,EAAE;EACzB,MAAM,WAAW,MAAM,MAAM,SAAS;EAGtC,KAAK,MAAM,aAAa,SAAS,QAAQ,GACrC,MAAM,MAAM,KAAK,EAAE,IAAI,UAAU,KAAK,CAAC;EAI3C,MAAM,MAAM,GAAG;EACf,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,QACK,QAAQ,WAAW,CAAC,CACpB,YAAY,0BAA0B,CAAC,CACvC,OAAO,YAAY;EAChB,IAAI,CAAC,iBACD,MAAM,IAAI,MACN,wEACJ;EAEJ,MAAM,KAAK,WAAW,MAAM;EAC5B,MAAM,UAAU,IAAI,iBAAiB,MAAM;EAC3C,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,OAAO;AACX"}
1
+ {"version":3,"file":"index.cjs","names":["authSchema","PartyLevelRight","UserLevelRight","assertConnected","resolveSelfIssuedNetworkByAudiences","providerErrors","sql","Database","Kysely","SqliteDialect","CamelCasePlugin","PostgresDialect","Umzug","Command"],"sources":["../src/schema.ts","../src/store-sql.ts","../src/migrator.ts","../src/bootstrap.ts","../src/cli.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n authSchema,\n type Idp,\n type UserId,\n} from '@canton-network/core-wallet-auth'\nimport {\n type Wallet,\n type Transaction,\n type Session,\n type Network,\n type WalletStatus,\n type UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n type MessageRaw,\n type ApiKey,\n} from '@canton-network/core-wallet-store'\n\ninterface MigrationTable {\n name: string\n executedAt: string\n}\n\ninterface IdpTable {\n id: string\n type: 'oauth' | 'self_signed' | 'self_issued'\n issuer: string | null\n configUrl: string | null\n}\n\ninterface NetworkTable {\n id: string\n name: string\n synchronizerId: string | null // retrieved at runtime if null\n description: string\n ledgerApiBaseUrl: string\n identityProviderId: string\n userId: UserId | undefined // global if undefined\n\n auth: string // json stringified\n adminAuth: string | undefined // json stringified\n serviceAccountAuth: string | undefined // json stringified\n}\n\n/**\n * Wallet table schema\n * Primary key on (partyId, networkId, userId)\n * Unique constraint on (networkId, userId) for primary wallet per network per user\n */\ninterface WalletTable {\n primary: number\n partyId: string\n hint: string\n publicKey: string\n namespace: string\n networkId: string\n signingProviderId: string\n userId: UserId\n externalTxId: string | null\n topologyTransactions: string | null\n status: string | null\n disabled: number\n reason: string | null\n isAuthParty: number\n}\ninterface UpdateWalletProperties {\n primary?: number\n externalTxId?: string | null\n topologyTransactions?: string | null\n status?: string | null\n disabled?: number\n reason?: string | null\n isAuthParty?: number\n}\n\ninterface UserPartyRightTable {\n userId: UserId\n networkId: string\n partyId: string\n right: PartyLevelRight\n}\n\ninterface UserRightTable {\n userId: UserId\n networkId: string\n right: UserLevelRight\n}\n\ninterface TransactionTable {\n id: string\n status: string\n commandId: string\n networkId: string\n preparedTransaction: string\n preparedTransactionHash: string\n payload: string | undefined\n origin: string | null\n userId: UserId\n createdAt: string | null\n signedAt: string | null\n externalTxId: string | null\n}\n\ninterface MessageRawTable {\n id: string\n status: string\n partyId: string\n publicKey: string\n message: string\n origin: string | null\n userId: UserId\n networkId: string\n createdAt: string\n signedAt: string | null\n signature: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string | null\n userId: UserId\n}\n\ninterface ApiKeysTable {\n id: string\n digest: string\n name: string\n userId: UserId\n email: string | null\n networkId: string\n createdAt: string\n lastUsedAt: string | null\n}\n\nexport interface DB {\n migrations: MigrationTable\n idps: IdpTable\n networks: NetworkTable\n wallets: WalletTable\n userPartyRights: UserPartyRightTable\n userRights: UserRightTable\n transactions: TransactionTable\n messagesRaw: MessageRawTable\n sessions: SessionTable\n apiKeys: ApiKeysTable\n}\n\nexport const toIdp = (table: IdpTable): Idp => {\n switch (table.type) {\n case 'oauth': {\n if (!table.configUrl) {\n throw new Error(`Missing configUrl for oauth IdP: ${table.id}`)\n }\n if (table.issuer === null) {\n throw new Error(`Missing issuer for oauth IdP: ${table.id}`)\n }\n\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n configUrl: table.configUrl,\n }\n }\n case 'self_signed':\n if (table.issuer === null) {\n throw new Error(\n `Missing issuer for self_signed IdP: ${table.id}`\n )\n }\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n case 'self_issued':\n return {\n id: table.id,\n type: table.type,\n }\n }\n}\n\nexport const fromIdp = (idp: Idp): IdpTable => {\n switch (idp.type) {\n case 'oauth':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: idp.configUrl,\n }\n case 'self_signed':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: null,\n }\n case 'self_issued':\n return {\n id: idp.id,\n type: idp.type,\n issuer: null,\n configUrl: null,\n }\n }\n}\n\nexport const toNetwork = (table: NetworkTable): Network => {\n return {\n name: table.name,\n id: table.id,\n synchronizerId: table.synchronizerId ?? undefined,\n identityProviderId: table.identityProviderId,\n description: table.description,\n ledgerApi: {\n baseUrl: table.ledgerApiBaseUrl,\n },\n auth: authSchema.parse(\n typeof table.auth === 'string' ? JSON.parse(table.auth) : table.auth\n ),\n adminAuth: table.adminAuth\n ? authSchema.parse(\n typeof table.adminAuth === 'string'\n ? JSON.parse(table.adminAuth)\n : table.adminAuth\n )\n : undefined,\n serviceAccountAuth: table.serviceAccountAuth\n ? authSchema.parse(\n typeof table.serviceAccountAuth === 'string'\n ? JSON.parse(table.serviceAccountAuth)\n : table.serviceAccountAuth\n )\n : undefined,\n }\n}\n\nexport const fromNetwork = (\n network: Network,\n userId?: UserId\n): NetworkTable => {\n return {\n name: network.name,\n id: network.id,\n synchronizerId: network.synchronizerId ?? null,\n description: network.description,\n ledgerApiBaseUrl: network.ledgerApi.baseUrl,\n userId: userId,\n identityProviderId: network.identityProviderId,\n auth: JSON.stringify(network.auth),\n adminAuth: network.adminAuth\n ? JSON.stringify(network.adminAuth)\n : undefined,\n serviceAccountAuth: network.serviceAccountAuth\n ? JSON.stringify(network.serviceAccountAuth)\n : undefined,\n }\n}\n\nexport const toSession = (table: SessionTable): Session => {\n return {\n id: table.id,\n network: table.network,\n origin: table.origin,\n ...(table.accessToken ? { accessToken: table.accessToken } : {}),\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, isAuthParty, ...rest } =\n wallet\n void rights\n return {\n ...rest,\n primary: wallet.primary ? 1 : 0,\n userId: userId,\n disabled: wallet.disabled !== undefined && wallet.disabled ? 1 : 0,\n isAuthParty: isAuthParty ? 1 : 0,\n reason: wallet.reason ?? null,\n externalTxId: externalTxId && externalTxId !== '' ? externalTxId : null,\n topologyTransactions:\n topologyTransactions && topologyTransactions !== ''\n ? topologyTransactions\n : null,\n }\n}\n\n// only update fields that are explicitly provided to prevent data loss\nexport const toWalletUpdateProperties = (\n params: UpdateWallet\n): UpdateWalletProperties => {\n const {\n status,\n externalTxId,\n topologyTransactions,\n disabled,\n reason,\n primary,\n signingProviderId,\n publicKey,\n namespace,\n isAuthParty,\n } = params\n return {\n ...(status !== undefined && { status }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(topologyTransactions !== undefined && { topologyTransactions }),\n ...(primary !== undefined && { primary: primary ? 1 : 0 }),\n ...(disabled !== undefined && { disabled: disabled ? 1 : 0 }),\n ...(reason !== undefined && { reason }),\n ...(signingProviderId !== undefined && { signingProviderId }),\n ...(publicKey !== undefined && { publicKey }),\n ...(namespace !== undefined && { namespace }),\n ...(isAuthParty !== undefined && { isAuthParty: isAuthParty ? 1 : 0 }),\n }\n}\n\nexport const toWalletStatus = (status?: string | null): WalletStatus => {\n if (status === 'allocated') return 'allocated'\n if (status === 'removed') return 'removed'\n return 'initialized'\n}\n\nexport const toWallet = (table: WalletTable): Wallet => {\n return {\n primary: Boolean(table.primary),\n status: toWalletStatus(table.status),\n partyId: table.partyId,\n hint: table.hint,\n publicKey: table.publicKey,\n namespace: table.namespace,\n networkId: table.networkId,\n signingProviderId: table.signingProviderId,\n disabled: table.disabled === 1,\n isAuthParty: Boolean(table.isAuthParty),\n userId: table.userId,\n ...(table.externalTxId !== null && {\n externalTxId: table.externalTxId,\n }),\n ...(table.topologyTransactions !== null && {\n topologyTransactions: table.topologyTransactions,\n }),\n ...(table.reason !== null && {\n reason: table.reason,\n }),\n rights: [],\n }\n}\n\nexport const fromPartyRight = (right: string): PartyLevelRight | undefined => {\n if (Object.values(PartyLevelRight).includes(right as PartyLevelRight)) {\n return right as PartyLevelRight\n }\n return undefined\n}\n\nexport const fromUserRight = (right: string): UserLevelRight | undefined => {\n if (Object.values(UserLevelRight).includes(right as UserLevelRight)) {\n return right as UserLevelRight\n }\n return undefined\n}\n\nexport const fromTransaction = (\n transaction: Transaction,\n userId: UserId,\n networkId: string\n): TransactionTable => {\n return {\n ...transaction,\n networkId,\n payload: transaction.payload\n ? JSON.stringify(transaction.payload)\n : undefined,\n origin: transaction.origin || null,\n userId: userId,\n createdAt: transaction.createdAt?.toISOString() || null,\n signedAt: transaction.signedAt?.toISOString() || null,\n externalTxId: transaction.externalTxId ?? null,\n }\n}\n\nexport const toTransaction = (table: TransactionTable): Transaction => {\n const result: Transaction = {\n id: table.id,\n commandId: table.commandId,\n status: table.status as 'pending' | 'signed' | 'executed' | 'failed',\n preparedTransaction: table.preparedTransaction,\n preparedTransactionHash: table.preparedTransactionHash,\n payload: table.payload ? JSON.parse(table.payload) : undefined,\n origin: table.origin || null,\n userId: table.userId,\n networkId: table.networkId,\n }\n\n if (table.createdAt) {\n result.createdAt = new Date(table.createdAt)\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n\n if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n\n return result\n}\n\nexport const fromMessageRaw = (\n message: MessageRaw,\n userId: UserId,\n networkId: string\n): MessageRawTable => {\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n return {\n id: message.id,\n status: message.status,\n userId: message.userId,\n partyId: message.partyId,\n publicKey: message.publicKey,\n message: message.message,\n origin: message.origin || null,\n networkId,\n createdAt: message.createdAt.toISOString(),\n signedAt: message.signedAt?.toISOString() || null,\n signature: message.signature ?? null,\n }\n}\n\nexport const toMessageRaw = (table: MessageRawTable): MessageRaw => {\n const result: MessageRaw = {\n id: table.id,\n status: table.status as MessageRaw['status'],\n userId: table.userId,\n partyId: table.partyId,\n publicKey: table.publicKey,\n message: table.message,\n origin: table.origin || null,\n createdAt: new Date(table.createdAt),\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n if (table.signature) {\n result.signature = table.signature\n }\n\n return result\n}\n\nexport const fromApiKey = (table: ApiKeysTable): ApiKey => {\n return {\n id: table.id,\n digest: table.digest,\n name: table.name,\n userId: table.userId,\n email: table.email,\n networkId: table.networkId,\n createdAt: new Date(table.createdAt),\n lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : undefined,\n }\n}\n\nexport const toApiKey = (apiKey: ApiKey): ApiKeysTable => {\n return {\n id: apiKey.id,\n digest: apiKey.digest,\n name: apiKey.name,\n userId: apiKey.userId,\n email: apiKey.email,\n networkId: apiKey.networkId,\n createdAt: apiKey.createdAt.toISOString(),\n lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null,\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Logger } from 'pino'\nimport {\n type AuthContext,\n type UserId,\n type AuthAware,\n assertConnected,\n type Idp,\n} from '@canton-network/core-wallet-auth'\nimport { providerErrors } from '@canton-network/core-rpc-errors'\nimport type {\n Store as BaseStore,\n Wallet,\n PartyId,\n Session,\n WalletFilter,\n Transaction,\n MessageRaw,\n MessageRawStatusUpdate,\n Network,\n StoreConfig,\n UpdateWallet,\n CurrentNetworkWalletFilter,\n PartyLevelRight,\n TransactionStatusUpdate,\n UserLevelRight,\n ApiKey,\n ListTransactionsOptions,\n WalletUniqueConstraint,\n} from '@canton-network/core-wallet-store'\nimport {\n assertUniqueSelfIssuedAudience,\n resolveSelfIssuedNetworkByAudiences,\n} from '@canton-network/core-wallet-store'\nimport {\n CamelCasePlugin,\n Kysely,\n PostgresDialect,\n SqliteDialect,\n sql,\n} from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n type DB,\n fromIdp,\n fromNetwork,\n fromTransaction,\n fromMessageRaw,\n fromWallet,\n fromPartyRight,\n fromUserRight,\n toWalletUpdateProperties,\n toIdp,\n toNetwork,\n toTransaction,\n toMessageRaw,\n toWallet,\n fromApiKey,\n toApiKey,\n toSession,\n} from './schema.js'\nimport pg from 'pg'\nimport type { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n private logger: Logger,\n authContext?: AuthContext\n ) {\n this.logger = logger.child({ component: 'StoreSql' })\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, this.logger, context)\n }\n\n private assertConnected(): UserId {\n return assertConnected(this.authContext).userId\n }\n\n // Wallet methods\n\n async getAllWallets(filter: WalletFilter = {}): Promise<Array<Wallet>> {\n const userId = this.assertConnected()\n const { networkIds, signingProviderIds } = filter\n const networkIdSet = networkIds ? new Set(networkIds) : null\n const signingProviderIdSet = signingProviderIds\n ? new Set(signingProviderIds)\n : null\n\n const wallets = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const userPartyRights = await this.db\n .selectFrom('userPartyRights')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const rightsByWallet = new Map<string, PartyLevelRight[]>()\n for (const row of userPartyRights) {\n const right = fromPartyRight(row.right)\n if (!right) continue\n const key = `${row.partyId}:${row.networkId}`\n const existing = rightsByWallet.get(key) ?? []\n rightsByWallet.set(key, [...existing, right])\n }\n\n return wallets\n .filter((wallet) => {\n const matchedNetworkIds = networkIdSet\n ? networkIdSet.has(wallet.networkId)\n : true\n const matchedSigningProviderIds = signingProviderIdSet\n ? signingProviderIdSet.has(wallet.signingProviderId)\n : true\n return matchedNetworkIds && matchedSigningProviderIds\n })\n .map((table) => {\n const wallet = toWallet(table)\n const rights = rightsByWallet.get(\n `${table.partyId}:${table.networkId}`\n )\n return {\n ...wallet,\n rights: rights ?? [],\n }\n })\n }\n\n async getWallets(\n filter: CurrentNetworkWalletFilter = {}\n ): Promise<Array<Wallet>> {\n const network = await this.getCurrentNetwork()\n return this.getAllWallets({\n ...filter,\n networkIds: [network.id],\n })\n }\n\n async getWallet(partyId: PartyId): Promise<Wallet | null> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const constraint: WalletUniqueConstraint = {\n partyId,\n networkId: network.id,\n userId,\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where((eb) => eb.and(constraint))\n .executeTakeFirst()\n\n if (!row) return null\n\n const rightRows = await this.db\n .selectFrom('userPartyRights')\n .select('right')\n .where((eb) => eb.and(constraint))\n .execute()\n\n return {\n ...toWallet(row),\n rights: rightRows\n .map(({ right }) => fromPartyRight(right))\n .filter((right) => right !== undefined),\n }\n }\n\n async getWalletByJwt(\n userId: string,\n partyId: PartyId,\n audiences: string[]\n ): Promise<Wallet | undefined> {\n const networks = (\n await this.db.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n const network = resolveSelfIssuedNetworkByAudiences(networks, audiences)\n if (!network) {\n return undefined\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .where('partyId', '=', partyId)\n .where('networkId', '=', network.id)\n .executeTakeFirst()\n\n return row ? toWallet(row) : undefined\n }\n\n async getPrimaryWallet(): Promise<Wallet | undefined> {\n const wallets = await this.getWallets()\n return wallets.find((w) => w.primary === true)\n }\n\n async setPrimaryWallet(partyId: PartyId): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n const wallets = await this.getWallets()\n\n if (!wallets.some((w) => w.partyId === partyId)) {\n throw new Error(\n `Wallet with partyId \"${partyId}\" not found in network \"${network.id}\"`\n )\n }\n\n const primary = wallets.find((w) => w.primary === true)\n\n await this.db.transaction().execute(async (trx) => {\n if (primary) {\n // Unset primary for current network only\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', primary.partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n // Set new primary for current network\n await trx\n .updateTable('wallets')\n .set({ primary: 1 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async addWallet(wallet: Wallet): Promise<void> {\n this.logger.info('Adding wallet')\n const userId = this.assertConnected()\n\n const wallets = await this.getWallets()\n if (\n wallets.some(\n (w) =>\n w.partyId === wallet.partyId &&\n w.networkId === wallet.networkId\n )\n ) {\n throw new Error(\n `Wallet with partyId \"${wallet.partyId}\" networkId \"${wallet.networkId}\" userId \"${userId}\" already exists`\n )\n }\n\n if (\n !wallet.disabled &&\n wallet.status === 'allocated' &&\n !wallets.some((wallet) => wallet.primary)\n ) {\n // If there is no primary wallet yet, set current one as primary (unless disabled or not allocated).\n // In regular case it would be the first added wallet.\n wallet.primary = true\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (wallet.primary) {\n // If the new wallet is primary, set all others in the same network and for this user to non-primary\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('primary', '=', 1),\n eb('networkId', '=', wallet.networkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n await trx\n .insertInto('wallets')\n .values(fromWallet(wallet, userId))\n .execute()\n\n if (wallet.rights && wallet.rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n wallet.rights.map((right) => ({\n userId,\n networkId: wallet.networkId,\n partyId: wallet.partyId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n async updateWallet(params: UpdateWallet): Promise<void> {\n const { partyId, networkId, rights } = params\n this.logger.info('Updating wallet')\n const userId = this.assertConnected()\n\n const updates = toWalletUpdateProperties(params)\n\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n if (Object.keys(updates).length === 0 && rights === undefined) return\n\n await this.db.transaction().execute(async (trx) => {\n if (Object.keys(updates).length > 0) {\n await trx\n .updateTable('wallets')\n .set(updates)\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n\n if (rights !== undefined) {\n await trx\n .deleteFrom('userPartyRights')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId: targetNetworkId,\n partyId,\n right,\n }))\n )\n .execute()\n }\n }\n })\n }\n\n async removeWallet(partyId: PartyId): Promise<void> {\n this.logger.info('Removing wallet')\n const userId = this.assertConnected()\n\n // Remove wallet from current network only\n const network = await this.getCurrentNetwork()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('wallets')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async getUserRights(networkId?: string): Promise<Array<UserLevelRight>> {\n const userId = this.assertConnected()\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n const rows = await this.db\n .selectFrom('userRights')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', targetNetworkId),\n ])\n )\n .execute()\n\n return rows\n .map((row) => fromUserRight(row.right))\n .filter((right): right is UserLevelRight => right !== undefined)\n }\n\n async setUserRights(\n networkId: string,\n rights: Array<UserLevelRight>\n ): Promise<void> {\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('userRights')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', networkId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n // Session methods\n async getSession(accessToken: AccessToken): Promise<Session | undefined> {\n const userId = this.assertConnected()\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async listSessions(): Promise<Array<Session>> {\n const userId = this.assertConnected()\n const rows = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n return rows.map((row) => toSession(row))\n }\n\n async setSession(session: Session): Promise<void> {\n const userId = this.assertConnected()\n\n if (!session.origin) {\n throw new Error('Session origin is required')\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (session.accessToken) {\n // Regular session - one user can have only one session per origin.\n // Tokenless sessions are not replaced by duplicates.\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n eb('accessToken', 'is not', null),\n ])\n )\n .execute()\n this.logger.debug(deleted, 'Deleted old session')\n }\n\n const inserted = await trx\n .insertInto('sessions')\n .values({\n ...session,\n accessToken: session.accessToken ?? null,\n userId,\n })\n .execute()\n\n this.logger.debug(inserted, 'Inserted new session')\n })\n }\n\n async getOnboardingSession(\n sessionId: string\n ): Promise<Session | undefined> {\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async upgradeOnboardingSession(\n sessionId: string,\n accessToken: AccessToken\n ): Promise<Session> {\n const userId = this.assertConnected()\n\n return this.db.transaction().execute(async (trx) => {\n const row = await trx\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('userId', '=', userId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n if (!row) {\n throw new Error('Onboarding session not found')\n }\n\n await trx\n .deleteFrom('sessions')\n .where('userId', '=', userId)\n .where('origin', '=', row.origin)\n .where('id', '!=', sessionId)\n .execute()\n await trx\n .updateTable('sessions')\n .set({ accessToken })\n .where('id', '=', sessionId)\n .execute()\n\n return toSession({ ...row, accessToken })\n })\n }\n\n async removeSession(accessToken: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .execute()\n }\n\n /**\n * Lists all pending transactions across all users.\n */\n\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.or([\n eb('status', '=', 'pending'),\n eb('status', '=', 'awaiting-signature'),\n ])\n )\n .execute()\n\n return rows.map((row) => toTransaction(row))\n }\n\n // IDP methods\n\n async getIdp(idpId: string): Promise<Idp> {\n const idps = await this.listIdps()\n if (!idps) throw new Error('No IDPs available')\n\n const idp = idps.find((n) => n.id === idpId)\n if (!idp) throw new Error(`IDP \"${idpId}\" not found`)\n return idp\n }\n\n async listIdps(): Promise<Array<Idp>> {\n // All IDPs are global for now -- TO-DO: user-specific IDPs\n const query = this.db.selectFrom('idps').selectAll()\n\n const idps = await query.execute()\n return idps.map((table) => toIdp(table))\n }\n\n async updateIdp(idp: Idp): Promise<void> {\n // todo: check and compare userid of existing idp\n await this.db.transaction().execute(async (trx) => {\n const idpEntry = fromIdp(idp)\n this.logger.info(idpEntry, 'Updating idp table')\n await trx\n .updateTable('idps')\n .set(idpEntry)\n .where('id', '=', idp.id)\n .execute()\n })\n }\n\n async addIdp(idp: Idp): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n const idpAlreadyExists = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idp.id)\n .executeTakeFirst()\n if (idpAlreadyExists) {\n throw new Error(`IDP ${idp.id} already exists`)\n } else {\n await trx.insertInto('idps').values(fromIdp(idp)).execute()\n }\n })\n }\n\n async removeIdp(idpId: string): Promise<void> {\n const networks = await this.listNetworks()\n if (networks.some((n) => n.identityProviderId === idpId)) {\n throw new Error(\n `Cannot delete IDP ${idpId} as it is in use by existing networks`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const idp = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idpId)\n .executeTakeFirst()\n if (!idp) {\n throw new Error(`IDP ${idpId} does not exists`)\n }\n await trx.deleteFrom('idps').where('id', '=', idpId).execute()\n })\n }\n\n // Network methods\n async getNetwork(networkId: string): Promise<Network> {\n const networks = await this.listNetworks()\n if (!networks) throw new Error('No networks available')\n\n const network = networks.find((n) => n.id === networkId)\n if (!network) throw new Error(`Network \"${networkId}\" not found`)\n return network\n }\n\n async getCurrentNetwork(): Promise<Network> {\n const userId = this.assertConnected()\n const token = this.authContext?.accessToken\n const onboardingSessionId =\n this.authContext && !this.authContext.isApiKey\n ? this.authContext.sessionId\n : undefined\n if (!token && !onboardingSessionId) {\n throw providerErrors.unauthorized({ message: 'No session found' })\n }\n\n const sessionRow = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .where((eb) =>\n token\n ? eb('accessToken', '=', token)\n : eb.and([\n eb('id', '=', onboardingSessionId!),\n eb('accessToken', 'is', null),\n ])\n )\n .executeTakeFirst()\n if (!sessionRow) {\n throw providerErrors.unauthorized({ message: 'No session found' })\n }\n\n const session = toSession(sessionRow)\n const networkId = session.network\n if (!networkId) {\n throw new Error('No current network set in session')\n }\n\n const networks = await this.listNetworks()\n const network = networks.find((n) => n.id === networkId)\n if (!network) {\n throw new Error(`Network \"${networkId}\" not found`)\n }\n return network\n }\n\n async getNetworkForTokenVerification(\n networkId: string\n ): Promise<Network | undefined> {\n // Not scoped by userId: key id resolution happens during token\n // verification, before there is an authenticated user.\n const row = await this.db\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!row) return undefined\n\n const network = toNetwork(row)\n return network.auth.method === 'self_signed' ? network : undefined\n }\n\n async listNetworks(): Promise<Array<Network>> {\n let query = this.db.selectFrom('networks').selectAll()\n\n if (this.authContext) {\n const userId = this.assertConnected()\n query = query.where((eb) =>\n eb.or([\n eb('userId', 'is', null), // Global networks\n eb('userId', '=', userId), // User-specific networks\n ])\n )\n } else {\n query = query.where('userId', 'is', null) // Only global networks\n }\n\n const networks = await query.execute()\n return networks.map((table) => toNetwork(table))\n }\n\n async updateNetwork(network: Network): Promise<void> {\n // todo: check and compare idpId of existing network\n this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const existing = (\n await trx.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n assertUniqueSelfIssuedAudience(existing, network, network.id)\n\n // we do not set a userId for now and leave all networks global when updating\n const networkEntry = fromNetwork(network, undefined)\n this.logger.info(networkEntry, 'Updating network table')\n await trx\n .updateTable('networks')\n .set(networkEntry)\n .where('id', '=', network.id)\n .execute()\n })\n }\n\n async addNetwork(network: Network): Promise<void> {\n const userId = this.authContext?.userId\n const idps = await this.listIdps()\n const networkIdp = idps.find(\n (idp) => idp.id === network.identityProviderId\n )\n\n if (!networkIdp) {\n throw new Error(\n `Identity provider \"${network.identityProviderId}\" not found`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const networkAlreadyExists = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', network.id)\n .executeTakeFirst()\n if (networkAlreadyExists) {\n throw new Error(`Network ${network.id} already exists`)\n }\n\n const existing = (\n await trx.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n assertUniqueSelfIssuedAudience(existing, network)\n\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\n })\n }\n\n async removeNetwork(networkId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const network = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!network) {\n throw new Error(`Network ${networkId} does not exists`)\n }\n if (network.userId !== userId) {\n throw new Error(\n `Network ${networkId} is not owned by user ${userId}`\n )\n }\n await trx\n .deleteFrom('networks')\n .where('id', '=', networkId)\n .execute()\n })\n }\n\n private mergeTransactionStatusUpdate(\n existing: Transaction,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Transaction {\n const payload = updates.payload ?? existing.payload\n const signedAt = updates.signedAt ?? existing.signedAt\n const externalTxId = updates.externalTxId ?? existing.externalTxId\n const failureReason = updates.failureReason ?? existing.failureReason\n\n return {\n id: existing.id,\n commandId: existing.commandId,\n status,\n preparedTransaction: existing.preparedTransaction,\n preparedTransactionHash: existing.preparedTransactionHash,\n origin: existing.origin,\n ...(payload !== undefined && { payload }),\n ...(existing.createdAt !== undefined && {\n createdAt: existing.createdAt,\n }),\n ...(signedAt !== undefined && { signedAt }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(failureReason !== undefined && { failureReason }),\n }\n }\n\n // Transaction methods\n async setTransaction(transaction: Transaction): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n await this.db\n .insertInto('transactions')\n .values(fromTransaction(transaction, userId, network.id))\n .execute()\n }\n\n async setTransactionSigned(\n transactionId: string,\n signedAt: Date,\n externalTxId?: string,\n opts?: { expectedStatus: Transaction['status'] }\n ): Promise<boolean> {\n return await this.setTransactionStatus(\n transactionId,\n 'signed',\n {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n },\n opts\n )\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {},\n opts?: { expectedStatus?: Transaction['status'] }\n ): Promise<boolean> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getTransaction(transactionId)\n if (!existing) {\n throw new Error(`Transaction not found with id: ${transactionId}`)\n }\n if (opts?.expectedStatus && existing.status !== opts.expectedStatus) {\n return false\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n const res = await this.db\n .updateTable('transactions')\n .set(fromTransaction(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ...(opts?.expectedStatus\n ? [eb('status', '=', opts.expectedStatus)]\n : []),\n ])\n )\n .executeTakeFirst()\n\n return res.numUpdatedRows > 0n\n }\n\n async getTransaction(\n transactionId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async getLatestTransactionByCommandId(\n commandId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('commandId', '=', commandId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .executeTakeFirst()\n\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async transactionsCount(): Promise<number> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n const result = await this.db\n .selectFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .select((eb) => eb.fn.count<number>('id').as('count'))\n .executeTakeFirstOrThrow()\n\n return Number(result.count)\n }\n\n async listTransactions(options?: ListTransactionsOptions) {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const { cursor, limit } = options ?? {}\n const lim = limit ? Math.min(limit, 100) : 100\n\n let query = this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .orderBy('id', 'desc')\n .limit(lim + 1)\n\n if (cursor) {\n const split = cursor.split('::')\n const dateString = split[0] === 'null' ? null : split[0]\n const cursorId = split[1]\n\n query = query.where((eb) => {\n if (dateString === null) {\n return eb.and([\n eb('createdAt', 'is', null),\n eb('id', '<', cursorId),\n ])\n }\n\n return eb.or([\n eb('createdAt', '<', dateString),\n eb.and([\n eb('createdAt', '=', dateString),\n eb('id', '<', split[1]),\n ]),\n eb('createdAt', 'is', null),\n ])\n })\n }\n\n const rows = await query.execute()\n const txs = rows.map((r) => toTransaction(r))\n\n const hasNextPage = txs.length > lim\n if (hasNextPage) {\n txs.pop()\n }\n\n if (txs.length === 0) {\n return {\n transactions: [],\n nextCursor: null,\n }\n }\n\n const lastTx = txs[txs.length - 1]\n if (lastTx === undefined) {\n return {\n transactions: txs,\n nextCursor: null,\n }\n }\n\n //handle case for if timestamp is null\n if (lastTx.createdAt) {\n const d = new Date(lastTx.createdAt).toISOString()\n const nextCursor = hasNextPage ? `${d}::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n } else {\n const nextCursor = hasNextPage ? `null::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n }\n }\n\n async removeTransaction(transactionId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n private mergeMessageRawStatusUpdate(\n existing: MessageRaw,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): MessageRaw {\n const signedAt = updates.signedAt ?? existing.signedAt\n const signature = updates.signature ?? existing.signature\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n }\n }\n\n // Message signing request methods\n async setMessageRaw(message: MessageRaw): Promise<void> {\n const userId = this.assertConnected()\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n const network = await this.getCurrentNetwork()\n await this.db\n .insertInto('messagesRaw')\n .values(fromMessageRaw(message, userId, network.id))\n .execute()\n }\n\n async setMessageRawStatus(\n messageId: string,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getMessageRaw(messageId)\n if (!existing) {\n throw new Error(`MessageRaw not found with id: ${messageId}`)\n }\n\n const updated = this.mergeMessageRawStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('messagesRaw')\n .set(fromMessageRaw(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getMessageRaw(messageId: string): Promise<MessageRaw | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const message = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return message ? toMessageRaw(message) : undefined\n }\n\n async listMessageRaws(): Promise<Array<MessageRaw>> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const messages = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .execute()\n return messages.map((m) => toMessageRaw(m))\n }\n\n async removeMessageRaw(messageId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('messagesRaw')\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n // API keys\n async addApiKey(apiKey: ApiKey): Promise<void> {\n const userId = this.assertConnected()\n if (apiKey.userId !== userId) {\n throw new Error(\n `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`\n )\n }\n\n const network = await this.getCurrentNetwork()\n if (apiKey.networkId !== network.id) {\n throw new Error(\n `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`\n )\n }\n\n await this.db.insertInto('apiKeys').values(toApiKey(apiKey)).execute()\n }\n\n async listApiKeys(): Promise<Array<ApiKey>> {\n const query = this.db\n .selectFrom('apiKeys')\n .selectAll()\n .orderBy('createdAt', 'desc')\n\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const apiKeys = await query\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n\n return apiKeys.map(fromApiKey)\n }\n\n async getApiKey(digest: string): Promise<ApiKey | undefined> {\n const apiKey = await this.db\n .selectFrom('apiKeys')\n .selectAll()\n .where((eb) => eb('digest', '=', digest))\n .executeTakeFirst()\n\n return apiKey ? fromApiKey(apiKey) : undefined\n }\n\n async removeApiKey(apiKeyId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('apiKeys')\n .where((eb) =>\n eb.and([\n eb('id', '=', apiKeyId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n}\n\nexport const connection = (config: StoreConfig) => {\n let database\n switch (config.connection.type) {\n case 'sqlite':\n database = new Database(config.connection.database)\n // normally sqlite3 has foreign_keys = OFF for each connection,\n // but better-sqlite3 uses custom build with compile flag SQLITE_DEFAULT_FOREIGN_KEYS=1,\n // making it ON by default.\n // Set explicitly ON anyway as redundancy\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'postgres':\n return new Kysely<DB>({\n dialect: new PostgresDialect({\n pool: new pg.Pool(config.connection),\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'memory':\n database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Umzug, type MigrationMeta, type UmzugStorage } from 'umzug'\nimport type { Kysely } from 'kysely'\nimport type { DB } from './schema'\n\nclass KyselyStorage implements UmzugStorage {\n constructor(private db: Kysely<DB>) {}\n\n private async ensureTable() {\n await this.db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'text', (col) => col.primaryKey())\n .addColumn('executedAt', 'text', (col) => col.notNull())\n .execute()\n }\n\n async executed(): Promise<string[]> {\n await this.ensureTable()\n const rows = await this.db\n .selectFrom('migrations')\n .select('name')\n .execute()\n return rows.map((r) => r.name)\n }\n\n async logMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .insertInto('migrations')\n .values({ name, executedAt: new Date().toISOString() })\n .execute()\n }\n\n async unlogMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute()\n }\n}\n\nexport const migrator = (db: Kysely<DB>) => {\n const ext = import.meta.url.endsWith('.ts') ? 'ts' : 'js'\n const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname\n return new Umzug({\n migrations: {\n glob: glob,\n resolve: ({ name, path, context }) => {\n // Dynamic import for ESM\n return {\n name,\n up: async () => {\n console.log(path)\n const { up } = await import(path!)\n return up(context)\n },\n down: async () => {\n const { down } = await import(path!)\n return down(context)\n },\n }\n },\n },\n context: db,\n storage: new KyselyStorage(db),\n logger: console,\n })\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport type { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport type { Logger } from 'pino'\nimport type { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig,\n logger: Logger\n): Promise<void> {\n const store = new StoreSql(db, logger)\n\n // Load all IDPs from config into the store\n await Promise.all(config.idps.map((idp) => store.addIdp(idp)))\n\n // Load all networks from config into the store\n await Promise.all(\n config.networks.map((network) => store.addNetwork(network))\n )\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Command } from 'commander'\nimport { connection } from './store-sql.js'\nimport { migrator } from './migrator.js'\nimport type {\n StoreConfig,\n BootstrapConfig,\n} from '@canton-network/core-wallet-store'\nimport { pino } from 'pino'\nimport { bootstrap } from './bootstrap.js'\n\nconst logger = pino({ name: 'main', level: 'debug' })\n\nexport function createCLI(\n config: StoreConfig,\n bootstrapConfig?: BootstrapConfig\n): Command {\n const program = new Command()\n\n program\n .command('up')\n .description('Run all pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('down')\n .description('Rollback last migration')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.down()\n await db.destroy()\n })\n\n program\n .command('status')\n .description('Show executed and pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n const pending = await umzug.pending()\n\n console.log('Executed migrations:', executed)\n console.log('Pending migrations:', pending)\n\n await db.destroy()\n })\n\n program\n .command('reset')\n .description('Rollback all migrations and reapply them')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n\n // Rollback all executed migrations in reverse order\n for (const migration of executed.reverse()) {\n await umzug.down({ to: migration.name })\n }\n\n // Reapply all migrations\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('bootstrap')\n .description('Bootstrap DB from config')\n .action(async () => {\n if (!bootstrapConfig) {\n throw new Error(\n 'Bootstrap config (idps/networks) is required for the bootstrap command'\n )\n }\n const db = connection(config)\n await bootstrap(db, bootstrapConfig, logger)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAElE,I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iB,MAAM;EAC3C,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,OAAO;AACX"}
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";
@@ -232,7 +233,7 @@ const toApiKey = (apiKey) => {
232
233
  };
233
234
  };
234
235
  //#endregion
235
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/typeof.js
236
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/typeof.js
236
237
  function _typeof(o) {
237
238
  "@babel/helpers - typeof";
238
239
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -242,7 +243,7 @@ function _typeof(o) {
242
243
  }, _typeof(o);
243
244
  }
244
245
  //#endregion
245
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/toPrimitive.js
246
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPrimitive.js
246
247
  function toPrimitive(t, r) {
247
248
  if ("object" != _typeof(t) || !t) return t;
248
249
  var e = t[Symbol.toPrimitive];
@@ -254,13 +255,13 @@ function toPrimitive(t, r) {
254
255
  return ("string" === r ? String : Number)(t);
255
256
  }
256
257
  //#endregion
257
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/toPropertyKey.js
258
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPropertyKey.js
258
259
  function toPropertyKey(t) {
259
260
  var i = toPrimitive(t, "string");
260
261
  return "symbol" == _typeof(i) ? i : i + "";
261
262
  }
262
263
  //#endregion
263
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/defineProperty.js
264
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/defineProperty.js
264
265
  function _defineProperty(e, r, t) {
265
266
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
266
267
  value: t,
@@ -335,6 +336,13 @@ var StoreSql = class StoreSql {
335
336
  rights: rightRows.map(({ right }) => fromPartyRight(right)).filter((right) => right !== void 0)
336
337
  };
337
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
+ }
338
346
  async getPrimaryWallet() {
339
347
  return (await this.getWallets()).find((w) => w.primary === true);
340
348
  }
@@ -531,9 +539,9 @@ var StoreSql = class StoreSql {
531
539
  const userId = this.assertConnected();
532
540
  const token = this.authContext?.accessToken;
533
541
  const onboardingSessionId = this.authContext && !this.authContext.isApiKey ? this.authContext.sessionId : void 0;
534
- if (!token && !onboardingSessionId) throw new Error("No session found");
542
+ if (!token && !onboardingSessionId) throw providerErrors.unauthorized({ message: "No session found" });
535
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();
536
- if (!sessionRow) throw new Error("No session found");
544
+ if (!sessionRow) throw providerErrors.unauthorized({ message: "No session found" });
537
545
  const networkId = toSession(sessionRow).network;
538
546
  if (!networkId) throw new Error("No current network set in session");
539
547
  const network = (await this.listNetworks()).find((n) => n.id === networkId);
@@ -557,6 +565,8 @@ var StoreSql = class StoreSql {
557
565
  async updateNetwork(network) {
558
566
  this.assertConnected();
559
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);
560
570
  const networkEntry = fromNetwork(network, void 0);
561
571
  this.logger.info(networkEntry, "Updating network table");
562
572
  await trx.updateTable("networks").set(networkEntry).where("id", "=", network.id).execute();
@@ -567,7 +577,9 @@ var StoreSql = class StoreSql {
567
577
  if (!(await this.listIdps()).find((idp) => idp.id === network.identityProviderId)) throw new Error(`Identity provider "${network.identityProviderId}" not found`);
568
578
  await this.db.transaction().execute(async (trx) => {
569
579
  if (await trx.selectFrom("networks").selectAll().where("id", "=", network.id).executeTakeFirst()) throw new Error(`Network ${network.id} already exists`);
570
- 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();
571
583
  });
572
584
  }
573
585
  async removeNetwork(networkId) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/schema.ts","../src/store-sql.ts","../src/migrator.ts","../src/bootstrap.ts","../src/cli.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n authSchema,\n type Idp,\n type UserId,\n} from '@canton-network/core-wallet-auth'\nimport {\n type Wallet,\n type Transaction,\n type Session,\n type Network,\n type WalletStatus,\n type UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n type MessageRaw,\n type ApiKey,\n} from '@canton-network/core-wallet-store'\n\ninterface MigrationTable {\n name: string\n executedAt: string\n}\n\ninterface IdpTable {\n id: string\n type: 'oauth' | 'self_signed' | 'self_issued'\n issuer: string | null\n configUrl: string | null\n}\n\ninterface NetworkTable {\n id: string\n name: string\n synchronizerId: string | null // retrieved at runtime if null\n description: string\n ledgerApiBaseUrl: string\n identityProviderId: string\n userId: UserId | undefined // global if undefined\n\n auth: string // json stringified\n adminAuth: string | undefined // json stringified\n serviceAccountAuth: string | undefined // json stringified\n}\n\n/**\n * Wallet table schema\n * Primary key on (partyId, networkId, userId)\n * Unique constraint on (networkId, userId) for primary wallet per network per user\n */\ninterface WalletTable {\n primary: number\n partyId: string\n hint: string\n publicKey: string\n namespace: string\n networkId: string\n signingProviderId: string\n userId: UserId\n externalTxId: string | null\n topologyTransactions: string | null\n status: string | null\n disabled: number\n reason: string | null\n isAuthParty: number\n}\ninterface UpdateWalletProperties {\n primary?: number\n externalTxId?: string | null\n topologyTransactions?: string | null\n status?: string | null\n disabled?: number\n reason?: string | null\n isAuthParty?: number\n}\n\ninterface UserPartyRightTable {\n userId: UserId\n networkId: string\n partyId: string\n right: PartyLevelRight\n}\n\ninterface UserRightTable {\n userId: UserId\n networkId: string\n right: UserLevelRight\n}\n\ninterface TransactionTable {\n id: string\n status: string\n commandId: string\n networkId: string\n preparedTransaction: string\n preparedTransactionHash: string\n payload: string | undefined\n origin: string | null\n userId: UserId\n createdAt: string | null\n signedAt: string | null\n externalTxId: string | null\n}\n\ninterface MessageRawTable {\n id: string\n status: string\n partyId: string\n publicKey: string\n message: string\n origin: string | null\n userId: UserId\n networkId: string\n createdAt: string\n signedAt: string | null\n signature: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string | null\n userId: UserId\n}\n\ninterface ApiKeysTable {\n id: string\n digest: string\n name: string\n userId: UserId\n email: string | null\n networkId: string\n createdAt: string\n lastUsedAt: string | null\n}\n\nexport interface DB {\n migrations: MigrationTable\n idps: IdpTable\n networks: NetworkTable\n wallets: WalletTable\n userPartyRights: UserPartyRightTable\n userRights: UserRightTable\n transactions: TransactionTable\n messagesRaw: MessageRawTable\n sessions: SessionTable\n apiKeys: ApiKeysTable\n}\n\nexport const toIdp = (table: IdpTable): Idp => {\n switch (table.type) {\n case 'oauth': {\n if (!table.configUrl) {\n throw new Error(`Missing configUrl for oauth IdP: ${table.id}`)\n }\n if (table.issuer === null) {\n throw new Error(`Missing issuer for oauth IdP: ${table.id}`)\n }\n\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n configUrl: table.configUrl,\n }\n }\n case 'self_signed':\n if (table.issuer === null) {\n throw new Error(\n `Missing issuer for self_signed IdP: ${table.id}`\n )\n }\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n case 'self_issued':\n return {\n id: table.id,\n type: table.type,\n }\n }\n}\n\nexport const fromIdp = (idp: Idp): IdpTable => {\n switch (idp.type) {\n case 'oauth':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: idp.configUrl,\n }\n case 'self_signed':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: null,\n }\n case 'self_issued':\n return {\n id: idp.id,\n type: idp.type,\n issuer: null,\n configUrl: null,\n }\n }\n}\n\nexport const toNetwork = (table: NetworkTable): Network => {\n return {\n name: table.name,\n id: table.id,\n synchronizerId: table.synchronizerId ?? undefined,\n identityProviderId: table.identityProviderId,\n description: table.description,\n ledgerApi: {\n baseUrl: table.ledgerApiBaseUrl,\n },\n auth: authSchema.parse(\n typeof table.auth === 'string' ? JSON.parse(table.auth) : table.auth\n ),\n adminAuth: table.adminAuth\n ? authSchema.parse(\n typeof table.adminAuth === 'string'\n ? JSON.parse(table.adminAuth)\n : table.adminAuth\n )\n : undefined,\n serviceAccountAuth: table.serviceAccountAuth\n ? authSchema.parse(\n typeof table.serviceAccountAuth === 'string'\n ? JSON.parse(table.serviceAccountAuth)\n : table.serviceAccountAuth\n )\n : undefined,\n }\n}\n\nexport const fromNetwork = (\n network: Network,\n userId?: UserId\n): NetworkTable => {\n return {\n name: network.name,\n id: network.id,\n synchronizerId: network.synchronizerId ?? null,\n description: network.description,\n ledgerApiBaseUrl: network.ledgerApi.baseUrl,\n userId: userId,\n identityProviderId: network.identityProviderId,\n auth: JSON.stringify(network.auth),\n adminAuth: network.adminAuth\n ? JSON.stringify(network.adminAuth)\n : undefined,\n serviceAccountAuth: network.serviceAccountAuth\n ? JSON.stringify(network.serviceAccountAuth)\n : undefined,\n }\n}\n\nexport const toSession = (table: SessionTable): Session => {\n return {\n id: table.id,\n network: table.network,\n origin: table.origin,\n ...(table.accessToken ? { accessToken: table.accessToken } : {}),\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, isAuthParty, ...rest } =\n wallet\n void rights\n return {\n ...rest,\n primary: wallet.primary ? 1 : 0,\n userId: userId,\n disabled: wallet.disabled !== undefined && wallet.disabled ? 1 : 0,\n isAuthParty: isAuthParty ? 1 : 0,\n reason: wallet.reason ?? null,\n externalTxId: externalTxId && externalTxId !== '' ? externalTxId : null,\n topologyTransactions:\n topologyTransactions && topologyTransactions !== ''\n ? topologyTransactions\n : null,\n }\n}\n\n// only update fields that are explicitly provided to prevent data loss\nexport const toWalletUpdateProperties = (\n params: UpdateWallet\n): UpdateWalletProperties => {\n const {\n status,\n externalTxId,\n topologyTransactions,\n disabled,\n reason,\n primary,\n signingProviderId,\n publicKey,\n namespace,\n isAuthParty,\n } = params\n return {\n ...(status !== undefined && { status }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(topologyTransactions !== undefined && { topologyTransactions }),\n ...(primary !== undefined && { primary: primary ? 1 : 0 }),\n ...(disabled !== undefined && { disabled: disabled ? 1 : 0 }),\n ...(reason !== undefined && { reason }),\n ...(signingProviderId !== undefined && { signingProviderId }),\n ...(publicKey !== undefined && { publicKey }),\n ...(namespace !== undefined && { namespace }),\n ...(isAuthParty !== undefined && { isAuthParty: isAuthParty ? 1 : 0 }),\n }\n}\n\nexport const toWalletStatus = (status?: string | null): WalletStatus => {\n if (status === 'allocated') return 'allocated'\n if (status === 'removed') return 'removed'\n return 'initialized'\n}\n\nexport const toWallet = (table: WalletTable): Wallet => {\n return {\n primary: Boolean(table.primary),\n status: toWalletStatus(table.status),\n partyId: table.partyId,\n hint: table.hint,\n publicKey: table.publicKey,\n namespace: table.namespace,\n networkId: table.networkId,\n signingProviderId: table.signingProviderId,\n disabled: table.disabled === 1,\n isAuthParty: Boolean(table.isAuthParty),\n userId: table.userId,\n ...(table.externalTxId !== null && {\n externalTxId: table.externalTxId,\n }),\n ...(table.topologyTransactions !== null && {\n topologyTransactions: table.topologyTransactions,\n }),\n ...(table.reason !== null && {\n reason: table.reason,\n }),\n rights: [],\n }\n}\n\nexport const fromPartyRight = (right: string): PartyLevelRight | undefined => {\n if (Object.values(PartyLevelRight).includes(right as PartyLevelRight)) {\n return right as PartyLevelRight\n }\n return undefined\n}\n\nexport const fromUserRight = (right: string): UserLevelRight | undefined => {\n if (Object.values(UserLevelRight).includes(right as UserLevelRight)) {\n return right as UserLevelRight\n }\n return undefined\n}\n\nexport const fromTransaction = (\n transaction: Transaction,\n userId: UserId,\n networkId: string\n): TransactionTable => {\n return {\n ...transaction,\n networkId,\n payload: transaction.payload\n ? JSON.stringify(transaction.payload)\n : undefined,\n origin: transaction.origin || null,\n userId: userId,\n createdAt: transaction.createdAt?.toISOString() || null,\n signedAt: transaction.signedAt?.toISOString() || null,\n externalTxId: transaction.externalTxId ?? null,\n }\n}\n\nexport const toTransaction = (table: TransactionTable): Transaction => {\n const result: Transaction = {\n id: table.id,\n commandId: table.commandId,\n status: table.status as 'pending' | 'signed' | 'executed' | 'failed',\n preparedTransaction: table.preparedTransaction,\n preparedTransactionHash: table.preparedTransactionHash,\n payload: table.payload ? JSON.parse(table.payload) : undefined,\n origin: table.origin || null,\n userId: table.userId,\n networkId: table.networkId,\n }\n\n if (table.createdAt) {\n result.createdAt = new Date(table.createdAt)\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n\n if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n\n return result\n}\n\nexport const fromMessageRaw = (\n message: MessageRaw,\n userId: UserId,\n networkId: string\n): MessageRawTable => {\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n return {\n id: message.id,\n status: message.status,\n userId: message.userId,\n partyId: message.partyId,\n publicKey: message.publicKey,\n message: message.message,\n origin: message.origin || null,\n networkId,\n createdAt: message.createdAt.toISOString(),\n signedAt: message.signedAt?.toISOString() || null,\n signature: message.signature ?? null,\n }\n}\n\nexport const toMessageRaw = (table: MessageRawTable): MessageRaw => {\n const result: MessageRaw = {\n id: table.id,\n status: table.status as MessageRaw['status'],\n userId: table.userId,\n partyId: table.partyId,\n publicKey: table.publicKey,\n message: table.message,\n origin: table.origin || null,\n createdAt: new Date(table.createdAt),\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n if (table.signature) {\n result.signature = table.signature\n }\n\n return result\n}\n\nexport const fromApiKey = (table: ApiKeysTable): ApiKey => {\n return {\n id: table.id,\n digest: table.digest,\n name: table.name,\n userId: table.userId,\n email: table.email,\n networkId: table.networkId,\n createdAt: new Date(table.createdAt),\n lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : undefined,\n }\n}\n\nexport const toApiKey = (apiKey: ApiKey): ApiKeysTable => {\n return {\n id: apiKey.id,\n digest: apiKey.digest,\n name: apiKey.name,\n userId: apiKey.userId,\n email: apiKey.email,\n networkId: apiKey.networkId,\n createdAt: apiKey.createdAt.toISOString(),\n lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null,\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Logger } from 'pino'\nimport {\n type AuthContext,\n type UserId,\n type AuthAware,\n assertConnected,\n type Idp,\n} from '@canton-network/core-wallet-auth'\nimport type {\n Store as BaseStore,\n Wallet,\n PartyId,\n Session,\n WalletFilter,\n Transaction,\n MessageRaw,\n MessageRawStatusUpdate,\n Network,\n StoreConfig,\n UpdateWallet,\n CurrentNetworkWalletFilter,\n PartyLevelRight,\n TransactionStatusUpdate,\n UserLevelRight,\n ApiKey,\n ListTransactionsOptions,\n WalletUniqueConstraint,\n} from '@canton-network/core-wallet-store'\nimport {\n CamelCasePlugin,\n Kysely,\n PostgresDialect,\n SqliteDialect,\n sql,\n} from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n type DB,\n fromIdp,\n fromNetwork,\n fromTransaction,\n fromMessageRaw,\n fromWallet,\n fromPartyRight,\n fromUserRight,\n toWalletUpdateProperties,\n toIdp,\n toNetwork,\n toTransaction,\n toMessageRaw,\n toWallet,\n fromApiKey,\n toApiKey,\n toSession,\n} from './schema.js'\nimport pg from 'pg'\nimport type { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n private logger: Logger,\n authContext?: AuthContext\n ) {\n this.logger = logger.child({ component: 'StoreSql' })\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, this.logger, context)\n }\n\n private assertConnected(): UserId {\n return assertConnected(this.authContext).userId\n }\n\n // Wallet methods\n\n async getAllWallets(filter: WalletFilter = {}): Promise<Array<Wallet>> {\n const userId = this.assertConnected()\n const { networkIds, signingProviderIds } = filter\n const networkIdSet = networkIds ? new Set(networkIds) : null\n const signingProviderIdSet = signingProviderIds\n ? new Set(signingProviderIds)\n : null\n\n const wallets = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const userPartyRights = await this.db\n .selectFrom('userPartyRights')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const rightsByWallet = new Map<string, PartyLevelRight[]>()\n for (const row of userPartyRights) {\n const right = fromPartyRight(row.right)\n if (!right) continue\n const key = `${row.partyId}:${row.networkId}`\n const existing = rightsByWallet.get(key) ?? []\n rightsByWallet.set(key, [...existing, right])\n }\n\n return wallets\n .filter((wallet) => {\n const matchedNetworkIds = networkIdSet\n ? networkIdSet.has(wallet.networkId)\n : true\n const matchedSigningProviderIds = signingProviderIdSet\n ? signingProviderIdSet.has(wallet.signingProviderId)\n : true\n return matchedNetworkIds && matchedSigningProviderIds\n })\n .map((table) => {\n const wallet = toWallet(table)\n const rights = rightsByWallet.get(\n `${table.partyId}:${table.networkId}`\n )\n return {\n ...wallet,\n rights: rights ?? [],\n }\n })\n }\n\n async getWallets(\n filter: CurrentNetworkWalletFilter = {}\n ): Promise<Array<Wallet>> {\n const network = await this.getCurrentNetwork()\n return this.getAllWallets({\n ...filter,\n networkIds: [network.id],\n })\n }\n\n async getWallet(partyId: PartyId): Promise<Wallet | null> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const constraint: WalletUniqueConstraint = {\n partyId,\n networkId: network.id,\n userId,\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where((eb) => eb.and(constraint))\n .executeTakeFirst()\n\n if (!row) return null\n\n const rightRows = await this.db\n .selectFrom('userPartyRights')\n .select('right')\n .where((eb) => eb.and(constraint))\n .execute()\n\n return {\n ...toWallet(row),\n rights: rightRows\n .map(({ right }) => fromPartyRight(right))\n .filter((right) => right !== undefined),\n }\n }\n\n async getPrimaryWallet(): Promise<Wallet | undefined> {\n const wallets = await this.getWallets()\n return wallets.find((w) => w.primary === true)\n }\n\n async setPrimaryWallet(partyId: PartyId): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n const wallets = await this.getWallets()\n\n if (!wallets.some((w) => w.partyId === partyId)) {\n throw new Error(\n `Wallet with partyId \"${partyId}\" not found in network \"${network.id}\"`\n )\n }\n\n const primary = wallets.find((w) => w.primary === true)\n\n await this.db.transaction().execute(async (trx) => {\n if (primary) {\n // Unset primary for current network only\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', primary.partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n // Set new primary for current network\n await trx\n .updateTable('wallets')\n .set({ primary: 1 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async addWallet(wallet: Wallet): Promise<void> {\n this.logger.info('Adding wallet')\n const userId = this.assertConnected()\n\n const wallets = await this.getWallets()\n if (\n wallets.some(\n (w) =>\n w.partyId === wallet.partyId &&\n w.networkId === wallet.networkId\n )\n ) {\n throw new Error(\n `Wallet with partyId \"${wallet.partyId}\" networkId \"${wallet.networkId}\" userId \"${userId}\" already exists`\n )\n }\n\n if (\n !wallet.disabled &&\n wallet.status === 'allocated' &&\n !wallets.some((wallet) => wallet.primary)\n ) {\n // If there is no primary wallet yet, set current one as primary (unless disabled or not allocated).\n // In regular case it would be the first added wallet.\n wallet.primary = true\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (wallet.primary) {\n // If the new wallet is primary, set all others in the same network and for this user to non-primary\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('primary', '=', 1),\n eb('networkId', '=', wallet.networkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n await trx\n .insertInto('wallets')\n .values(fromWallet(wallet, userId))\n .execute()\n\n if (wallet.rights && wallet.rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n wallet.rights.map((right) => ({\n userId,\n networkId: wallet.networkId,\n partyId: wallet.partyId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n async updateWallet(params: UpdateWallet): Promise<void> {\n const { partyId, networkId, rights } = params\n this.logger.info('Updating wallet')\n const userId = this.assertConnected()\n\n const updates = toWalletUpdateProperties(params)\n\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n if (Object.keys(updates).length === 0 && rights === undefined) return\n\n await this.db.transaction().execute(async (trx) => {\n if (Object.keys(updates).length > 0) {\n await trx\n .updateTable('wallets')\n .set(updates)\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n\n if (rights !== undefined) {\n await trx\n .deleteFrom('userPartyRights')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId: targetNetworkId,\n partyId,\n right,\n }))\n )\n .execute()\n }\n }\n })\n }\n\n async removeWallet(partyId: PartyId): Promise<void> {\n this.logger.info('Removing wallet')\n const userId = this.assertConnected()\n\n // Remove wallet from current network only\n const network = await this.getCurrentNetwork()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('wallets')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async getUserRights(networkId?: string): Promise<Array<UserLevelRight>> {\n const userId = this.assertConnected()\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n const rows = await this.db\n .selectFrom('userRights')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', targetNetworkId),\n ])\n )\n .execute()\n\n return rows\n .map((row) => fromUserRight(row.right))\n .filter((right): right is UserLevelRight => right !== undefined)\n }\n\n async setUserRights(\n networkId: string,\n rights: Array<UserLevelRight>\n ): Promise<void> {\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('userRights')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', networkId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n // Session methods\n async getSession(accessToken: AccessToken): Promise<Session | undefined> {\n const userId = this.assertConnected()\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async listSessions(): Promise<Array<Session>> {\n const userId = this.assertConnected()\n const rows = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n return rows.map((row) => toSession(row))\n }\n\n async setSession(session: Session): Promise<void> {\n const userId = this.assertConnected()\n\n if (!session.origin) {\n throw new Error('Session origin is required')\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (session.accessToken) {\n // Regular session - one user can have only one session per origin.\n // Tokenless sessions are not replaced by duplicates.\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n eb('accessToken', 'is not', null),\n ])\n )\n .execute()\n this.logger.debug(deleted, 'Deleted old session')\n }\n\n const inserted = await trx\n .insertInto('sessions')\n .values({\n ...session,\n accessToken: session.accessToken ?? null,\n userId,\n })\n .execute()\n\n this.logger.debug(inserted, 'Inserted new session')\n })\n }\n\n async getOnboardingSession(\n sessionId: string\n ): Promise<Session | undefined> {\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async upgradeOnboardingSession(\n sessionId: string,\n accessToken: AccessToken\n ): Promise<Session> {\n const userId = this.assertConnected()\n\n return this.db.transaction().execute(async (trx) => {\n const row = await trx\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('userId', '=', userId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n if (!row) {\n throw new Error('Onboarding session not found')\n }\n\n await trx\n .deleteFrom('sessions')\n .where('userId', '=', userId)\n .where('origin', '=', row.origin)\n .where('id', '!=', sessionId)\n .execute()\n await trx\n .updateTable('sessions')\n .set({ accessToken })\n .where('id', '=', sessionId)\n .execute()\n\n return toSession({ ...row, accessToken })\n })\n }\n\n async removeSession(accessToken: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .execute()\n }\n\n /**\n * Lists all pending transactions across all users.\n */\n\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.or([\n eb('status', '=', 'pending'),\n eb('status', '=', 'awaiting-signature'),\n ])\n )\n .execute()\n\n return rows.map((row) => toTransaction(row))\n }\n\n // IDP methods\n\n async getIdp(idpId: string): Promise<Idp> {\n const idps = await this.listIdps()\n if (!idps) throw new Error('No IDPs available')\n\n const idp = idps.find((n) => n.id === idpId)\n if (!idp) throw new Error(`IDP \"${idpId}\" not found`)\n return idp\n }\n\n async listIdps(): Promise<Array<Idp>> {\n // All IDPs are global for now -- TO-DO: user-specific IDPs\n const query = this.db.selectFrom('idps').selectAll()\n\n const idps = await query.execute()\n return idps.map((table) => toIdp(table))\n }\n\n async updateIdp(idp: Idp): Promise<void> {\n // todo: check and compare userid of existing idp\n await this.db.transaction().execute(async (trx) => {\n const idpEntry = fromIdp(idp)\n this.logger.info(idpEntry, 'Updating idp table')\n await trx\n .updateTable('idps')\n .set(idpEntry)\n .where('id', '=', idp.id)\n .execute()\n })\n }\n\n async addIdp(idp: Idp): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n const idpAlreadyExists = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idp.id)\n .executeTakeFirst()\n if (idpAlreadyExists) {\n throw new Error(`IDP ${idp.id} already exists`)\n } else {\n await trx.insertInto('idps').values(fromIdp(idp)).execute()\n }\n })\n }\n\n async removeIdp(idpId: string): Promise<void> {\n const networks = await this.listNetworks()\n if (networks.some((n) => n.identityProviderId === idpId)) {\n throw new Error(\n `Cannot delete IDP ${idpId} as it is in use by existing networks`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const idp = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idpId)\n .executeTakeFirst()\n if (!idp) {\n throw new Error(`IDP ${idpId} does not exists`)\n }\n await trx.deleteFrom('idps').where('id', '=', idpId).execute()\n })\n }\n\n // Network methods\n async getNetwork(networkId: string): Promise<Network> {\n const networks = await this.listNetworks()\n if (!networks) throw new Error('No networks available')\n\n const network = networks.find((n) => n.id === networkId)\n if (!network) throw new Error(`Network \"${networkId}\" not found`)\n return network\n }\n\n async getCurrentNetwork(): Promise<Network> {\n const userId = this.assertConnected()\n const token = this.authContext?.accessToken\n const onboardingSessionId =\n this.authContext && !this.authContext.isApiKey\n ? this.authContext.sessionId\n : undefined\n if (!token && !onboardingSessionId) {\n throw new Error('No session found')\n }\n\n const sessionRow = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .where((eb) =>\n token\n ? eb('accessToken', '=', token)\n : eb.and([\n eb('id', '=', onboardingSessionId!),\n eb('accessToken', 'is', null),\n ])\n )\n .executeTakeFirst()\n if (!sessionRow) {\n throw new Error('No session found')\n }\n\n const session = toSession(sessionRow)\n const networkId = session.network\n if (!networkId) {\n throw new Error('No current network set in session')\n }\n\n const networks = await this.listNetworks()\n const network = networks.find((n) => n.id === networkId)\n if (!network) {\n throw new Error(`Network \"${networkId}\" not found`)\n }\n return network\n }\n\n async getNetworkForTokenVerification(\n networkId: string\n ): Promise<Network | undefined> {\n // Not scoped by userId: key id resolution happens during token\n // verification, before there is an authenticated user.\n const row = await this.db\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!row) return undefined\n\n const network = toNetwork(row)\n return network.auth.method === 'self_signed' ? network : undefined\n }\n\n async listNetworks(): Promise<Array<Network>> {\n let query = this.db.selectFrom('networks').selectAll()\n\n if (this.authContext) {\n const userId = this.assertConnected()\n query = query.where((eb) =>\n eb.or([\n eb('userId', 'is', null), // Global networks\n eb('userId', '=', userId), // User-specific networks\n ])\n )\n } else {\n query = query.where('userId', 'is', null) // Only global networks\n }\n\n const networks = await query.execute()\n return networks.map((table) => toNetwork(table))\n }\n\n async updateNetwork(network: Network): Promise<void> {\n // todo: check and compare idpId of existing network\n this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n // we do not set a userId for now and leave all networks global when updating\n const networkEntry = fromNetwork(network, undefined)\n this.logger.info(networkEntry, 'Updating network table')\n await trx\n .updateTable('networks')\n .set(networkEntry)\n .where('id', '=', network.id)\n .execute()\n })\n }\n\n async addNetwork(network: Network): Promise<void> {\n const userId = this.authContext?.userId\n const idps = await this.listIdps()\n const networkIdp = idps.find(\n (idp) => idp.id === network.identityProviderId\n )\n\n if (!networkIdp) {\n throw new Error(\n `Identity provider \"${network.identityProviderId}\" not found`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const networkAlreadyExists = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', network.id)\n .executeTakeFirst()\n if (networkAlreadyExists) {\n throw new Error(`Network ${network.id} already exists`)\n } else {\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\n }\n })\n }\n\n async removeNetwork(networkId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const network = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!network) {\n throw new Error(`Network ${networkId} does not exists`)\n }\n if (network.userId !== userId) {\n throw new Error(\n `Network ${networkId} is not owned by user ${userId}`\n )\n }\n await trx\n .deleteFrom('networks')\n .where('id', '=', networkId)\n .execute()\n })\n }\n\n private mergeTransactionStatusUpdate(\n existing: Transaction,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Transaction {\n const payload = updates.payload ?? existing.payload\n const signedAt = updates.signedAt ?? existing.signedAt\n const externalTxId = updates.externalTxId ?? existing.externalTxId\n const failureReason = updates.failureReason ?? existing.failureReason\n\n return {\n id: existing.id,\n commandId: existing.commandId,\n status,\n preparedTransaction: existing.preparedTransaction,\n preparedTransactionHash: existing.preparedTransactionHash,\n origin: existing.origin,\n ...(payload !== undefined && { payload }),\n ...(existing.createdAt !== undefined && {\n createdAt: existing.createdAt,\n }),\n ...(signedAt !== undefined && { signedAt }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(failureReason !== undefined && { failureReason }),\n }\n }\n\n // Transaction methods\n async setTransaction(transaction: Transaction): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n await this.db\n .insertInto('transactions')\n .values(fromTransaction(transaction, userId, network.id))\n .execute()\n }\n\n async setTransactionSigned(\n transactionId: string,\n signedAt: Date,\n externalTxId?: string,\n opts?: { expectedStatus: Transaction['status'] }\n ): Promise<boolean> {\n return await this.setTransactionStatus(\n transactionId,\n 'signed',\n {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n },\n opts\n )\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {},\n opts?: { expectedStatus?: Transaction['status'] }\n ): Promise<boolean> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getTransaction(transactionId)\n if (!existing) {\n throw new Error(`Transaction not found with id: ${transactionId}`)\n }\n if (opts?.expectedStatus && existing.status !== opts.expectedStatus) {\n return false\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n const res = await this.db\n .updateTable('transactions')\n .set(fromTransaction(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ...(opts?.expectedStatus\n ? [eb('status', '=', opts.expectedStatus)]\n : []),\n ])\n )\n .executeTakeFirst()\n\n return res.numUpdatedRows > 0n\n }\n\n async getTransaction(\n transactionId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async getLatestTransactionByCommandId(\n commandId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('commandId', '=', commandId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .executeTakeFirst()\n\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async transactionsCount(): Promise<number> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n const result = await this.db\n .selectFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .select((eb) => eb.fn.count<number>('id').as('count'))\n .executeTakeFirstOrThrow()\n\n return Number(result.count)\n }\n\n async listTransactions(options?: ListTransactionsOptions) {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const { cursor, limit } = options ?? {}\n const lim = limit ? Math.min(limit, 100) : 100\n\n let query = this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .orderBy('id', 'desc')\n .limit(lim + 1)\n\n if (cursor) {\n const split = cursor.split('::')\n const dateString = split[0] === 'null' ? null : split[0]\n const cursorId = split[1]\n\n query = query.where((eb) => {\n if (dateString === null) {\n return eb.and([\n eb('createdAt', 'is', null),\n eb('id', '<', cursorId),\n ])\n }\n\n return eb.or([\n eb('createdAt', '<', dateString),\n eb.and([\n eb('createdAt', '=', dateString),\n eb('id', '<', split[1]),\n ]),\n eb('createdAt', 'is', null),\n ])\n })\n }\n\n const rows = await query.execute()\n const txs = rows.map((r) => toTransaction(r))\n\n const hasNextPage = txs.length > lim\n if (hasNextPage) {\n txs.pop()\n }\n\n if (txs.length === 0) {\n return {\n transactions: [],\n nextCursor: null,\n }\n }\n\n const lastTx = txs[txs.length - 1]\n if (lastTx === undefined) {\n return {\n transactions: txs,\n nextCursor: null,\n }\n }\n\n //handle case for if timestamp is null\n if (lastTx.createdAt) {\n const d = new Date(lastTx.createdAt).toISOString()\n const nextCursor = hasNextPage ? `${d}::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n } else {\n const nextCursor = hasNextPage ? `null::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n }\n }\n\n async removeTransaction(transactionId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n private mergeMessageRawStatusUpdate(\n existing: MessageRaw,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): MessageRaw {\n const signedAt = updates.signedAt ?? existing.signedAt\n const signature = updates.signature ?? existing.signature\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n }\n }\n\n // Message signing request methods\n async setMessageRaw(message: MessageRaw): Promise<void> {\n const userId = this.assertConnected()\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n const network = await this.getCurrentNetwork()\n await this.db\n .insertInto('messagesRaw')\n .values(fromMessageRaw(message, userId, network.id))\n .execute()\n }\n\n async setMessageRawStatus(\n messageId: string,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getMessageRaw(messageId)\n if (!existing) {\n throw new Error(`MessageRaw not found with id: ${messageId}`)\n }\n\n const updated = this.mergeMessageRawStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('messagesRaw')\n .set(fromMessageRaw(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getMessageRaw(messageId: string): Promise<MessageRaw | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const message = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return message ? toMessageRaw(message) : undefined\n }\n\n async listMessageRaws(): Promise<Array<MessageRaw>> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const messages = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .execute()\n return messages.map((m) => toMessageRaw(m))\n }\n\n async removeMessageRaw(messageId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('messagesRaw')\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n // API keys\n async addApiKey(apiKey: ApiKey): Promise<void> {\n const userId = this.assertConnected()\n if (apiKey.userId !== userId) {\n throw new Error(\n `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`\n )\n }\n\n const network = await this.getCurrentNetwork()\n if (apiKey.networkId !== network.id) {\n throw new Error(\n `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`\n )\n }\n\n await this.db.insertInto('apiKeys').values(toApiKey(apiKey)).execute()\n }\n\n async listApiKeys(): Promise<Array<ApiKey>> {\n const query = this.db\n .selectFrom('apiKeys')\n .selectAll()\n .orderBy('createdAt', 'desc')\n\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const apiKeys = await query\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n\n return apiKeys.map(fromApiKey)\n }\n\n async getApiKey(digest: string): Promise<ApiKey | undefined> {\n const apiKey = await this.db\n .selectFrom('apiKeys')\n .selectAll()\n .where((eb) => eb('digest', '=', digest))\n .executeTakeFirst()\n\n return apiKey ? fromApiKey(apiKey) : undefined\n }\n\n async removeApiKey(apiKeyId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('apiKeys')\n .where((eb) =>\n eb.and([\n eb('id', '=', apiKeyId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n}\n\nexport const connection = (config: StoreConfig) => {\n let database\n switch (config.connection.type) {\n case 'sqlite':\n database = new Database(config.connection.database)\n // normally sqlite3 has foreign_keys = OFF for each connection,\n // but better-sqlite3 uses custom build with compile flag SQLITE_DEFAULT_FOREIGN_KEYS=1,\n // making it ON by default.\n // Set explicitly ON anyway as redundancy\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'postgres':\n return new Kysely<DB>({\n dialect: new PostgresDialect({\n pool: new pg.Pool(config.connection),\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'memory':\n database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Umzug, type MigrationMeta, type UmzugStorage } from 'umzug'\nimport type { Kysely } from 'kysely'\nimport type { DB } from './schema'\n\nclass KyselyStorage implements UmzugStorage {\n constructor(private db: Kysely<DB>) {}\n\n private async ensureTable() {\n await this.db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'text', (col) => col.primaryKey())\n .addColumn('executedAt', 'text', (col) => col.notNull())\n .execute()\n }\n\n async executed(): Promise<string[]> {\n await this.ensureTable()\n const rows = await this.db\n .selectFrom('migrations')\n .select('name')\n .execute()\n return rows.map((r) => r.name)\n }\n\n async logMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .insertInto('migrations')\n .values({ name, executedAt: new Date().toISOString() })\n .execute()\n }\n\n async unlogMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute()\n }\n}\n\nexport const migrator = (db: Kysely<DB>) => {\n const ext = import.meta.url.endsWith('.ts') ? 'ts' : 'js'\n const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname\n return new Umzug({\n migrations: {\n glob: glob,\n resolve: ({ name, path, context }) => {\n // Dynamic import for ESM\n return {\n name,\n up: async () => {\n console.log(path)\n const { up } = await import(path!)\n return up(context)\n },\n down: async () => {\n const { down } = await import(path!)\n return down(context)\n },\n }\n },\n },\n context: db,\n storage: new KyselyStorage(db),\n logger: console,\n })\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport type { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport type { Logger } from 'pino'\nimport type { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig,\n logger: Logger\n): Promise<void> {\n const store = new StoreSql(db, logger)\n\n // Load all IDPs from config into the store\n await Promise.all(config.idps.map((idp) => store.addIdp(idp)))\n\n // Load all networks from config into the store\n await Promise.all(\n config.networks.map((network) => store.addNetwork(network))\n )\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Command } from 'commander'\nimport { connection } from './store-sql.js'\nimport { migrator } from './migrator.js'\nimport type {\n StoreConfig,\n BootstrapConfig,\n} from '@canton-network/core-wallet-store'\nimport { pino } from 'pino'\nimport { bootstrap } from './bootstrap.js'\n\nconst logger = pino({ name: 'main', level: 'debug' })\n\nexport function createCLI(\n config: StoreConfig,\n bootstrapConfig?: BootstrapConfig\n): Command {\n const program = new Command()\n\n program\n .command('up')\n .description('Run all pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('down')\n .description('Rollback last migration')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.down()\n await db.destroy()\n })\n\n program\n .command('status')\n .description('Show executed and pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n const pending = await umzug.pending()\n\n console.log('Executed migrations:', executed)\n console.log('Pending migrations:', pending)\n\n await db.destroy()\n })\n\n program\n .command('reset')\n .description('Rollback all migrations and reapply them')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n\n // Rollback all executed migrations in reverse order\n for (const migration of executed.reverse()) {\n await umzug.down({ to: migration.name })\n }\n\n // Reapply all migrations\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('bootstrap')\n .description('Bootstrap DB from config')\n .action(async () => {\n if (!bootstrapConfig) {\n throw new Error(\n 'Bootstrap config (idps/networks) is required for the bootstrap command'\n )\n }\n const db = connection(config)\n await bootstrap(db, bootstrapConfig, logger)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;AAwJA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAElE,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MAAM,iCAAiC,MAAM,IAAI;GAG/D,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,WAAW,MAAM;GACrB;EAEJ,KAAK;GACD,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MACN,uCAAuC,MAAM,IACjD;GAEJ,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;GAClB;EACJ,KAAK,eACD,OAAO;GACH,IAAI,MAAM;GACV,MAAM,MAAM;EAChB;CACR;AACJ;AAEA,MAAa,WAAW,QAAuB;CAC3C,QAAQ,IAAI,MAAZ;EACI,KAAK,SACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW,IAAI;EACnB;EACJ,KAAK,eACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW;EACf;EACJ,KAAK,eACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ;GACR,WAAW;EACf;CACR;AACJ;AAEA,MAAa,aAAa,UAAiC;CACvD,OAAO;EACH,MAAM,MAAM;EACZ,IAAI,MAAM;EACV,gBAAgB,MAAM,kBAAkB,KAAA;EACxC,oBAAoB,MAAM;EAC1B,aAAa,MAAM;EACnB,WAAW,EACP,SAAS,MAAM,iBACnB;EACA,MAAM,WAAW,MACb,OAAO,MAAM,SAAS,WAAW,KAAK,MAAM,MAAM,IAAI,IAAI,MAAM,IACpE;EACA,WAAW,MAAM,YACX,WAAW,MACP,O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,IAAI,UAAU,KAAK,CAAC;EAI3C,MAAM,MAAM,GAAG;EACf,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,QACK,QAAQ,WAAW,CAAC,CACpB,YAAY,0BAA0B,CAAC,CACvC,OAAO,YAAY;EAChB,IAAI,CAAC,iBACD,MAAM,IAAI,MACN,wEACJ;EAEJ,MAAM,KAAK,WAAW,MAAM;EAC5B,MAAM,UAAU,IAAI,iBAAiB,MAAM;EAC3C,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,OAAO;AACX"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/schema.ts","../src/store-sql.ts","../src/migrator.ts","../src/bootstrap.ts","../src/cli.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n authSchema,\n type Idp,\n type UserId,\n} from '@canton-network/core-wallet-auth'\nimport {\n type Wallet,\n type Transaction,\n type Session,\n type Network,\n type WalletStatus,\n type UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n type MessageRaw,\n type ApiKey,\n} from '@canton-network/core-wallet-store'\n\ninterface MigrationTable {\n name: string\n executedAt: string\n}\n\ninterface IdpTable {\n id: string\n type: 'oauth' | 'self_signed' | 'self_issued'\n issuer: string | null\n configUrl: string | null\n}\n\ninterface NetworkTable {\n id: string\n name: string\n synchronizerId: string | null // retrieved at runtime if null\n description: string\n ledgerApiBaseUrl: string\n identityProviderId: string\n userId: UserId | undefined // global if undefined\n\n auth: string // json stringified\n adminAuth: string | undefined // json stringified\n serviceAccountAuth: string | undefined // json stringified\n}\n\n/**\n * Wallet table schema\n * Primary key on (partyId, networkId, userId)\n * Unique constraint on (networkId, userId) for primary wallet per network per user\n */\ninterface WalletTable {\n primary: number\n partyId: string\n hint: string\n publicKey: string\n namespace: string\n networkId: string\n signingProviderId: string\n userId: UserId\n externalTxId: string | null\n topologyTransactions: string | null\n status: string | null\n disabled: number\n reason: string | null\n isAuthParty: number\n}\ninterface UpdateWalletProperties {\n primary?: number\n externalTxId?: string | null\n topologyTransactions?: string | null\n status?: string | null\n disabled?: number\n reason?: string | null\n isAuthParty?: number\n}\n\ninterface UserPartyRightTable {\n userId: UserId\n networkId: string\n partyId: string\n right: PartyLevelRight\n}\n\ninterface UserRightTable {\n userId: UserId\n networkId: string\n right: UserLevelRight\n}\n\ninterface TransactionTable {\n id: string\n status: string\n commandId: string\n networkId: string\n preparedTransaction: string\n preparedTransactionHash: string\n payload: string | undefined\n origin: string | null\n userId: UserId\n createdAt: string | null\n signedAt: string | null\n externalTxId: string | null\n}\n\ninterface MessageRawTable {\n id: string\n status: string\n partyId: string\n publicKey: string\n message: string\n origin: string | null\n userId: UserId\n networkId: string\n createdAt: string\n signedAt: string | null\n signature: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string | null\n userId: UserId\n}\n\ninterface ApiKeysTable {\n id: string\n digest: string\n name: string\n userId: UserId\n email: string | null\n networkId: string\n createdAt: string\n lastUsedAt: string | null\n}\n\nexport interface DB {\n migrations: MigrationTable\n idps: IdpTable\n networks: NetworkTable\n wallets: WalletTable\n userPartyRights: UserPartyRightTable\n userRights: UserRightTable\n transactions: TransactionTable\n messagesRaw: MessageRawTable\n sessions: SessionTable\n apiKeys: ApiKeysTable\n}\n\nexport const toIdp = (table: IdpTable): Idp => {\n switch (table.type) {\n case 'oauth': {\n if (!table.configUrl) {\n throw new Error(`Missing configUrl for oauth IdP: ${table.id}`)\n }\n if (table.issuer === null) {\n throw new Error(`Missing issuer for oauth IdP: ${table.id}`)\n }\n\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n configUrl: table.configUrl,\n }\n }\n case 'self_signed':\n if (table.issuer === null) {\n throw new Error(\n `Missing issuer for self_signed IdP: ${table.id}`\n )\n }\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n case 'self_issued':\n return {\n id: table.id,\n type: table.type,\n }\n }\n}\n\nexport const fromIdp = (idp: Idp): IdpTable => {\n switch (idp.type) {\n case 'oauth':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: idp.configUrl,\n }\n case 'self_signed':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: null,\n }\n case 'self_issued':\n return {\n id: idp.id,\n type: idp.type,\n issuer: null,\n configUrl: null,\n }\n }\n}\n\nexport const toNetwork = (table: NetworkTable): Network => {\n return {\n name: table.name,\n id: table.id,\n synchronizerId: table.synchronizerId ?? undefined,\n identityProviderId: table.identityProviderId,\n description: table.description,\n ledgerApi: {\n baseUrl: table.ledgerApiBaseUrl,\n },\n auth: authSchema.parse(\n typeof table.auth === 'string' ? JSON.parse(table.auth) : table.auth\n ),\n adminAuth: table.adminAuth\n ? authSchema.parse(\n typeof table.adminAuth === 'string'\n ? JSON.parse(table.adminAuth)\n : table.adminAuth\n )\n : undefined,\n serviceAccountAuth: table.serviceAccountAuth\n ? authSchema.parse(\n typeof table.serviceAccountAuth === 'string'\n ? JSON.parse(table.serviceAccountAuth)\n : table.serviceAccountAuth\n )\n : undefined,\n }\n}\n\nexport const fromNetwork = (\n network: Network,\n userId?: UserId\n): NetworkTable => {\n return {\n name: network.name,\n id: network.id,\n synchronizerId: network.synchronizerId ?? null,\n description: network.description,\n ledgerApiBaseUrl: network.ledgerApi.baseUrl,\n userId: userId,\n identityProviderId: network.identityProviderId,\n auth: JSON.stringify(network.auth),\n adminAuth: network.adminAuth\n ? JSON.stringify(network.adminAuth)\n : undefined,\n serviceAccountAuth: network.serviceAccountAuth\n ? JSON.stringify(network.serviceAccountAuth)\n : undefined,\n }\n}\n\nexport const toSession = (table: SessionTable): Session => {\n return {\n id: table.id,\n network: table.network,\n origin: table.origin,\n ...(table.accessToken ? { accessToken: table.accessToken } : {}),\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, isAuthParty, ...rest } =\n wallet\n void rights\n return {\n ...rest,\n primary: wallet.primary ? 1 : 0,\n userId: userId,\n disabled: wallet.disabled !== undefined && wallet.disabled ? 1 : 0,\n isAuthParty: isAuthParty ? 1 : 0,\n reason: wallet.reason ?? null,\n externalTxId: externalTxId && externalTxId !== '' ? externalTxId : null,\n topologyTransactions:\n topologyTransactions && topologyTransactions !== ''\n ? topologyTransactions\n : null,\n }\n}\n\n// only update fields that are explicitly provided to prevent data loss\nexport const toWalletUpdateProperties = (\n params: UpdateWallet\n): UpdateWalletProperties => {\n const {\n status,\n externalTxId,\n topologyTransactions,\n disabled,\n reason,\n primary,\n signingProviderId,\n publicKey,\n namespace,\n isAuthParty,\n } = params\n return {\n ...(status !== undefined && { status }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(topologyTransactions !== undefined && { topologyTransactions }),\n ...(primary !== undefined && { primary: primary ? 1 : 0 }),\n ...(disabled !== undefined && { disabled: disabled ? 1 : 0 }),\n ...(reason !== undefined && { reason }),\n ...(signingProviderId !== undefined && { signingProviderId }),\n ...(publicKey !== undefined && { publicKey }),\n ...(namespace !== undefined && { namespace }),\n ...(isAuthParty !== undefined && { isAuthParty: isAuthParty ? 1 : 0 }),\n }\n}\n\nexport const toWalletStatus = (status?: string | null): WalletStatus => {\n if (status === 'allocated') return 'allocated'\n if (status === 'removed') return 'removed'\n return 'initialized'\n}\n\nexport const toWallet = (table: WalletTable): Wallet => {\n return {\n primary: Boolean(table.primary),\n status: toWalletStatus(table.status),\n partyId: table.partyId,\n hint: table.hint,\n publicKey: table.publicKey,\n namespace: table.namespace,\n networkId: table.networkId,\n signingProviderId: table.signingProviderId,\n disabled: table.disabled === 1,\n isAuthParty: Boolean(table.isAuthParty),\n userId: table.userId,\n ...(table.externalTxId !== null && {\n externalTxId: table.externalTxId,\n }),\n ...(table.topologyTransactions !== null && {\n topologyTransactions: table.topologyTransactions,\n }),\n ...(table.reason !== null && {\n reason: table.reason,\n }),\n rights: [],\n }\n}\n\nexport const fromPartyRight = (right: string): PartyLevelRight | undefined => {\n if (Object.values(PartyLevelRight).includes(right as PartyLevelRight)) {\n return right as PartyLevelRight\n }\n return undefined\n}\n\nexport const fromUserRight = (right: string): UserLevelRight | undefined => {\n if (Object.values(UserLevelRight).includes(right as UserLevelRight)) {\n return right as UserLevelRight\n }\n return undefined\n}\n\nexport const fromTransaction = (\n transaction: Transaction,\n userId: UserId,\n networkId: string\n): TransactionTable => {\n return {\n ...transaction,\n networkId,\n payload: transaction.payload\n ? JSON.stringify(transaction.payload)\n : undefined,\n origin: transaction.origin || null,\n userId: userId,\n createdAt: transaction.createdAt?.toISOString() || null,\n signedAt: transaction.signedAt?.toISOString() || null,\n externalTxId: transaction.externalTxId ?? null,\n }\n}\n\nexport const toTransaction = (table: TransactionTable): Transaction => {\n const result: Transaction = {\n id: table.id,\n commandId: table.commandId,\n status: table.status as 'pending' | 'signed' | 'executed' | 'failed',\n preparedTransaction: table.preparedTransaction,\n preparedTransactionHash: table.preparedTransactionHash,\n payload: table.payload ? JSON.parse(table.payload) : undefined,\n origin: table.origin || null,\n userId: table.userId,\n networkId: table.networkId,\n }\n\n if (table.createdAt) {\n result.createdAt = new Date(table.createdAt)\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n\n if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n\n return result\n}\n\nexport const fromMessageRaw = (\n message: MessageRaw,\n userId: UserId,\n networkId: string\n): MessageRawTable => {\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n return {\n id: message.id,\n status: message.status,\n userId: message.userId,\n partyId: message.partyId,\n publicKey: message.publicKey,\n message: message.message,\n origin: message.origin || null,\n networkId,\n createdAt: message.createdAt.toISOString(),\n signedAt: message.signedAt?.toISOString() || null,\n signature: message.signature ?? null,\n }\n}\n\nexport const toMessageRaw = (table: MessageRawTable): MessageRaw => {\n const result: MessageRaw = {\n id: table.id,\n status: table.status as MessageRaw['status'],\n userId: table.userId,\n partyId: table.partyId,\n publicKey: table.publicKey,\n message: table.message,\n origin: table.origin || null,\n createdAt: new Date(table.createdAt),\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n if (table.signature) {\n result.signature = table.signature\n }\n\n return result\n}\n\nexport const fromApiKey = (table: ApiKeysTable): ApiKey => {\n return {\n id: table.id,\n digest: table.digest,\n name: table.name,\n userId: table.userId,\n email: table.email,\n networkId: table.networkId,\n createdAt: new Date(table.createdAt),\n lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : undefined,\n }\n}\n\nexport const toApiKey = (apiKey: ApiKey): ApiKeysTable => {\n return {\n id: apiKey.id,\n digest: apiKey.digest,\n name: apiKey.name,\n userId: apiKey.userId,\n email: apiKey.email,\n networkId: apiKey.networkId,\n createdAt: apiKey.createdAt.toISOString(),\n lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null,\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Logger } from 'pino'\nimport {\n type AuthContext,\n type UserId,\n type AuthAware,\n assertConnected,\n type Idp,\n} from '@canton-network/core-wallet-auth'\nimport { providerErrors } from '@canton-network/core-rpc-errors'\nimport type {\n Store as BaseStore,\n Wallet,\n PartyId,\n Session,\n WalletFilter,\n Transaction,\n MessageRaw,\n MessageRawStatusUpdate,\n Network,\n StoreConfig,\n UpdateWallet,\n CurrentNetworkWalletFilter,\n PartyLevelRight,\n TransactionStatusUpdate,\n UserLevelRight,\n ApiKey,\n ListTransactionsOptions,\n WalletUniqueConstraint,\n} from '@canton-network/core-wallet-store'\nimport {\n assertUniqueSelfIssuedAudience,\n resolveSelfIssuedNetworkByAudiences,\n} from '@canton-network/core-wallet-store'\nimport {\n CamelCasePlugin,\n Kysely,\n PostgresDialect,\n SqliteDialect,\n sql,\n} from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n type DB,\n fromIdp,\n fromNetwork,\n fromTransaction,\n fromMessageRaw,\n fromWallet,\n fromPartyRight,\n fromUserRight,\n toWalletUpdateProperties,\n toIdp,\n toNetwork,\n toTransaction,\n toMessageRaw,\n toWallet,\n fromApiKey,\n toApiKey,\n toSession,\n} from './schema.js'\nimport pg from 'pg'\nimport type { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n private logger: Logger,\n authContext?: AuthContext\n ) {\n this.logger = logger.child({ component: 'StoreSql' })\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, this.logger, context)\n }\n\n private assertConnected(): UserId {\n return assertConnected(this.authContext).userId\n }\n\n // Wallet methods\n\n async getAllWallets(filter: WalletFilter = {}): Promise<Array<Wallet>> {\n const userId = this.assertConnected()\n const { networkIds, signingProviderIds } = filter\n const networkIdSet = networkIds ? new Set(networkIds) : null\n const signingProviderIdSet = signingProviderIds\n ? new Set(signingProviderIds)\n : null\n\n const wallets = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const userPartyRights = await this.db\n .selectFrom('userPartyRights')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const rightsByWallet = new Map<string, PartyLevelRight[]>()\n for (const row of userPartyRights) {\n const right = fromPartyRight(row.right)\n if (!right) continue\n const key = `${row.partyId}:${row.networkId}`\n const existing = rightsByWallet.get(key) ?? []\n rightsByWallet.set(key, [...existing, right])\n }\n\n return wallets\n .filter((wallet) => {\n const matchedNetworkIds = networkIdSet\n ? networkIdSet.has(wallet.networkId)\n : true\n const matchedSigningProviderIds = signingProviderIdSet\n ? signingProviderIdSet.has(wallet.signingProviderId)\n : true\n return matchedNetworkIds && matchedSigningProviderIds\n })\n .map((table) => {\n const wallet = toWallet(table)\n const rights = rightsByWallet.get(\n `${table.partyId}:${table.networkId}`\n )\n return {\n ...wallet,\n rights: rights ?? [],\n }\n })\n }\n\n async getWallets(\n filter: CurrentNetworkWalletFilter = {}\n ): Promise<Array<Wallet>> {\n const network = await this.getCurrentNetwork()\n return this.getAllWallets({\n ...filter,\n networkIds: [network.id],\n })\n }\n\n async getWallet(partyId: PartyId): Promise<Wallet | null> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const constraint: WalletUniqueConstraint = {\n partyId,\n networkId: network.id,\n userId,\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where((eb) => eb.and(constraint))\n .executeTakeFirst()\n\n if (!row) return null\n\n const rightRows = await this.db\n .selectFrom('userPartyRights')\n .select('right')\n .where((eb) => eb.and(constraint))\n .execute()\n\n return {\n ...toWallet(row),\n rights: rightRows\n .map(({ right }) => fromPartyRight(right))\n .filter((right) => right !== undefined),\n }\n }\n\n async getWalletByJwt(\n userId: string,\n partyId: PartyId,\n audiences: string[]\n ): Promise<Wallet | undefined> {\n const networks = (\n await this.db.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n const network = resolveSelfIssuedNetworkByAudiences(networks, audiences)\n if (!network) {\n return undefined\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .where('partyId', '=', partyId)\n .where('networkId', '=', network.id)\n .executeTakeFirst()\n\n return row ? toWallet(row) : undefined\n }\n\n async getPrimaryWallet(): Promise<Wallet | undefined> {\n const wallets = await this.getWallets()\n return wallets.find((w) => w.primary === true)\n }\n\n async setPrimaryWallet(partyId: PartyId): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n const wallets = await this.getWallets()\n\n if (!wallets.some((w) => w.partyId === partyId)) {\n throw new Error(\n `Wallet with partyId \"${partyId}\" not found in network \"${network.id}\"`\n )\n }\n\n const primary = wallets.find((w) => w.primary === true)\n\n await this.db.transaction().execute(async (trx) => {\n if (primary) {\n // Unset primary for current network only\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', primary.partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n // Set new primary for current network\n await trx\n .updateTable('wallets')\n .set({ primary: 1 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async addWallet(wallet: Wallet): Promise<void> {\n this.logger.info('Adding wallet')\n const userId = this.assertConnected()\n\n const wallets = await this.getWallets()\n if (\n wallets.some(\n (w) =>\n w.partyId === wallet.partyId &&\n w.networkId === wallet.networkId\n )\n ) {\n throw new Error(\n `Wallet with partyId \"${wallet.partyId}\" networkId \"${wallet.networkId}\" userId \"${userId}\" already exists`\n )\n }\n\n if (\n !wallet.disabled &&\n wallet.status === 'allocated' &&\n !wallets.some((wallet) => wallet.primary)\n ) {\n // If there is no primary wallet yet, set current one as primary (unless disabled or not allocated).\n // In regular case it would be the first added wallet.\n wallet.primary = true\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (wallet.primary) {\n // If the new wallet is primary, set all others in the same network and for this user to non-primary\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('primary', '=', 1),\n eb('networkId', '=', wallet.networkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n await trx\n .insertInto('wallets')\n .values(fromWallet(wallet, userId))\n .execute()\n\n if (wallet.rights && wallet.rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n wallet.rights.map((right) => ({\n userId,\n networkId: wallet.networkId,\n partyId: wallet.partyId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n async updateWallet(params: UpdateWallet): Promise<void> {\n const { partyId, networkId, rights } = params\n this.logger.info('Updating wallet')\n const userId = this.assertConnected()\n\n const updates = toWalletUpdateProperties(params)\n\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n if (Object.keys(updates).length === 0 && rights === undefined) return\n\n await this.db.transaction().execute(async (trx) => {\n if (Object.keys(updates).length > 0) {\n await trx\n .updateTable('wallets')\n .set(updates)\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n\n if (rights !== undefined) {\n await trx\n .deleteFrom('userPartyRights')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId: targetNetworkId,\n partyId,\n right,\n }))\n )\n .execute()\n }\n }\n })\n }\n\n async removeWallet(partyId: PartyId): Promise<void> {\n this.logger.info('Removing wallet')\n const userId = this.assertConnected()\n\n // Remove wallet from current network only\n const network = await this.getCurrentNetwork()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('wallets')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async getUserRights(networkId?: string): Promise<Array<UserLevelRight>> {\n const userId = this.assertConnected()\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n const rows = await this.db\n .selectFrom('userRights')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', targetNetworkId),\n ])\n )\n .execute()\n\n return rows\n .map((row) => fromUserRight(row.right))\n .filter((right): right is UserLevelRight => right !== undefined)\n }\n\n async setUserRights(\n networkId: string,\n rights: Array<UserLevelRight>\n ): Promise<void> {\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('userRights')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', networkId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n // Session methods\n async getSession(accessToken: AccessToken): Promise<Session | undefined> {\n const userId = this.assertConnected()\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async listSessions(): Promise<Array<Session>> {\n const userId = this.assertConnected()\n const rows = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n return rows.map((row) => toSession(row))\n }\n\n async setSession(session: Session): Promise<void> {\n const userId = this.assertConnected()\n\n if (!session.origin) {\n throw new Error('Session origin is required')\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (session.accessToken) {\n // Regular session - one user can have only one session per origin.\n // Tokenless sessions are not replaced by duplicates.\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n eb('accessToken', 'is not', null),\n ])\n )\n .execute()\n this.logger.debug(deleted, 'Deleted old session')\n }\n\n const inserted = await trx\n .insertInto('sessions')\n .values({\n ...session,\n accessToken: session.accessToken ?? null,\n userId,\n })\n .execute()\n\n this.logger.debug(inserted, 'Inserted new session')\n })\n }\n\n async getOnboardingSession(\n sessionId: string\n ): Promise<Session | undefined> {\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async upgradeOnboardingSession(\n sessionId: string,\n accessToken: AccessToken\n ): Promise<Session> {\n const userId = this.assertConnected()\n\n return this.db.transaction().execute(async (trx) => {\n const row = await trx\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('userId', '=', userId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n if (!row) {\n throw new Error('Onboarding session not found')\n }\n\n await trx\n .deleteFrom('sessions')\n .where('userId', '=', userId)\n .where('origin', '=', row.origin)\n .where('id', '!=', sessionId)\n .execute()\n await trx\n .updateTable('sessions')\n .set({ accessToken })\n .where('id', '=', sessionId)\n .execute()\n\n return toSession({ ...row, accessToken })\n })\n }\n\n async removeSession(accessToken: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .execute()\n }\n\n /**\n * Lists all pending transactions across all users.\n */\n\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.or([\n eb('status', '=', 'pending'),\n eb('status', '=', 'awaiting-signature'),\n ])\n )\n .execute()\n\n return rows.map((row) => toTransaction(row))\n }\n\n // IDP methods\n\n async getIdp(idpId: string): Promise<Idp> {\n const idps = await this.listIdps()\n if (!idps) throw new Error('No IDPs available')\n\n const idp = idps.find((n) => n.id === idpId)\n if (!idp) throw new Error(`IDP \"${idpId}\" not found`)\n return idp\n }\n\n async listIdps(): Promise<Array<Idp>> {\n // All IDPs are global for now -- TO-DO: user-specific IDPs\n const query = this.db.selectFrom('idps').selectAll()\n\n const idps = await query.execute()\n return idps.map((table) => toIdp(table))\n }\n\n async updateIdp(idp: Idp): Promise<void> {\n // todo: check and compare userid of existing idp\n await this.db.transaction().execute(async (trx) => {\n const idpEntry = fromIdp(idp)\n this.logger.info(idpEntry, 'Updating idp table')\n await trx\n .updateTable('idps')\n .set(idpEntry)\n .where('id', '=', idp.id)\n .execute()\n })\n }\n\n async addIdp(idp: Idp): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n const idpAlreadyExists = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idp.id)\n .executeTakeFirst()\n if (idpAlreadyExists) {\n throw new Error(`IDP ${idp.id} already exists`)\n } else {\n await trx.insertInto('idps').values(fromIdp(idp)).execute()\n }\n })\n }\n\n async removeIdp(idpId: string): Promise<void> {\n const networks = await this.listNetworks()\n if (networks.some((n) => n.identityProviderId === idpId)) {\n throw new Error(\n `Cannot delete IDP ${idpId} as it is in use by existing networks`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const idp = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idpId)\n .executeTakeFirst()\n if (!idp) {\n throw new Error(`IDP ${idpId} does not exists`)\n }\n await trx.deleteFrom('idps').where('id', '=', idpId).execute()\n })\n }\n\n // Network methods\n async getNetwork(networkId: string): Promise<Network> {\n const networks = await this.listNetworks()\n if (!networks) throw new Error('No networks available')\n\n const network = networks.find((n) => n.id === networkId)\n if (!network) throw new Error(`Network \"${networkId}\" not found`)\n return network\n }\n\n async getCurrentNetwork(): Promise<Network> {\n const userId = this.assertConnected()\n const token = this.authContext?.accessToken\n const onboardingSessionId =\n this.authContext && !this.authContext.isApiKey\n ? this.authContext.sessionId\n : undefined\n if (!token && !onboardingSessionId) {\n throw providerErrors.unauthorized({ message: 'No session found' })\n }\n\n const sessionRow = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .where((eb) =>\n token\n ? eb('accessToken', '=', token)\n : eb.and([\n eb('id', '=', onboardingSessionId!),\n eb('accessToken', 'is', null),\n ])\n )\n .executeTakeFirst()\n if (!sessionRow) {\n throw providerErrors.unauthorized({ message: 'No session found' })\n }\n\n const session = toSession(sessionRow)\n const networkId = session.network\n if (!networkId) {\n throw new Error('No current network set in session')\n }\n\n const networks = await this.listNetworks()\n const network = networks.find((n) => n.id === networkId)\n if (!network) {\n throw new Error(`Network \"${networkId}\" not found`)\n }\n return network\n }\n\n async getNetworkForTokenVerification(\n networkId: string\n ): Promise<Network | undefined> {\n // Not scoped by userId: key id resolution happens during token\n // verification, before there is an authenticated user.\n const row = await this.db\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!row) return undefined\n\n const network = toNetwork(row)\n return network.auth.method === 'self_signed' ? network : undefined\n }\n\n async listNetworks(): Promise<Array<Network>> {\n let query = this.db.selectFrom('networks').selectAll()\n\n if (this.authContext) {\n const userId = this.assertConnected()\n query = query.where((eb) =>\n eb.or([\n eb('userId', 'is', null), // Global networks\n eb('userId', '=', userId), // User-specific networks\n ])\n )\n } else {\n query = query.where('userId', 'is', null) // Only global networks\n }\n\n const networks = await query.execute()\n return networks.map((table) => toNetwork(table))\n }\n\n async updateNetwork(network: Network): Promise<void> {\n // todo: check and compare idpId of existing network\n this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const existing = (\n await trx.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n assertUniqueSelfIssuedAudience(existing, network, network.id)\n\n // we do not set a userId for now and leave all networks global when updating\n const networkEntry = fromNetwork(network, undefined)\n this.logger.info(networkEntry, 'Updating network table')\n await trx\n .updateTable('networks')\n .set(networkEntry)\n .where('id', '=', network.id)\n .execute()\n })\n }\n\n async addNetwork(network: Network): Promise<void> {\n const userId = this.authContext?.userId\n const idps = await this.listIdps()\n const networkIdp = idps.find(\n (idp) => idp.id === network.identityProviderId\n )\n\n if (!networkIdp) {\n throw new Error(\n `Identity provider \"${network.identityProviderId}\" not found`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const networkAlreadyExists = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', network.id)\n .executeTakeFirst()\n if (networkAlreadyExists) {\n throw new Error(`Network ${network.id} already exists`)\n }\n\n const existing = (\n await trx.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n assertUniqueSelfIssuedAudience(existing, network)\n\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\n })\n }\n\n async removeNetwork(networkId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const network = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!network) {\n throw new Error(`Network ${networkId} does not exists`)\n }\n if (network.userId !== userId) {\n throw new Error(\n `Network ${networkId} is not owned by user ${userId}`\n )\n }\n await trx\n .deleteFrom('networks')\n .where('id', '=', networkId)\n .execute()\n })\n }\n\n private mergeTransactionStatusUpdate(\n existing: Transaction,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Transaction {\n const payload = updates.payload ?? existing.payload\n const signedAt = updates.signedAt ?? existing.signedAt\n const externalTxId = updates.externalTxId ?? existing.externalTxId\n const failureReason = updates.failureReason ?? existing.failureReason\n\n return {\n id: existing.id,\n commandId: existing.commandId,\n status,\n preparedTransaction: existing.preparedTransaction,\n preparedTransactionHash: existing.preparedTransactionHash,\n origin: existing.origin,\n ...(payload !== undefined && { payload }),\n ...(existing.createdAt !== undefined && {\n createdAt: existing.createdAt,\n }),\n ...(signedAt !== undefined && { signedAt }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(failureReason !== undefined && { failureReason }),\n }\n }\n\n // Transaction methods\n async setTransaction(transaction: Transaction): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n await this.db\n .insertInto('transactions')\n .values(fromTransaction(transaction, userId, network.id))\n .execute()\n }\n\n async setTransactionSigned(\n transactionId: string,\n signedAt: Date,\n externalTxId?: string,\n opts?: { expectedStatus: Transaction['status'] }\n ): Promise<boolean> {\n return await this.setTransactionStatus(\n transactionId,\n 'signed',\n {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n },\n opts\n )\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {},\n opts?: { expectedStatus?: Transaction['status'] }\n ): Promise<boolean> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getTransaction(transactionId)\n if (!existing) {\n throw new Error(`Transaction not found with id: ${transactionId}`)\n }\n if (opts?.expectedStatus && existing.status !== opts.expectedStatus) {\n return false\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n const res = await this.db\n .updateTable('transactions')\n .set(fromTransaction(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ...(opts?.expectedStatus\n ? [eb('status', '=', opts.expectedStatus)]\n : []),\n ])\n )\n .executeTakeFirst()\n\n return res.numUpdatedRows > 0n\n }\n\n async getTransaction(\n transactionId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async getLatestTransactionByCommandId(\n commandId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('commandId', '=', commandId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .executeTakeFirst()\n\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async transactionsCount(): Promise<number> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n const result = await this.db\n .selectFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .select((eb) => eb.fn.count<number>('id').as('count'))\n .executeTakeFirstOrThrow()\n\n return Number(result.count)\n }\n\n async listTransactions(options?: ListTransactionsOptions) {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const { cursor, limit } = options ?? {}\n const lim = limit ? Math.min(limit, 100) : 100\n\n let query = this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .orderBy('id', 'desc')\n .limit(lim + 1)\n\n if (cursor) {\n const split = cursor.split('::')\n const dateString = split[0] === 'null' ? null : split[0]\n const cursorId = split[1]\n\n query = query.where((eb) => {\n if (dateString === null) {\n return eb.and([\n eb('createdAt', 'is', null),\n eb('id', '<', cursorId),\n ])\n }\n\n return eb.or([\n eb('createdAt', '<', dateString),\n eb.and([\n eb('createdAt', '=', dateString),\n eb('id', '<', split[1]),\n ]),\n eb('createdAt', 'is', null),\n ])\n })\n }\n\n const rows = await query.execute()\n const txs = rows.map((r) => toTransaction(r))\n\n const hasNextPage = txs.length > lim\n if (hasNextPage) {\n txs.pop()\n }\n\n if (txs.length === 0) {\n return {\n transactions: [],\n nextCursor: null,\n }\n }\n\n const lastTx = txs[txs.length - 1]\n if (lastTx === undefined) {\n return {\n transactions: txs,\n nextCursor: null,\n }\n }\n\n //handle case for if timestamp is null\n if (lastTx.createdAt) {\n const d = new Date(lastTx.createdAt).toISOString()\n const nextCursor = hasNextPage ? `${d}::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n } else {\n const nextCursor = hasNextPage ? `null::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n }\n }\n\n async removeTransaction(transactionId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n private mergeMessageRawStatusUpdate(\n existing: MessageRaw,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): MessageRaw {\n const signedAt = updates.signedAt ?? existing.signedAt\n const signature = updates.signature ?? existing.signature\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n }\n }\n\n // Message signing request methods\n async setMessageRaw(message: MessageRaw): Promise<void> {\n const userId = this.assertConnected()\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n const network = await this.getCurrentNetwork()\n await this.db\n .insertInto('messagesRaw')\n .values(fromMessageRaw(message, userId, network.id))\n .execute()\n }\n\n async setMessageRawStatus(\n messageId: string,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getMessageRaw(messageId)\n if (!existing) {\n throw new Error(`MessageRaw not found with id: ${messageId}`)\n }\n\n const updated = this.mergeMessageRawStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('messagesRaw')\n .set(fromMessageRaw(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getMessageRaw(messageId: string): Promise<MessageRaw | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const message = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return message ? toMessageRaw(message) : undefined\n }\n\n async listMessageRaws(): Promise<Array<MessageRaw>> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const messages = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .execute()\n return messages.map((m) => toMessageRaw(m))\n }\n\n async removeMessageRaw(messageId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('messagesRaw')\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n // API keys\n async addApiKey(apiKey: ApiKey): Promise<void> {\n const userId = this.assertConnected()\n if (apiKey.userId !== userId) {\n throw new Error(\n `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`\n )\n }\n\n const network = await this.getCurrentNetwork()\n if (apiKey.networkId !== network.id) {\n throw new Error(\n `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`\n )\n }\n\n await this.db.insertInto('apiKeys').values(toApiKey(apiKey)).execute()\n }\n\n async listApiKeys(): Promise<Array<ApiKey>> {\n const query = this.db\n .selectFrom('apiKeys')\n .selectAll()\n .orderBy('createdAt', 'desc')\n\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const apiKeys = await query\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n\n return apiKeys.map(fromApiKey)\n }\n\n async getApiKey(digest: string): Promise<ApiKey | undefined> {\n const apiKey = await this.db\n .selectFrom('apiKeys')\n .selectAll()\n .where((eb) => eb('digest', '=', digest))\n .executeTakeFirst()\n\n return apiKey ? fromApiKey(apiKey) : undefined\n }\n\n async removeApiKey(apiKeyId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('apiKeys')\n .where((eb) =>\n eb.and([\n eb('id', '=', apiKeyId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n}\n\nexport const connection = (config: StoreConfig) => {\n let database\n switch (config.connection.type) {\n case 'sqlite':\n database = new Database(config.connection.database)\n // normally sqlite3 has foreign_keys = OFF for each connection,\n // but better-sqlite3 uses custom build with compile flag SQLITE_DEFAULT_FOREIGN_KEYS=1,\n // making it ON by default.\n // Set explicitly ON anyway as redundancy\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'postgres':\n return new Kysely<DB>({\n dialect: new PostgresDialect({\n pool: new pg.Pool(config.connection),\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'memory':\n database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Umzug, type MigrationMeta, type UmzugStorage } from 'umzug'\nimport type { Kysely } from 'kysely'\nimport type { DB } from './schema'\n\nclass KyselyStorage implements UmzugStorage {\n constructor(private db: Kysely<DB>) {}\n\n private async ensureTable() {\n await this.db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'text', (col) => col.primaryKey())\n .addColumn('executedAt', 'text', (col) => col.notNull())\n .execute()\n }\n\n async executed(): Promise<string[]> {\n await this.ensureTable()\n const rows = await this.db\n .selectFrom('migrations')\n .select('name')\n .execute()\n return rows.map((r) => r.name)\n }\n\n async logMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .insertInto('migrations')\n .values({ name, executedAt: new Date().toISOString() })\n .execute()\n }\n\n async unlogMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute()\n }\n}\n\nexport const migrator = (db: Kysely<DB>) => {\n const ext = import.meta.url.endsWith('.ts') ? 'ts' : 'js'\n const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname\n return new Umzug({\n migrations: {\n glob: glob,\n resolve: ({ name, path, context }) => {\n // Dynamic import for ESM\n return {\n name,\n up: async () => {\n console.log(path)\n const { up } = await import(path!)\n return up(context)\n },\n down: async () => {\n const { down } = await import(path!)\n return down(context)\n },\n }\n },\n },\n context: db,\n storage: new KyselyStorage(db),\n logger: console,\n })\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport type { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport type { Logger } from 'pino'\nimport type { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig,\n logger: Logger\n): Promise<void> {\n const store = new StoreSql(db, logger)\n\n // Load all IDPs from config into the store\n await Promise.all(config.idps.map((idp) => store.addIdp(idp)))\n\n // Load all networks from config into the store\n await Promise.all(\n config.networks.map((network) => store.addNetwork(network))\n )\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Command } from 'commander'\nimport { connection } from './store-sql.js'\nimport { migrator } from './migrator.js'\nimport type {\n StoreConfig,\n BootstrapConfig,\n} from '@canton-network/core-wallet-store'\nimport { pino } from 'pino'\nimport { bootstrap } from './bootstrap.js'\n\nconst logger = pino({ name: 'main', level: 'debug' })\n\nexport function createCLI(\n config: StoreConfig,\n bootstrapConfig?: BootstrapConfig\n): Command {\n const program = new Command()\n\n program\n .command('up')\n .description('Run all pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('down')\n .description('Rollback last migration')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.down()\n await db.destroy()\n })\n\n program\n .command('status')\n .description('Show executed and pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n const pending = await umzug.pending()\n\n console.log('Executed migrations:', executed)\n console.log('Pending migrations:', pending)\n\n await db.destroy()\n })\n\n program\n .command('reset')\n .description('Rollback all migrations and reapply them')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n\n // Rollback all executed migrations in reverse order\n for (const migration of executed.reverse()) {\n await umzug.down({ to: migration.name })\n }\n\n // Reapply all migrations\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('bootstrap')\n .description('Bootstrap DB from config')\n .action(async () => {\n if (!bootstrapConfig) {\n throw new Error(\n 'Bootstrap config (idps/networks) is required for the bootstrap command'\n )\n }\n const db = connection(config)\n await bootstrap(db, bootstrapConfig, logger)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;;AAwJA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAElE,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MAAM,iCAAiC,MAAM,IAAI;GAG/D,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,WAAW,MAAM;GACrB;EAEJ,KAAK;GACD,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MACN,uCAAuC,MAAM,IACjD;GAEJ,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;GAClB;EACJ,KAAK,eACD,OAAO;GACH,IAAI,MAAM;GACV,MAAM,MAAM;EAChB;CACR;AACJ;AAEA,MAAa,WAAW,QAAuB;CAC3C,QAAQ,IAAI,MAAZ;EACI,KAAK,SACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW,IAAI;EACnB;EACJ,KAAK,eACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW;EACf;EACJ,KAAK,eACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ;GACR,WAAW;EACf;CACR;AACJ;AAEA,MAAa,aAAa,UAAiC;CACvD,OAAO;EACH,MAAM,MAAM;EACZ,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KAAK,WAAW,MAAM;EAC5B,MAAM,UAAU,IAAI,iBAAiB,MAAM;EAC3C,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,OAAO;AACX"}
@@ -1,5 +1,5 @@
1
- import { Kysely } from 'kysely';
2
- import { DB } from '../schema.js';
1
+ import { type Kysely } from 'kysely';
2
+ import type { DB } from '../schema.js';
3
3
  export declare function up(db: Kysely<DB>): Promise<void>;
4
4
  export declare function down(db: Kysely<DB>): Promise<void>;
5
5
  //# sourceMappingURL=016-add-failure-reason-and-awaiting-signature.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"016-add-failure-reason-and-awaiting-signature.d.ts","sourceRoot":"","sources":["../../src/migrations/016-add-failure-reason-and-awaiting-signature.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAO,MAAM,QAAQ,CAAA;AACpC,OAAO,EAAE,EAAE,EAAE,MAAM,cAAc,CAAA;AAEjC,wBAAsB,EAAE,CAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAatD;AAED,wBAAsB,IAAI,CAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAaxD"}
1
+ {"version":3,"file":"016-add-failure-reason-and-awaiting-signature.d.ts","sourceRoot":"","sources":["../../src/migrations/016-add-failure-reason-and-awaiting-signature.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,MAAM,EAAO,MAAM,QAAQ,CAAA;AACzC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,cAAc,CAAA;AAEtC,wBAAsB,EAAE,CAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAatD;AAED,wBAAsB,IAAI,CAAC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAaxD"}
@@ -1,5 +1,5 @@
1
- import { Kysely } from 'kysely';
2
- import { DB } from '../../schema';
1
+ import { type Kysely } from 'kysely';
2
+ import type { DB } from '../../schema';
3
3
  export declare function insertTransaction(db: Kysely<DB>, row: {
4
4
  id?: string;
5
5
  commandId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"016-add-failure-reason-and-awaiting-signature.d.ts","sourceRoot":"","sources":["../../../src/migrations-test/seeds/016-add-failure-reason-and-awaiting-signature.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAO,MAAM,QAAQ,CAAA;AACpC,OAAO,EAAE,EAAE,EAAE,MAAM,cAAc,CAAA;AAEjC,wBAAsB,iBAAiB,CACnC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,EACd,GAAG,EAAE;IACD,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B,uBAAuB,CAAC,EAAE,MAAM,CAAA;IAChC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC5B,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC7B,SAAS,EAAE,MAAM,CAAA;CACpB,GACF,OAAO,CAAC,IAAI,CAAC,CAqBf"}
1
+ {"version":3,"file":"016-add-failure-reason-and-awaiting-signature.d.ts","sourceRoot":"","sources":["../../../src/migrations-test/seeds/016-add-failure-reason-and-awaiting-signature.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,MAAM,EAAO,MAAM,QAAQ,CAAA;AACzC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,cAAc,CAAA;AAEtC,wBAAsB,iBAAiB,CACnC,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,EACd,GAAG,EAAE;IACD,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B,uBAAuB,CAAC,EAAE,MAAM,CAAA;IAChC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC5B,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC7B,SAAS,EAAE,MAAM,CAAA;CACpB,GACF,OAAO,CAAC,IAAI,CAAC,CAqBf"}
@@ -14,6 +14,7 @@ export declare class StoreSql implements BaseStore, AuthAware<StoreSql> {
14
14
  getAllWallets(filter?: WalletFilter): Promise<Array<Wallet>>;
15
15
  getWallets(filter?: CurrentNetworkWalletFilter): Promise<Array<Wallet>>;
16
16
  getWallet(partyId: PartyId): Promise<Wallet | null>;
17
+ getWalletByJwt(userId: string, partyId: PartyId, audiences: string[]): Promise<Wallet | undefined>;
17
18
  getPrimaryWallet(): Promise<Wallet | undefined>;
18
19
  setPrimaryWallet(partyId: PartyId): Promise<void>;
19
20
  addWallet(wallet: Wallet): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"store-sql.d.ts","sourceRoot":"","sources":["../src/store-sql.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAClC,OAAO,EACH,KAAK,WAAW,EAEhB,KAAK,SAAS,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AI,CAAC;IAe7D,OAAO,CAAC,2BAA2B;IAiB7B,aAAa,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAcjD,mBAAmB,CACrB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC,EAC5B,OAAO,GAAE,sBAA2B,GACrC,OAAO,CAAC,IAAI,CAAC;IA2BV,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC;IAiBjE,eAAe,IAAI,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAkB7C,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAgBlD,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkBxC,WAAW,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAoBrC,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAUtD,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CActD;AAED,eAAO,MAAM,UAAU,GAAI,QAAQ,WAAW,eAiC7C,CAAA"}
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@canton-network/core-wallet-store-sql",
3
- "version": "1.14.0",
3
+ "version": "1.15.0",
4
4
  "type": "module",
5
5
  "description": "SQL implementation of the Store API",
6
6
  "license": "Apache-2.0",
7
7
  "author": "Marc Juchli <marc.juchli@digitalasset.com>",
8
+ "sideEffects": false,
8
9
  "main": "dist/index.cjs",
9
10
  "module": "dist/index.js",
10
11
  "types": "dist/index.d.ts",
@@ -17,11 +18,11 @@
17
18
  }
18
19
  },
19
20
  "dependencies": {
20
- "@canton-network/core-ledger-client": "^1.13.0",
21
- "@canton-network/core-rpc-errors": "^1.12.0",
22
- "@canton-network/core-types": "^1.13.0",
23
- "@canton-network/core-wallet-auth": "^1.13.0",
24
- "@canton-network/core-wallet-store": "^1.14.0",
21
+ "@canton-network/core-ledger-client": "1.14.0",
22
+ "@canton-network/core-rpc-errors": "1.13.0",
23
+ "@canton-network/core-types": "1.14.0",
24
+ "@canton-network/core-wallet-auth": "1.14.0",
25
+ "@canton-network/core-wallet-store": "1.15.0",
25
26
  "better-sqlite3": "^12.11.1",
26
27
  "commander": "^14.0.3",
27
28
  "kysely": "^0.28.17",
@@ -38,7 +39,7 @@
38
39
  "pino-test": "^1.1.0",
39
40
  "tsdown": "^0.22.9",
40
41
  "tsx": "^4.23.0",
41
- "typescript": "^5.9.3",
42
+ "typescript": "^6.0.3",
42
43
  "vitest": "^5.0.1"
43
44
  },
44
45
  "files": [
@@ -56,13 +57,20 @@
56
57
  "bugs": {
57
58
  "url": "https://github.com/canton-network/wallet/issues"
58
59
  },
60
+ "nx": {
61
+ "targets": {
62
+ "test": {
63
+ "options": {
64
+ "args": "--project=node"
65
+ }
66
+ }
67
+ }
68
+ },
59
69
  "scripts": {
60
70
  "build": "tsdown --onSuccess \"tsc\" && tsc -b tsconfig.migrations.json",
61
- "dev": "tsdown --watch --onSuccess \"tsc -p tsconfig.types.json && tsc -b tsconfig.migrations.json\"",
71
+ "dev": "tsdown --watch --onSuccess \"tsc && tsc -b tsconfig.migrations.json\"",
62
72
  "flatpack": "pnpm pack --pack-destination \"$FLATPACK_OUTDIR\"",
63
73
  "clean": "tsc -b --clean; rm -rf dist",
64
- "test": "vitest run --project node",
65
- "test:coverage": "vitest run --project node --coverage",
66
74
  "test:migrations": "vitest run --project migrations",
67
75
  "migrations:check-lock": "tsx ../../scripts/src/check-migration-lock.ts",
68
76
  "migrations:update-lock": "tsx ../../scripts/src/check-migration-lock.ts --update"