@helia/verified-fetch 0.0.0-8a5bc6f → 0.0.0-9b1ddf8
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/README.md +80 -43
- package/dist/index.min.js +4 -29
- package/dist/src/index.d.ts +114 -52
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +87 -48
- package/dist/src/index.js.map +1 -1
- package/dist/src/singleton.d.ts +3 -0
- package/dist/src/singleton.d.ts.map +1 -0
- package/dist/src/singleton.js +15 -0
- package/dist/src/singleton.js.map +1 -0
- package/dist/src/utils/get-stream-from-async-iterable.d.ts +10 -0
- package/dist/src/utils/get-stream-from-async-iterable.d.ts.map +1 -0
- package/dist/src/utils/{get-stream-and-content-type.js → get-stream-from-async-iterable.js} +10 -9
- package/dist/src/utils/get-stream-from-async-iterable.js.map +1 -0
- package/dist/src/verified-fetch.d.ts +4 -1
- package/dist/src/verified-fetch.d.ts.map +1 -1
- package/dist/src/verified-fetch.js +46 -18
- package/dist/src/verified-fetch.js.map +1 -1
- package/package.json +19 -19
- package/src/index.ts +120 -53
- package/src/singleton.ts +20 -0
- package/src/utils/{get-stream-and-content-type.ts → get-stream-from-async-iterable.ts} +9 -8
- package/src/verified-fetch.ts +53 -22
- package/dist/src/utils/get-content-type.d.ts +0 -11
- package/dist/src/utils/get-content-type.d.ts.map +0 -1
- package/dist/src/utils/get-content-type.js +0 -43
- package/dist/src/utils/get-content-type.js.map +0 -1
- package/dist/src/utils/get-stream-and-content-type.d.ts +0 -10
- package/dist/src/utils/get-stream-and-content-type.d.ts.map +0 -1
- package/dist/src/utils/get-stream-and-content-type.js.map +0 -1
- package/src/utils/get-content-type.ts +0 -55
package/src/index.ts
CHANGED
|
@@ -1,57 +1,49 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @packageDocumentation
|
|
3
3
|
*
|
|
4
|
-
* `@helia/verified-fetch`
|
|
4
|
+
* `@helia/verified-fetch` provides a [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)-like API for retrieving content from the [IPFS](https://ipfs.tech/) network.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
6
|
+
* All content is retrieved in a [trustless manner](https://www.techopedia.com/definition/trustless), and the integrity of all bytes are verified by comparing hashes of the data.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
8
|
+
* This is a marked improvement over `fetch` which offers no such protections and is vulnerable to all sorts of attacks like [Content Spoofing](https://owasp.org/www-community/attacks/Content_Spoofing), [DNS Hijacking](https://en.wikipedia.org/wiki/DNS_hijacking), etc.
|
|
9
|
+
*
|
|
10
|
+
* A `verifiedFetch` function is exported to get up and running quickly, and a `createVerifiedFetch` function is also available that allows customizing the underlying [Helia](https://helia.io/) node for complete control over how content is retrieved.
|
|
11
|
+
*
|
|
12
|
+
* Browser-cache-friendly [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects are returned which should be instantly familiar to web developers.
|
|
9
13
|
*
|
|
10
14
|
* You may use any supported resource argument to fetch content:
|
|
11
15
|
*
|
|
12
|
-
* - CID instance
|
|
16
|
+
* - [CID](https://multiformats.github.io/js-multiformats/classes/cid.CID.html) instance
|
|
13
17
|
* - IPFS URL
|
|
14
18
|
* - IPNS URL
|
|
15
19
|
*
|
|
16
|
-
* @example
|
|
20
|
+
* @example Getting started
|
|
17
21
|
*
|
|
18
22
|
* ```typescript
|
|
19
|
-
* import {
|
|
23
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
20
24
|
*
|
|
21
|
-
* const
|
|
22
|
-
* gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
|
|
23
|
-
*})
|
|
24
|
-
*
|
|
25
|
-
* const resp = await fetch('ipfs://bafy...')
|
|
25
|
+
* const resp = await verifiedFetch('ipfs://bafy...')
|
|
26
26
|
*
|
|
27
27
|
* const json = await resp.json()
|
|
28
28
|
*```
|
|
29
29
|
*
|
|
30
|
-
*
|
|
31
30
|
* @example Using a CID instance to fetch JSON
|
|
32
31
|
*
|
|
33
32
|
* ```typescript
|
|
34
|
-
* import {
|
|
33
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
35
34
|
* import { CID } from 'multiformats/cid'
|
|
36
35
|
*
|
|
37
|
-
* const fetch = await createVerifiedFetch({
|
|
38
|
-
* gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
|
|
39
|
-
* })
|
|
40
|
-
*
|
|
41
36
|
* const cid = CID.parse('bafyFoo') // some image file
|
|
42
|
-
* const response = await
|
|
37
|
+
* const response = await verifiedFetch(cid)
|
|
43
38
|
* const json = await response.json()
|
|
44
39
|
* ```
|
|
45
40
|
*
|
|
46
41
|
* @example Using IPFS protocol to fetch an image
|
|
47
42
|
*
|
|
48
43
|
* ```typescript
|
|
49
|
-
* import {
|
|
44
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
50
45
|
*
|
|
51
|
-
* const
|
|
52
|
-
* gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
|
|
53
|
-
* })
|
|
54
|
-
* const response = await fetch('ipfs://bafyFoo') // CID for some image file
|
|
46
|
+
* const response = await verifiedFetch('ipfs://bafyFoo') // CID for some image file
|
|
55
47
|
* const blob = await response.blob()
|
|
56
48
|
* const image = document.createElement('img')
|
|
57
49
|
* image.src = URL.createObjectURL(blob)
|
|
@@ -61,22 +53,42 @@
|
|
|
61
53
|
* @example Using IPNS protocol to stream a big file
|
|
62
54
|
*
|
|
63
55
|
* ```typescript
|
|
56
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
57
|
+
*
|
|
58
|
+
* const response = await verifiedFetch('ipns://mydomain.com/path/to/very-long-file.log')
|
|
59
|
+
* const bigFileStreamReader = await response.body.getReader()
|
|
60
|
+
* ```
|
|
61
|
+
*
|
|
62
|
+
* ## Configuration
|
|
63
|
+
*
|
|
64
|
+
* ### Custom HTTP gateways and routers
|
|
65
|
+
*
|
|
66
|
+
* Out of the box `@helia/verified-fetch` uses a default set of [trustless gateways](https://specs.ipfs.tech/http-gateways/trustless-gateway/) for fetching blocks and [HTTP delegated routers](https://specs.ipfs.tech/routing/http-routing-v1/) for performing routing tasks - looking up peers, resolving/publishing [IPNS](https://docs.ipfs.tech/concepts/ipns/) names, etc.
|
|
67
|
+
*
|
|
68
|
+
* It's possible to override these by passing `gateways` and `routers` keys to the `createVerifiedFetch` function:
|
|
69
|
+
*
|
|
70
|
+
* @example Configuring gateways and routers
|
|
71
|
+
*
|
|
72
|
+
* ```typescript
|
|
64
73
|
* import { createVerifiedFetch } from '@helia/verified-fetch'
|
|
65
74
|
*
|
|
66
75
|
* const fetch = await createVerifiedFetch({
|
|
67
|
-
* gateways: ['https://
|
|
76
|
+
* gateways: ['https://trustless-gateway.link'],
|
|
77
|
+
* routers: ['http://delegated-ipfs.dev']
|
|
68
78
|
* })
|
|
69
|
-
* const response = await fetch('ipns://mydomain.com/path/to/very-long-file.log')
|
|
70
|
-
* const bigFileStreamReader = await response.body.getReader()
|
|
71
|
-
* ```
|
|
72
79
|
*
|
|
73
|
-
*
|
|
80
|
+
* const resp = await fetch('ipfs://bafy...')
|
|
81
|
+
*
|
|
82
|
+
* const json = await resp.json()
|
|
83
|
+
*```
|
|
74
84
|
*
|
|
75
|
-
*
|
|
85
|
+
* ### Usage with customized Helia
|
|
76
86
|
*
|
|
77
|
-
*
|
|
87
|
+
* For full control of how `@helia/verified-fetch` fetches content from the distributed web you can pass a preconfigured Helia node to `createVerifiedFetch`.
|
|
78
88
|
*
|
|
79
|
-
* The
|
|
89
|
+
* The [helia](https://www.npmjs.com/package/helia) module is configured with a libp2p node that is suited for decentralized applications, alternatively [@helia/http](https://www.npmjs.com/package/@helia/http) is available which uses HTTP gateways for all network operations.
|
|
90
|
+
*
|
|
91
|
+
* You can see variations of Helia and js-libp2p configuration options at https://helia.io/interfaces/helia.index.HeliaInit.html.
|
|
80
92
|
*
|
|
81
93
|
* ```typescript
|
|
82
94
|
* import { trustlessGateway } from '@helia/block-brokers'
|
|
@@ -100,28 +112,54 @@
|
|
|
100
112
|
* const json = await resp.json()
|
|
101
113
|
* ```
|
|
102
114
|
*
|
|
103
|
-
* ###
|
|
115
|
+
* ### Custom content-type parsing
|
|
116
|
+
*
|
|
117
|
+
* By default, `@helia/verified-fetch` sets the `Content-Type` header as `application/octet-stream` - this is because the `.json()`, `.text()`, `.blob()`, and `.arrayBuffer()` methods will usually work as expected without a detailed content type.
|
|
104
118
|
*
|
|
105
|
-
*
|
|
119
|
+
* If you require an accurate content-type you can provide a `contentTypeParser` function as an option to `createVerifiedFetch` to handle parsing the content type.
|
|
120
|
+
*
|
|
121
|
+
* The function you provide will be called with the first chunk of bytes from the file and should return a string or a promise of a string.
|
|
122
|
+
*
|
|
123
|
+
* @example Customizing content-type parsing
|
|
124
|
+
*
|
|
125
|
+
* ```typescript
|
|
126
|
+
* import { createVerifiedFetch } from '@helia/verified-fetch'
|
|
127
|
+
* import { fileTypeFromBuffer } from '@sgtpooki/file-type'
|
|
128
|
+
*
|
|
129
|
+
* const fetch = await createVerifiedFetch({
|
|
130
|
+
* gateways: ['https://trustless-gateway.link'],
|
|
131
|
+
* routers: ['http://delegated-ipfs.dev']
|
|
132
|
+
* }, {
|
|
133
|
+
* contentTypeParser: async (bytes) => {
|
|
134
|
+
* // call to some magic-byte recognition library like magic-bytes, file-type, or your own custom byte recognition
|
|
135
|
+
* const result = await fileTypeFromBuffer(bytes)
|
|
136
|
+
* return result?.mime
|
|
137
|
+
* }
|
|
138
|
+
* })
|
|
139
|
+
* ```
|
|
140
|
+
*
|
|
141
|
+
* ## Comparison to fetch
|
|
142
|
+
*
|
|
143
|
+
* This module attempts to act as similarly to the `fetch()` API as possible.
|
|
106
144
|
*
|
|
107
145
|
* [The `fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/fetch) takes two parameters:
|
|
108
146
|
*
|
|
109
147
|
* 1. A [resource](https://developer.mozilla.org/en-US/docs/Web/API/fetch#resource)
|
|
110
148
|
* 2. An [options object](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)
|
|
111
149
|
*
|
|
112
|
-
*
|
|
150
|
+
* ### Resource argument
|
|
113
151
|
*
|
|
114
|
-
* This library
|
|
152
|
+
* This library supports the following methods of fetching web3 content from IPFS:
|
|
115
153
|
*
|
|
116
154
|
* 1. IPFS protocol: `ipfs://<cidv0>` & `ipfs://<cidv0>`
|
|
117
155
|
* 2. IPNS protocol: `ipns://<peerId>` & `ipns://<publicKey>` & `ipns://<hostUri_Supporting_DnsLink_TxtRecords>`
|
|
118
156
|
* 3. CID instances: An actual CID instance `CID.parse('bafy...')`
|
|
119
157
|
*
|
|
120
|
-
* As well as support for pathing & params for item 1&2 above according to [IPFS - Path Gateway Specification](https://specs.ipfs.tech/http-gateways/path-gateway) & [IPFS - Trustless Gateway Specification](https://specs.ipfs.tech/http-gateways/trustless-gateway/). Further refinement of those specifications specifically for web-based scenarios can be found in the [Web Pathing Specification IPIP](https://github.com/ipfs/specs/pull/453).
|
|
158
|
+
* As well as support for pathing & params for item 1 & 2 above according to [IPFS - Path Gateway Specification](https://specs.ipfs.tech/http-gateways/path-gateway) & [IPFS - Trustless Gateway Specification](https://specs.ipfs.tech/http-gateways/trustless-gateway/). Further refinement of those specifications specifically for web-based scenarios can be found in the [Web Pathing Specification IPIP](https://github.com/ipfs/specs/pull/453).
|
|
121
159
|
*
|
|
122
|
-
* If you pass a CID instance,
|
|
160
|
+
* If you pass a CID instance, it assumes you want the content for that specific CID only, and does not support pathing or params for that CID.
|
|
123
161
|
*
|
|
124
|
-
*
|
|
162
|
+
* ### Options argument
|
|
125
163
|
*
|
|
126
164
|
* This library does not plan to support the exact Fetch API options object, as some of the arguments don't make sense. Instead, it will only support options necessary to meet [IPFS specs](https://specs.ipfs.tech/) related to specifying the resultant shape of desired content.
|
|
127
165
|
*
|
|
@@ -146,7 +184,6 @@
|
|
|
146
184
|
* 5. `body` - An object that specifies the body of the request. Best effort to adhere to the [Fetch API body](https://developer.mozilla.org/en-US/docs/Web/API/fetch#body) parameter.
|
|
147
185
|
* 6. `cache` - Will basically act as `force-cache` for the request. Best effort to adhere to the [Fetch API cache](https://developer.mozilla.org/en-US/docs/Web/API/fetch#cache) parameter.
|
|
148
186
|
*
|
|
149
|
-
*
|
|
150
187
|
* Non-Fetch API options that will be supported:
|
|
151
188
|
*
|
|
152
189
|
* 1. `onProgress` - Similar to Helia `onProgress` options, this will be a function that will be called with a progress event. Supported progress events are:
|
|
@@ -167,7 +204,7 @@
|
|
|
167
204
|
* 4. [IPIP-0328: JSON and CBOR Response Formats on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0328/)
|
|
168
205
|
* 5. [IPIP-0288: TAR Response Format on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0288/)
|
|
169
206
|
*
|
|
170
|
-
*
|
|
207
|
+
* ### Response types
|
|
171
208
|
*
|
|
172
209
|
* This library's purpose is to return reasonably representable content from IPFS. In other words, fetching content is intended for leaf-node content -- such as images/videos/audio & other assets, or other IPLD content (with link) -- that can be represented by https://developer.mozilla.org/en-US/docs/Web/API/Response#instance_methods. The content type you receive back will depend upon the CID you request as well as the `Accept` header value you provide.
|
|
173
210
|
*
|
|
@@ -175,7 +212,7 @@
|
|
|
175
212
|
*
|
|
176
213
|
* If your content doesn't have a mime-type or an [IPFS spec](https://specs.ipfs.tech), this library will not support it, but you can use the [`helia`](https://github.com/ipfs/helia) library directly for those use cases. See [Unsupported response types](#unsupported-response-types) for more information.
|
|
177
214
|
*
|
|
178
|
-
*
|
|
215
|
+
* #### Handling response types
|
|
179
216
|
*
|
|
180
217
|
* For handling responses we want to follow conventions/abstractions from Fetch API where possible:
|
|
181
218
|
*
|
|
@@ -184,12 +221,12 @@
|
|
|
184
221
|
* - For plain text in utf-8, you would call `.text()`
|
|
185
222
|
* - For streaming response data, use something like `response.body.getReader()` to get a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#consuming_a_fetch_as_a_stream).
|
|
186
223
|
*
|
|
187
|
-
*
|
|
224
|
+
* #### Unsupported response types
|
|
188
225
|
*
|
|
189
226
|
* * Returning IPLD nodes or DAGs as JS objects is not supported, as there is no currently well-defined structure for representing this data in an [HTTP Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). Instead, users should request `aplication/vnd.ipld.car` or use the [`helia`](https://github.com/ipfs/helia) library directly for this use case.
|
|
190
227
|
* * Others? Open an issue or PR!
|
|
191
228
|
*
|
|
192
|
-
*
|
|
229
|
+
* ### Response headers
|
|
193
230
|
*
|
|
194
231
|
* This library will set the [HTTP Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) headers to the appropriate values for the content type according to the appropriate [IPFS Specifications](https://specs.ipfs.tech/).
|
|
195
232
|
*
|
|
@@ -199,13 +236,13 @@
|
|
|
199
236
|
* * https://specs.ipfs.tech/http-gateways/trustless-gateway/#response-headers
|
|
200
237
|
* * https://specs.ipfs.tech/http-gateways/subdomain-gateway/#response-headers
|
|
201
238
|
*
|
|
202
|
-
*
|
|
239
|
+
* ### Possible Scenarios that could cause confusion
|
|
203
240
|
*
|
|
204
|
-
*
|
|
241
|
+
* #### Attempting to fetch the CID for content that does not make sense
|
|
205
242
|
*
|
|
206
243
|
* If you request `bafybeiaysi4s6lnjev27ln5icwm6tueaw2vdykrtjkwiphwekaywqhcjze`, which points to the root of the en.wikipedia.org mirror, a response object does not make sense.
|
|
207
244
|
*
|
|
208
|
-
*
|
|
245
|
+
* ### Errors
|
|
209
246
|
*
|
|
210
247
|
* Known Errors that can be thrown:
|
|
211
248
|
*
|
|
@@ -231,7 +268,7 @@ import type { ProgressEvent, ProgressOptions } from 'progress-events'
|
|
|
231
268
|
export type Resource = string | CID
|
|
232
269
|
|
|
233
270
|
export interface CIDDetail {
|
|
234
|
-
cid:
|
|
271
|
+
cid: CID
|
|
235
272
|
path: string
|
|
236
273
|
}
|
|
237
274
|
|
|
@@ -246,13 +283,38 @@ export interface VerifiedFetch {
|
|
|
246
283
|
}
|
|
247
284
|
|
|
248
285
|
/**
|
|
249
|
-
* Instead of passing a Helia instance, you can pass a list of gateways and
|
|
286
|
+
* Instead of passing a Helia instance, you can pass a list of gateways and
|
|
287
|
+
* routers, and a HeliaHTTP instance will be created for you.
|
|
250
288
|
*/
|
|
251
|
-
export interface
|
|
289
|
+
export interface CreateVerifiedFetchInit {
|
|
252
290
|
gateways: string[]
|
|
253
291
|
routers?: string[]
|
|
254
292
|
}
|
|
255
293
|
|
|
294
|
+
export interface CreateVerifiedFetchOptions {
|
|
295
|
+
/**
|
|
296
|
+
* A function to handle parsing content type from bytes. The function you
|
|
297
|
+
* provide will be passed the first set of bytes we receive from the network,
|
|
298
|
+
* and should return a string that will be used as the value for the
|
|
299
|
+
* `Content-Type` header in the response.
|
|
300
|
+
*/
|
|
301
|
+
contentTypeParser?: ContentTypeParser
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* A ContentTypeParser attempts to return the mime type of a given file. It
|
|
306
|
+
* receives the first chunk of the file data and the file name, if it is
|
|
307
|
+
* available. The function can be sync or async and if it returns/resolves to
|
|
308
|
+
* `undefined`, `application/octet-stream` will be used.
|
|
309
|
+
*/
|
|
310
|
+
export interface ContentTypeParser {
|
|
311
|
+
/**
|
|
312
|
+
* Attempt to determine a mime type, either via of the passed bytes or the
|
|
313
|
+
* filename if it is available.
|
|
314
|
+
*/
|
|
315
|
+
(bytes: Uint8Array, fileName?: string): Promise<string | undefined> | string | undefined
|
|
316
|
+
}
|
|
317
|
+
|
|
256
318
|
export type BubbledProgressEvents =
|
|
257
319
|
// unixfs
|
|
258
320
|
GetEvents |
|
|
@@ -269,8 +331,9 @@ export type VerifiedFetchProgressEvents =
|
|
|
269
331
|
/**
|
|
270
332
|
* Options for the `fetch` function returned by `createVerifiedFetch`.
|
|
271
333
|
*
|
|
272
|
-
* This
|
|
273
|
-
* listen for
|
|
334
|
+
* This interface contains all the same fields as the [options object](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)
|
|
335
|
+
* passed to `fetch` in browsers, plus an `onProgress` option to listen for
|
|
336
|
+
* progress events.
|
|
274
337
|
*/
|
|
275
338
|
export interface VerifiedFetchInit extends RequestInit, ProgressOptions<BubbledProgressEvents | VerifiedFetchProgressEvents> {
|
|
276
339
|
}
|
|
@@ -278,7 +341,9 @@ export interface VerifiedFetchInit extends RequestInit, ProgressOptions<BubbledP
|
|
|
278
341
|
/**
|
|
279
342
|
* Create and return a Helia node
|
|
280
343
|
*/
|
|
281
|
-
export async function createVerifiedFetch (init?: Helia |
|
|
344
|
+
export async function createVerifiedFetch (init?: Helia | CreateVerifiedFetchInit, options?: CreateVerifiedFetchOptions): Promise<VerifiedFetch> {
|
|
345
|
+
const contentTypeParser: ContentTypeParser | undefined = options?.contentTypeParser
|
|
346
|
+
|
|
282
347
|
if (!isHelia(init)) {
|
|
283
348
|
init = await createHeliaHTTP({
|
|
284
349
|
blockBrokers: [
|
|
@@ -290,7 +355,7 @@ export async function createVerifiedFetch (init?: Helia | CreateVerifiedFetchWit
|
|
|
290
355
|
})
|
|
291
356
|
}
|
|
292
357
|
|
|
293
|
-
const verifiedFetchInstance = new VerifiedFetchClass({ helia: init })
|
|
358
|
+
const verifiedFetchInstance = new VerifiedFetchClass({ helia: init }, { contentTypeParser })
|
|
294
359
|
async function verifiedFetch (resource: Resource, options?: VerifiedFetchInit): Promise<Response> {
|
|
295
360
|
return verifiedFetchInstance.fetch(resource, options)
|
|
296
361
|
}
|
|
@@ -300,6 +365,8 @@ export async function createVerifiedFetch (init?: Helia | CreateVerifiedFetchWit
|
|
|
300
365
|
return verifiedFetch
|
|
301
366
|
}
|
|
302
367
|
|
|
368
|
+
export { verifiedFetch } from './singleton.js'
|
|
369
|
+
|
|
303
370
|
function isHelia (obj: any): obj is Helia {
|
|
304
371
|
// test for the presence of known Helia properties, return a boolean value
|
|
305
372
|
return obj?.blockstore != null &&
|
package/src/singleton.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createVerifiedFetch } from './index.js'
|
|
2
|
+
import type { Resource, VerifiedFetch, VerifiedFetchInit } from './index.js'
|
|
3
|
+
|
|
4
|
+
let impl: VerifiedFetch | undefined
|
|
5
|
+
|
|
6
|
+
export const verifiedFetch: VerifiedFetch = async function verifiedFetch (resource: Resource, options?: VerifiedFetchInit): Promise<Response> {
|
|
7
|
+
if (impl == null) {
|
|
8
|
+
impl = await createVerifiedFetch()
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
return impl(resource, options)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
verifiedFetch.start = async function () {
|
|
15
|
+
await impl?.start()
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
verifiedFetch.stop = async function () {
|
|
19
|
+
await impl?.stop()
|
|
20
|
+
}
|
|
@@ -1,27 +1,25 @@
|
|
|
1
1
|
import { CustomProgressEvent } from 'progress-events'
|
|
2
|
-
import { getContentType } from './get-content-type.js'
|
|
3
2
|
import type { VerifiedFetchInit } from '../index.js'
|
|
4
3
|
import type { ComponentLogger } from '@libp2p/interface'
|
|
5
4
|
|
|
6
5
|
/**
|
|
7
|
-
* Converts an async iterator of Uint8Array bytes to a stream and
|
|
6
|
+
* Converts an async iterator of Uint8Array bytes to a stream and returns the first chunk of bytes
|
|
8
7
|
*/
|
|
9
|
-
export async function
|
|
10
|
-
const log = logger.forComponent('helia:verified-fetch:get-stream-
|
|
8
|
+
export async function getStreamFromAsyncIterable (iterator: AsyncIterable<Uint8Array>, path: string, logger: ComponentLogger, options?: Pick<VerifiedFetchInit, 'onProgress'>): Promise<{ stream: ReadableStream<Uint8Array>, firstChunk: Uint8Array }> {
|
|
9
|
+
const log = logger.forComponent('helia:verified-fetch:get-stream-from-async-iterable')
|
|
11
10
|
const reader = iterator[Symbol.asyncIterator]()
|
|
12
|
-
const { value, done } = await reader.next()
|
|
11
|
+
const { value: firstChunk, done } = await reader.next()
|
|
13
12
|
|
|
14
13
|
if (done === true) {
|
|
15
14
|
log.error('No content found for path', path)
|
|
16
15
|
throw new Error('No content found')
|
|
17
16
|
}
|
|
18
17
|
|
|
19
|
-
const contentType = await getContentType({ bytes: value, path })
|
|
20
18
|
const stream = new ReadableStream({
|
|
21
19
|
async start (controller) {
|
|
22
20
|
// the initial value is already available
|
|
23
21
|
options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
|
|
24
|
-
controller.enqueue(
|
|
22
|
+
controller.enqueue(firstChunk)
|
|
25
23
|
},
|
|
26
24
|
async pull (controller) {
|
|
27
25
|
const { value, done } = await reader.next()
|
|
@@ -40,5 +38,8 @@ export async function getStreamAndContentType (iterator: AsyncIterable<Uint8Arra
|
|
|
40
38
|
}
|
|
41
39
|
})
|
|
42
40
|
|
|
43
|
-
return {
|
|
41
|
+
return {
|
|
42
|
+
stream,
|
|
43
|
+
firstChunk
|
|
44
|
+
}
|
|
44
45
|
}
|
package/src/verified-fetch.ts
CHANGED
|
@@ -10,10 +10,10 @@ import { code as dagPbCode } from '@ipld/dag-pb'
|
|
|
10
10
|
import { code as jsonCode } from 'multiformats/codecs/json'
|
|
11
11
|
import { decode, code as rawCode } from 'multiformats/codecs/raw'
|
|
12
12
|
import { CustomProgressEvent } from 'progress-events'
|
|
13
|
-
import {
|
|
13
|
+
import { getStreamFromAsyncIterable } from './utils/get-stream-from-async-iterable.js'
|
|
14
14
|
import { parseResource } from './utils/parse-resource.js'
|
|
15
15
|
import { walkPath, type PathWalkerFn } from './utils/walk-path.js'
|
|
16
|
-
import type { CIDDetail, Resource, VerifiedFetchInit as VerifiedFetchOptions } from './index.js'
|
|
16
|
+
import type { CIDDetail, ContentTypeParser, Resource, VerifiedFetchInit as VerifiedFetchOptions } from './index.js'
|
|
17
17
|
import type { Helia } from '@helia/interface'
|
|
18
18
|
import type { AbortOptions, Logger } from '@libp2p/interface'
|
|
19
19
|
import type { UnixFSEntry } from 'ipfs-unixfs-exporter'
|
|
@@ -32,9 +32,8 @@ interface VerifiedFetchComponents {
|
|
|
32
32
|
/**
|
|
33
33
|
* Potential future options for the VerifiedFetch constructor.
|
|
34
34
|
*/
|
|
35
|
-
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
|
36
35
|
interface VerifiedFetchInit {
|
|
37
|
-
|
|
36
|
+
contentTypeParser?: ContentTypeParser
|
|
38
37
|
}
|
|
39
38
|
|
|
40
39
|
interface FetchHandlerFunctionArg {
|
|
@@ -72,6 +71,7 @@ export class VerifiedFetch {
|
|
|
72
71
|
private readonly json: JSON
|
|
73
72
|
private readonly pathWalker: PathWalkerFn
|
|
74
73
|
private readonly log: Logger
|
|
74
|
+
private readonly contentTypeParser: ContentTypeParser | undefined
|
|
75
75
|
|
|
76
76
|
constructor ({ helia, ipns, unixfs, dagJson, json, dagCbor, pathWalker }: VerifiedFetchComponents, init?: VerifiedFetchInit) {
|
|
77
77
|
this.helia = helia
|
|
@@ -87,6 +87,7 @@ export class VerifiedFetch {
|
|
|
87
87
|
this.json = json ?? heliaJson(helia)
|
|
88
88
|
this.dagCbor = dagCbor ?? heliaDagCbor(helia)
|
|
89
89
|
this.pathWalker = pathWalker ?? walkPath
|
|
90
|
+
this.contentTypeParser = init?.contentTypeParser
|
|
90
91
|
this.log.trace('created VerifiedFetch instance')
|
|
91
92
|
}
|
|
92
93
|
|
|
@@ -106,12 +107,12 @@ export class VerifiedFetch {
|
|
|
106
107
|
|
|
107
108
|
private async handleDagJson ({ cid, path, options }: FetchHandlerFunctionArg): Promise<Response> {
|
|
108
109
|
this.log.trace('fetching %c/%s', cid, path)
|
|
109
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid
|
|
110
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid, path }))
|
|
110
111
|
const result = await this.dagJson.get(cid, {
|
|
111
112
|
signal: options?.signal,
|
|
112
113
|
onProgress: options?.onProgress
|
|
113
114
|
})
|
|
114
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid
|
|
115
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid, path }))
|
|
115
116
|
const response = new Response(JSON.stringify(result), { status: 200 })
|
|
116
117
|
response.headers.set('content-type', 'application/json')
|
|
117
118
|
return response
|
|
@@ -119,12 +120,12 @@ export class VerifiedFetch {
|
|
|
119
120
|
|
|
120
121
|
private async handleJson ({ cid, path, options }: FetchHandlerFunctionArg): Promise<Response> {
|
|
121
122
|
this.log.trace('fetching %c/%s', cid, path)
|
|
122
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid
|
|
123
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid, path }))
|
|
123
124
|
const result: Record<any, any> = await this.json.get(cid, {
|
|
124
125
|
signal: options?.signal,
|
|
125
126
|
onProgress: options?.onProgress
|
|
126
127
|
})
|
|
127
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid
|
|
128
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid, path }))
|
|
128
129
|
const response = new Response(JSON.stringify(result), { status: 200 })
|
|
129
130
|
response.headers.set('content-type', 'application/json')
|
|
130
131
|
return response
|
|
@@ -132,14 +133,14 @@ export class VerifiedFetch {
|
|
|
132
133
|
|
|
133
134
|
private async handleDagCbor ({ cid, path, options }: FetchHandlerFunctionArg): Promise<Response> {
|
|
134
135
|
this.log.trace('fetching %c/%s', cid, path)
|
|
135
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid
|
|
136
|
-
const result = await this.dagCbor.get(cid, {
|
|
136
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid, path }))
|
|
137
|
+
const result = await this.dagCbor.get<Uint8Array>(cid, {
|
|
137
138
|
signal: options?.signal,
|
|
138
139
|
onProgress: options?.onProgress
|
|
139
140
|
})
|
|
140
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid
|
|
141
|
-
const response = new Response(
|
|
142
|
-
|
|
141
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid, path }))
|
|
142
|
+
const response = new Response(result, { status: 200 })
|
|
143
|
+
await this.setContentType(result, path, response)
|
|
143
144
|
return response
|
|
144
145
|
}
|
|
145
146
|
|
|
@@ -153,7 +154,7 @@ export class VerifiedFetch {
|
|
|
153
154
|
const rootFilePath = 'index.html'
|
|
154
155
|
try {
|
|
155
156
|
this.log.trace('found directory at %c/%s, looking for index.html', cid, path)
|
|
156
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid: dirCid
|
|
157
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid: dirCid, path: rootFilePath }))
|
|
157
158
|
stat = await this.unixfs.stat(dirCid, {
|
|
158
159
|
path: rootFilePath,
|
|
159
160
|
signal: options?.signal,
|
|
@@ -167,37 +168,63 @@ export class VerifiedFetch {
|
|
|
167
168
|
this.log('error loading path %c/%s', dirCid, rootFilePath, err)
|
|
168
169
|
return new Response('Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented', { status: 501 })
|
|
169
170
|
} finally {
|
|
170
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid: dirCid
|
|
171
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid: dirCid, path: rootFilePath }))
|
|
171
172
|
}
|
|
172
173
|
}
|
|
173
174
|
|
|
174
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid: resolvedCID
|
|
175
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid: resolvedCID, path: '' }))
|
|
175
176
|
const asyncIter = this.unixfs.cat(resolvedCID, {
|
|
176
177
|
signal: options?.signal,
|
|
177
178
|
onProgress: options?.onProgress
|
|
178
179
|
})
|
|
179
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid: resolvedCID
|
|
180
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid: resolvedCID, path: '' }))
|
|
180
181
|
this.log('got async iterator for %c/%s', cid, path)
|
|
181
182
|
|
|
182
|
-
const {
|
|
183
|
+
const { stream, firstChunk } = await getStreamFromAsyncIterable(asyncIter, path ?? '', this.helia.logger, {
|
|
183
184
|
onProgress: options?.onProgress
|
|
184
185
|
})
|
|
185
186
|
const response = new Response(stream, { status: 200 })
|
|
186
|
-
|
|
187
|
+
await this.setContentType(firstChunk, path, response)
|
|
187
188
|
|
|
188
189
|
return response
|
|
189
190
|
}
|
|
190
191
|
|
|
191
192
|
private async handleRaw ({ cid, path, options }: FetchHandlerFunctionArg): Promise<Response> {
|
|
192
193
|
this.log.trace('fetching %c/%s', cid, path)
|
|
193
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid
|
|
194
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:start', { cid, path }))
|
|
194
195
|
const result = await this.helia.blockstore.get(cid)
|
|
195
|
-
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid
|
|
196
|
+
options?.onProgress?.(new CustomProgressEvent<CIDDetail>('verified-fetch:request:end', { cid, path }))
|
|
196
197
|
const response = new Response(decode(result), { status: 200 })
|
|
197
|
-
|
|
198
|
+
await this.setContentType(result, path, response)
|
|
198
199
|
return response
|
|
199
200
|
}
|
|
200
201
|
|
|
202
|
+
private async setContentType (bytes: Uint8Array, path: string, response: Response): Promise<void> {
|
|
203
|
+
let contentType = 'application/octet-stream'
|
|
204
|
+
|
|
205
|
+
if (this.contentTypeParser != null) {
|
|
206
|
+
try {
|
|
207
|
+
let fileName = path.split('/').pop()?.trim()
|
|
208
|
+
fileName = fileName === '' ? undefined : fileName
|
|
209
|
+
const parsed = this.contentTypeParser(bytes, fileName)
|
|
210
|
+
|
|
211
|
+
if (isPromise(parsed)) {
|
|
212
|
+
const result = await parsed
|
|
213
|
+
|
|
214
|
+
if (result != null) {
|
|
215
|
+
contentType = result
|
|
216
|
+
}
|
|
217
|
+
} else if (parsed != null) {
|
|
218
|
+
contentType = parsed
|
|
219
|
+
}
|
|
220
|
+
} catch (err) {
|
|
221
|
+
this.log.error('Error parsing content type', err)
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
response.headers.set('content-type', contentType)
|
|
226
|
+
}
|
|
227
|
+
|
|
201
228
|
/**
|
|
202
229
|
* Determines the format requested by the client, defaults to `null` if no format is requested.
|
|
203
230
|
*
|
|
@@ -321,3 +348,7 @@ export class VerifiedFetch {
|
|
|
321
348
|
await this.helia.stop()
|
|
322
349
|
}
|
|
323
350
|
}
|
|
351
|
+
|
|
352
|
+
function isPromise <T> (p?: any): p is Promise<T> {
|
|
353
|
+
return p?.then != null
|
|
354
|
+
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
interface TestInput {
|
|
2
|
-
bytes: Uint8Array;
|
|
3
|
-
path: string;
|
|
4
|
-
}
|
|
5
|
-
export declare const DEFAULT_MIME_TYPE = "application/octet-stream";
|
|
6
|
-
/**
|
|
7
|
-
* Get the content type from the input based on the tests.
|
|
8
|
-
*/
|
|
9
|
-
export declare function getContentType(input: TestInput): Promise<string>;
|
|
10
|
-
export {};
|
|
11
|
-
//# sourceMappingURL=get-content-type.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"get-content-type.d.ts","sourceRoot":"","sources":["../../../src/utils/get-content-type.ts"],"names":[],"mappings":"AAEA,UAAU,SAAS;IACjB,KAAK,EAAE,UAAU,CAAA;IACjB,IAAI,EAAE,MAAM,CAAA;CACb;AAID,eAAO,MAAM,iBAAiB,6BAA6B,CAAA;AAkC3D;;GAEG;AACH,wBAAsB,cAAc,CAAE,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,CAQvE"}
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import mime from 'mime-types';
|
|
2
|
-
export const DEFAULT_MIME_TYPE = 'application/octet-stream';
|
|
3
|
-
const xmlRegex = /^(<\?xml[^>]+>)?[^<^\w]+<svg/ig;
|
|
4
|
-
/**
|
|
5
|
-
* Tests to determine the content type of the input.
|
|
6
|
-
* The order is important on this one.
|
|
7
|
-
*/
|
|
8
|
-
const tests = [
|
|
9
|
-
// svg
|
|
10
|
-
async ({ bytes }) => xmlRegex.test(new TextDecoder().decode(bytes.slice(0, 64)))
|
|
11
|
-
? 'image/svg+xml'
|
|
12
|
-
: undefined,
|
|
13
|
-
// testing file-type from path
|
|
14
|
-
async ({ path }) => {
|
|
15
|
-
const mimeType = mime.lookup(path);
|
|
16
|
-
if (mimeType !== false) {
|
|
17
|
-
return mimeType;
|
|
18
|
-
}
|
|
19
|
-
return undefined;
|
|
20
|
-
}
|
|
21
|
-
];
|
|
22
|
-
const overrides = {
|
|
23
|
-
'video/quicktime': 'video/mp4'
|
|
24
|
-
};
|
|
25
|
-
/**
|
|
26
|
-
* Override the content type based on overrides.
|
|
27
|
-
*/
|
|
28
|
-
function overrideContentType(type) {
|
|
29
|
-
return overrides[type] ?? type;
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Get the content type from the input based on the tests.
|
|
33
|
-
*/
|
|
34
|
-
export async function getContentType(input) {
|
|
35
|
-
for (const test of tests) {
|
|
36
|
-
const type = await test(input);
|
|
37
|
-
if (type !== undefined) {
|
|
38
|
-
return overrideContentType(type);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
return DEFAULT_MIME_TYPE;
|
|
42
|
-
}
|
|
43
|
-
//# sourceMappingURL=get-content-type.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"get-content-type.js","sourceRoot":"","sources":["../../../src/utils/get-content-type.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,YAAY,CAAA;AAS7B,MAAM,CAAC,MAAM,iBAAiB,GAAG,0BAA0B,CAAA;AAE3D,MAAM,QAAQ,GAAG,gCAAgC,CAAA;AAEjD;;;GAGG;AACH,MAAM,KAAK,GAA4C;IACrD,MAAM;IACN,KAAK,EAAE,EAAE,KAAK,EAAE,EAAc,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QAC1F,CAAC,CAAC,eAAe;QACjB,CAAC,CAAC,SAAS;IACb,8BAA8B;IAC9B,KAAK,EAAE,EAAE,IAAI,EAAE,EAAc,EAAE;QAC7B,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QAClC,IAAI,QAAQ,KAAK,KAAK,EAAE,CAAC;YACvB,OAAO,QAAQ,CAAA;QACjB,CAAC;QACD,OAAO,SAAS,CAAA;IAClB,CAAC;CACF,CAAA;AAED,MAAM,SAAS,GAA2B;IACxC,iBAAiB,EAAE,WAAW;CAC/B,CAAA;AAED;;GAEG;AACH,SAAS,mBAAmB,CAAE,IAAY;IACxC,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,CAAA;AAChC,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAE,KAAgB;IACpD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,CAAA;QAC9B,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,mBAAmB,CAAC,IAAI,CAAC,CAAA;QAClC,CAAC;IACH,CAAC;IACD,OAAO,iBAAiB,CAAA;AAC1B,CAAC"}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { VerifiedFetchInit } from '../index.js';
|
|
2
|
-
import type { ComponentLogger } from '@libp2p/interface';
|
|
3
|
-
/**
|
|
4
|
-
* Converts an async iterator of Uint8Array bytes to a stream and attempts to determine the content type of those bytes.
|
|
5
|
-
*/
|
|
6
|
-
export declare function getStreamAndContentType(iterator: AsyncIterable<Uint8Array>, path: string, logger: ComponentLogger, options?: Pick<VerifiedFetchInit, 'onProgress'>): Promise<{
|
|
7
|
-
contentType: string;
|
|
8
|
-
stream: ReadableStream<Uint8Array>;
|
|
9
|
-
}>;
|
|
10
|
-
//# sourceMappingURL=get-stream-and-content-type.d.ts.map
|