forked from hummingbot/gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
329 lines (287 loc) · 10 KB
/
utils.ts
File metadata and controls
329 lines (287 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { FastifyInstance } from 'fastify';
import fse from 'fs-extra';
import { Ethereum } from '../chains/ethereum/ethereum';
import { Solana } from '../chains/solana/solana';
import { ConfigManagerCertPassphrase } from '../services/config-manager-cert-passphrase';
import {
getInitializedChain,
UnsupportedChainException,
Chain,
getSupportedChains,
} from '../services/connection-manager';
import { logger } from '../services/logger';
import {
AddWalletRequest,
AddWalletResponse,
RemoveWalletRequest,
SignMessageRequest,
SignMessageResponse,
GetWalletResponse,
} from './schemas';
export const walletPath = './conf/wallets';
// Utility to sanitize file paths and prevent path traversal attacks
export function sanitizePathComponent(input: string): string {
// Remove any characters that could be used for directory traversal
return input.replace(/[\/\\:*?"<>|]/g, '');
}
// Import supported chains function
// Validate chain name against known chains to prevent injection
export function validateChainName(chain: string): boolean {
if (!chain) return false;
try {
// Get supported chains directly without caching
const supportedChains = getSupportedChains();
return supportedChains.includes(chain.toLowerCase());
} catch (error) {
// Fallback to hardcoded list if there's an error
logger.warn(
`Failed to get supported chains: ${error.message}. Using fallback list.`,
);
return ['ethereum', 'solana'].includes(chain.toLowerCase());
}
}
// Get safe path for wallet files, with chain and address validation
export function getSafeWalletFilePath(chain: string, address: string): string {
// Validate chain name
if (!validateChainName(chain)) {
throw new Error(`Invalid chain name: ${chain}`);
}
// Sanitize both inputs
const safeChain = sanitizePathComponent(chain.toLowerCase());
const safeAddress = sanitizePathComponent(address);
// Ensure address isn't empty after sanitization
if (!safeAddress) {
throw new Error('Invalid wallet address');
}
return `${walletPath}/${safeChain}/${safeAddress}.json`;
}
export async function mkdirIfDoesNotExist(path: string): Promise<void> {
const exists = await fse.pathExists(path);
if (!exists) {
await fse.mkdir(path, { recursive: true });
}
}
export async function addWallet(
fastify: FastifyInstance,
req: AddWalletRequest,
): Promise<AddWalletResponse> {
const passphrase = ConfigManagerCertPassphrase.readPassphrase();
if (!passphrase) {
throw fastify.httpErrors.internalServerError('No passphrase configured');
}
// Validate chain name
if (!validateChainName(req.chain)) {
throw fastify.httpErrors.badRequest(
`Unrecognized chain name: ${req.chain}`,
);
}
let connection: Chain;
let address: string | undefined;
let encryptedPrivateKey: string | undefined;
// Default to mainnet-beta for Solana or mainnet for other chains
const network = req.chain === 'solana' ? 'mainnet-beta' : 'mainnet';
try {
connection = await getInitializedChain<Chain>(req.chain, network);
} catch (e) {
if (e instanceof UnsupportedChainException) {
throw fastify.httpErrors.badRequest(
`Unrecognized chain name: ${req.chain}`,
);
}
throw e;
}
try {
if (connection instanceof Ethereum) {
address = connection.getWalletFromPrivateKey(req.privateKey).address;
// Further validate Ethereum address
address = Ethereum.validateAddress(address);
encryptedPrivateKey = await connection.encrypt(
req.privateKey,
passphrase,
);
} else if (connection instanceof Solana) {
address = connection
.getKeypairFromPrivateKey(req.privateKey)
.publicKey.toBase58();
// Further validate Solana address
address = Solana.validateAddress(address);
encryptedPrivateKey = await connection.encrypt(
req.privateKey,
passphrase,
);
}
if (address === undefined || encryptedPrivateKey === undefined) {
throw new Error('Unable to retrieve wallet address');
}
} catch (_e: unknown) {
throw fastify.httpErrors.badRequest(
`Unable to retrieve wallet address for provided private key: ${req.privateKey.substring(0, 5)}...`,
);
}
// Create safe path for wallet storage
const safeChain = sanitizePathComponent(req.chain.toLowerCase());
const path = `${walletPath}/${safeChain}`;
await mkdirIfDoesNotExist(path);
// Sanitize address for filename
const safeAddress = sanitizePathComponent(address);
await fse.writeFile(`${path}/${safeAddress}.json`, encryptedPrivateKey);
return { address };
}
export async function removeWallet(
fastify: FastifyInstance,
req: RemoveWalletRequest,
): Promise<void> {
logger.info(`Removing wallet: ${req.address} from chain: ${req.chain}`);
try {
// Validate chain name
if (!validateChainName(req.chain)) {
throw fastify.httpErrors.badRequest(
`Unrecognized chain name: ${req.chain}`,
);
}
// Validate the address based on chain type
let validatedAddress: string;
if (req.chain.toLowerCase() === 'ethereum') {
validatedAddress = Ethereum.validateAddress(req.address);
} else if (req.chain.toLowerCase() === 'solana') {
validatedAddress = Solana.validateAddress(req.address);
} else {
// This should not happen due to validateChainName check, but just in case
throw new Error(`Unsupported chain: ${req.chain}`);
}
// Create safe file path
const safeChain = sanitizePathComponent(req.chain.toLowerCase());
const safeAddress = sanitizePathComponent(validatedAddress);
// Remove file
await fse.remove(`${walletPath}/${safeChain}/${safeAddress}.json`);
} catch (error) {
if (
error.message.includes('Invalid') ||
error.message.includes('Unrecognized')
) {
throw fastify.httpErrors.badRequest(error.message);
}
throw fastify.httpErrors.internalServerError(
`Failed to remove wallet: ${error.message}`,
);
}
}
export async function signMessage(
fastify: FastifyInstance,
req: SignMessageRequest,
): Promise<SignMessageResponse> {
logger.info(
`Signing message for wallet: ${req.address} on chain: ${req.chain}`,
);
try {
// Validate chain name
if (!validateChainName(req.chain)) {
throw fastify.httpErrors.badRequest(
`Unrecognized chain name: ${req.chain}`,
);
}
// Validate the address based on chain type
let validatedAddress: string;
if (req.chain.toLowerCase() === 'ethereum') {
validatedAddress = Ethereum.validateAddress(req.address);
} else if (req.chain.toLowerCase() === 'solana') {
validatedAddress = Solana.validateAddress(req.address);
} else {
throw new Error(`Unsupported chain: ${req.chain}`);
}
// Get connection with validated network parameter
const safeNetwork = sanitizePathComponent(req.network);
const connection = await getInitializedChain(req.chain, safeNetwork);
// getWallet now includes its own address validation
const wallet = await (connection as any).getWallet(validatedAddress);
if (!wallet) {
throw fastify.httpErrors.notFound(
`Wallet ${req.address} not found for chain ${req.chain}`,
);
}
const signature = await wallet.signMessage(req.message);
return { signature };
} catch (error) {
if (
error.message.includes('Invalid') ||
error.message.includes('Unrecognized')
) {
throw fastify.httpErrors.badRequest(error.message);
}
if (error.statusCode) {
throw error;
}
throw fastify.httpErrors.internalServerError(
`Failed to sign message: ${error.message}`,
);
}
}
async function getDirectories(source: string): Promise<string[]> {
await mkdirIfDoesNotExist(source);
const files = await fse.readdir(source, { withFileTypes: true });
return files
.filter((dirent) => dirent.isDirectory())
.map((dirent) => dirent.name);
}
function dropExtension(path: string): string {
return path.substr(0, path.lastIndexOf('.')) || path;
}
async function getJsonFiles(source: string): Promise<string[]> {
try {
const files = await fse.readdir(source, { withFileTypes: true });
return files
.filter((f) => f.isFile() && f.name.endsWith('.json'))
.map((f) => f.name);
} catch (error) {
// Return empty array if directory doesn't exist or is not accessible
return [];
}
}
export async function getWallets(
fastify: FastifyInstance,
): Promise<GetWalletResponse[]> {
logger.info('Getting all wallets');
try {
// Create wallet directory if it doesn't exist
await mkdirIfDoesNotExist(walletPath);
// Get only valid chain directories
const validChains = ['ethereum', 'solana'];
const allDirs = await getDirectories(walletPath);
const chains = allDirs.filter((dir) =>
validChains.includes(dir.toLowerCase()),
);
const responses: GetWalletResponse[] = [];
for (const chain of chains) {
// Sanitize the chain name to prevent directory traversal
const safeChain = sanitizePathComponent(chain);
const walletFiles = await getJsonFiles(`${walletPath}/${safeChain}`);
// Filter out any suspicious filenames that might have survived
const safeWalletAddresses = walletFiles
.map((file) => dropExtension(file))
// Additional validation for addresses based on chain type
.filter((address) => {
try {
if (chain.toLowerCase() === 'ethereum') {
// Basic Ethereum address validation (0x + 40 hex chars)
return /^0x[a-fA-F0-9]{40}$/i.test(address);
} else if (chain.toLowerCase() === 'solana') {
// Basic Solana address length check
return address.length >= 32 && address.length <= 44;
}
return false;
} catch {
return false;
}
});
responses.push({
chain: safeChain,
walletAddresses: safeWalletAddresses,
});
}
return responses;
} catch (error) {
throw fastify.httpErrors.internalServerError(
`Failed to get wallets: ${error.message}`,
);
}
}