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