-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.ts
416 lines (367 loc) · 11.2 KB
/
index.ts
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import {
ArweaveFileObject,
FileInfoRequest,
FileInfoResponse,
FileObjectType,
IpfsFileObject,
StorageReadable,
UrlFileObject,
EncryptMethod
} from '../../@types/fileObject.js'
import { OceanNodeConfig } from '../../@types/OceanNode.js'
import { fetchFileMetadata } from '../../utils/asset.js'
import axios from 'axios'
import urlJoin from 'url-join'
import { encrypt as encryptData, decrypt as decryptData } from '../../utils/crypt.js'
import { Readable } from 'stream'
import { CORE_LOGGER } from '../../utils/logging/common.js'
export abstract class Storage {
private file: UrlFileObject | IpfsFileObject | ArweaveFileObject
config: OceanNodeConfig
public constructor(
file: UrlFileObject | IpfsFileObject | ArweaveFileObject,
config: OceanNodeConfig
) {
this.file = file
this.config = config
}
abstract validate(): [boolean, string]
abstract getDownloadUrl(): string
abstract fetchSpecificFileMetadata(
fileObject: any,
forceChecksum: boolean
): Promise<FileInfoResponse>
abstract encryptContent(encryptionType: 'AES' | 'ECIES'): Promise<Buffer>
abstract isFilePath(): boolean
getFile(): any {
return this.file
}
// similar to all subclasses
async getReadableStream(): Promise<StorageReadable> {
const input = this.getDownloadUrl()
const response = await axios({
method: 'get',
url: input,
responseType: 'stream'
})
return {
httpStatus: response.status,
stream: response.data,
headers: response.headers as any
}
}
static getStorageClass(
file: any,
config: OceanNodeConfig
): UrlStorage | IpfsStorage | ArweaveStorage {
const { type } = file
switch (
type?.toLowerCase() // case insensitive
) {
case FileObjectType.URL:
return new UrlStorage(file, config)
case FileObjectType.IPFS:
return new IpfsStorage(file, config)
case FileObjectType.ARWEAVE:
return new ArweaveStorage(file, config)
default:
throw new Error(`Invalid storage type: ${type}`)
}
}
async getFileInfo(
fileInfoRequest: FileInfoRequest,
forceChecksum: boolean = false
): Promise<FileInfoResponse[]> {
if (!fileInfoRequest.type) {
throw new Error('Storage type is not provided')
}
const response: FileInfoResponse[] = []
try {
const file = this.getFile()
if (!file) {
throw new Error('Empty file object')
} else {
const fileInfo = await this.fetchSpecificFileMetadata(file, forceChecksum)
response.push(fileInfo)
}
} catch (error) {
CORE_LOGGER.error(error)
}
return response
}
async encrypt(encryptionType: EncryptMethod = EncryptMethod.AES) {
const readableStream = await this.getReadableStream()
// Convert the readable stream to a buffer
const chunks: Buffer[] = []
for await (const chunk of readableStream.stream) {
chunks.push(chunk)
}
const buffer = Buffer.concat(chunks)
// Encrypt the buffer using the encrypt function
const encryptedBuffer = await encryptData(new Uint8Array(buffer), encryptionType)
// Convert the encrypted buffer back into a stream
const encryptedStream = Readable.from(encryptedBuffer)
return {
...readableStream,
stream: encryptedStream
}
}
async decrypt() {
const { keys } = this.config
const nodeId = keys.peerId.toString()
if (!this.canDecrypt(nodeId)) {
throw new Error('Node is not authorized to decrypt this file')
}
const { encryptMethod } = this.file
const readableStream = await this.getReadableStream()
// Convert the readable stream to a buffer
const chunks: Buffer[] = []
for await (const chunk of readableStream.stream) {
chunks.push(chunk)
}
const buffer = Buffer.concat(chunks)
// Decrypt the buffer using your existing function
const decryptedBuffer = await decryptData(new Uint8Array(buffer), encryptMethod)
// Convert the decrypted buffer back into a stream
const decryptedStream = Readable.from(decryptedBuffer)
return {
...readableStream,
stream: decryptedStream
}
}
isEncrypted(): boolean {
if (
this.file.encryptedBy &&
(this.file.encryptMethod === EncryptMethod.AES ||
this.file.encryptMethod === EncryptMethod.ECIES)
) {
return true
} else {
return false
}
}
canDecrypt(nodeId: string): boolean {
if (
this.file.encryptedBy === nodeId &&
(this.file.encryptMethod === EncryptMethod.AES ||
this.file.encryptMethod === EncryptMethod.ECIES)
) {
return true
} else {
return false
}
}
}
export class UrlStorage extends Storage {
public constructor(file: UrlFileObject, config: OceanNodeConfig) {
super(file, config)
const [isValid, message] = this.validate()
if (isValid === false) {
throw new Error(`Error validationg the URL file: ${message}`)
}
}
validate(): [boolean, string] {
const file: UrlFileObject = this.getFile() as UrlFileObject
if (!file.url || !file.method) {
return [false, 'URL or method are missing']
}
if (!['get', 'post'].includes(file.method?.toLowerCase())) {
return [false, 'Invalid method for URL']
}
if (this.config && this.config.unsafeURLs) {
for (const regex of this.config.unsafeURLs) {
try {
// eslint-disable-next-line security/detect-non-literal-regexp
const pattern = new RegExp(regex)
if (pattern.test(file.url)) {
return [false, 'URL is marked as unsafe']
}
} catch (e) {}
}
}
if (this.isFilePath() === true) {
return [false, 'URL looks like a file path']
}
return [true, '']
}
isFilePath(): boolean {
const regex: RegExp = /^(.+)\/([^/]*)$/ // The URL should not represent a path
const { url } = this.getFile()
if (url.startsWith('http://') || url.startsWith('https://')) {
return false
}
return regex.test(url)
}
getDownloadUrl(): string {
if (this.validate()[0] === true) {
return this.getFile().url
}
return null
}
async fetchSpecificFileMetadata(
fileObject: UrlFileObject,
forceChecksum: boolean
): Promise<FileInfoResponse> {
const { url, method } = fileObject
const { contentLength, contentType, contentChecksum } = await fetchFileMetadata(
url,
method,
forceChecksum
)
return {
valid: true,
contentLength,
contentType,
checksum: contentChecksum,
name: new URL(url).pathname.split('/').pop() || '',
type: 'url',
encryptedBy: fileObject.encryptedBy,
encryptMethod: fileObject.encryptMethod
}
}
async encryptContent(
encryptionType: EncryptMethod.AES | EncryptMethod.ECIES
): Promise<Buffer> {
const file = this.getFile()
const response = await axios({
url: file.url,
method: file.method || 'get',
headers: file.headers
})
return await encryptData(response.data, encryptionType)
}
}
export class ArweaveStorage extends Storage {
public constructor(file: ArweaveFileObject, config: OceanNodeConfig) {
super(file, config)
const [isValid, message] = this.validate()
if (isValid === false) {
throw new Error(`Error validationg the Arweave file: ${message}`)
}
}
validate(): [boolean, string] {
if (!process.env.ARWEAVE_GATEWAY) {
return [false, 'Arweave gateway is not provided!']
}
const file: ArweaveFileObject = this.getFile() as ArweaveFileObject
if (!file.transactionId) {
return [false, 'Missing transaction ID']
}
if (
file.transactionId.startsWith('http://') ||
file.transactionId.startsWith('https://')
) {
return [
false,
'Transaction ID looks like an URL. Please specify URL storage instead.'
]
}
if (this.isFilePath() === true) {
return [false, 'Transaction ID looks like a file path']
}
return [true, '']
}
isFilePath(): boolean {
const regex: RegExp = /^(.+)\/([^/]*)$/ // The transaction ID should not represent a path
const { transactionId } = this.getFile()
return regex.test(transactionId)
}
getDownloadUrl(): string {
return urlJoin(process.env.ARWEAVE_GATEWAY, this.getFile().transactionId)
}
async fetchSpecificFileMetadata(
fileObject: ArweaveFileObject,
forceChecksum: boolean
): Promise<FileInfoResponse> {
const url = urlJoin(process.env.ARWEAVE_GATEWAY, fileObject.transactionId)
const { contentLength, contentType, contentChecksum } = await fetchFileMetadata(
url,
'get',
forceChecksum
)
return {
valid: true,
contentLength,
contentType,
checksum: contentChecksum,
name: '', // Never send the file name for Arweave as it may leak the transaction ID
type: 'arweave',
encryptedBy: fileObject.encryptedBy,
encryptMethod: fileObject.encryptMethod
}
}
async encryptContent(
encryptionType: EncryptMethod.AES | EncryptMethod.ECIES
): Promise<Buffer> {
const file = this.getFile()
const response = await axios({
url: urlJoin(process.env.ARWEAVE_GATEWAY, file.transactionId),
method: 'get'
})
return await encryptData(response.data, encryptionType)
}
}
export class IpfsStorage extends Storage {
public constructor(file: IpfsFileObject, config: OceanNodeConfig) {
super(file, config)
const [isValid, message] = this.validate()
if (isValid === false) {
throw new Error(`Error validationg the IPFS file: ${message}`)
}
}
validate(): [boolean, string] {
if (!process.env.IPFS_GATEWAY) {
return [false, 'IPFS gateway is not provided!']
}
const file: IpfsFileObject = this.getFile() as IpfsFileObject
if (!file.hash) {
return [false, 'Missing CID']
}
if (file.hash.startsWith('http://') || file.hash.startsWith('https://')) {
return [false, 'CID looks like an URL. Please specify URL storage instead.']
}
if (this.isFilePath() === true) {
return [false, 'CID looks like a file path']
}
return [true, '']
}
isFilePath(): boolean {
const regex: RegExp = /^(.+)\/([^/]*)$/ // The CID should not represent a path
const { hash } = this.getFile()
return regex.test(hash)
}
getDownloadUrl(): string {
return urlJoin(process.env.IPFS_GATEWAY, urlJoin('/ipfs', this.getFile().hash))
}
async fetchSpecificFileMetadata(
fileObject: IpfsFileObject,
forceChecksum: boolean
): Promise<FileInfoResponse> {
const url = urlJoin(process.env.IPFS_GATEWAY, urlJoin('/ipfs', fileObject.hash))
const { contentLength, contentType, contentChecksum } = await fetchFileMetadata(
url,
'get',
forceChecksum
)
return {
valid: true,
contentLength,
contentType,
checksum: contentChecksum,
name: '',
type: 'ipfs',
encryptedBy: fileObject.encryptedBy,
encryptMethod: fileObject.encryptMethod
}
}
async encryptContent(
encryptionType: EncryptMethod.AES | EncryptMethod.ECIES
): Promise<Buffer> {
const file = this.getFile()
const response = await axios({
url: file.hash,
method: 'get'
})
return await encryptData(response.data, encryptionType)
}
}