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