@helia/verified-fetch 0.0.0-3283a5c

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.
Files changed (44) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +299 -0
  3. package/dist/index.min.js +115 -0
  4. package/dist/src/index.d.ts +321 -0
  5. package/dist/src/index.d.ts.map +1 -0
  6. package/dist/src/index.js +290 -0
  7. package/dist/src/index.js.map +1 -0
  8. package/dist/src/singleton.d.ts +3 -0
  9. package/dist/src/singleton.d.ts.map +1 -0
  10. package/dist/src/singleton.js +15 -0
  11. package/dist/src/singleton.js.map +1 -0
  12. package/dist/src/utils/get-stream-from-async-iterable.d.ts +10 -0
  13. package/dist/src/utils/get-stream-from-async-iterable.d.ts.map +1 -0
  14. package/dist/src/utils/get-stream-from-async-iterable.js +38 -0
  15. package/dist/src/utils/get-stream-from-async-iterable.js.map +1 -0
  16. package/dist/src/utils/parse-resource.d.ts +18 -0
  17. package/dist/src/utils/parse-resource.d.ts.map +1 -0
  18. package/dist/src/utils/parse-resource.js +24 -0
  19. package/dist/src/utils/parse-resource.js.map +1 -0
  20. package/dist/src/utils/parse-url-string.d.ts +26 -0
  21. package/dist/src/utils/parse-url-string.d.ts.map +1 -0
  22. package/dist/src/utils/parse-url-string.js +109 -0
  23. package/dist/src/utils/parse-url-string.js.map +1 -0
  24. package/dist/src/utils/tlru.d.ts +15 -0
  25. package/dist/src/utils/tlru.d.ts.map +1 -0
  26. package/dist/src/utils/tlru.js +40 -0
  27. package/dist/src/utils/tlru.js.map +1 -0
  28. package/dist/src/utils/walk-path.d.ts +13 -0
  29. package/dist/src/utils/walk-path.d.ts.map +1 -0
  30. package/dist/src/utils/walk-path.js +17 -0
  31. package/dist/src/utils/walk-path.js.map +1 -0
  32. package/dist/src/verified-fetch.d.ts +67 -0
  33. package/dist/src/verified-fetch.d.ts.map +1 -0
  34. package/dist/src/verified-fetch.js +289 -0
  35. package/dist/src/verified-fetch.js.map +1 -0
  36. package/package.json +176 -0
  37. package/src/index.ts +377 -0
  38. package/src/singleton.ts +20 -0
  39. package/src/utils/get-stream-from-async-iterable.ts +45 -0
  40. package/src/utils/parse-resource.ts +40 -0
  41. package/src/utils/parse-url-string.ts +139 -0
  42. package/src/utils/tlru.ts +52 -0
  43. package/src/utils/walk-path.ts +34 -0
  44. package/src/verified-fetch.ts +354 -0
package/src/index.ts ADDED
@@ -0,0 +1,377 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
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
+ *
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
+ *
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.
13
+ *
14
+ * You may use any supported resource argument to fetch content:
15
+ *
16
+ * - [CID](https://multiformats.github.io/js-multiformats/classes/cid.CID.html) instance
17
+ * - IPFS URL
18
+ * - IPNS URL
19
+ *
20
+ * @example Getting started
21
+ *
22
+ * ```typescript
23
+ * import { verifiedFetch } from '@helia/verified-fetch'
24
+ *
25
+ * const resp = await verifiedFetch('ipfs://bafy...')
26
+ *
27
+ * const json = await resp.json()
28
+ *```
29
+ *
30
+ * @example Using a CID instance to fetch JSON
31
+ *
32
+ * ```typescript
33
+ * import { verifiedFetch } from '@helia/verified-fetch'
34
+ * import { CID } from 'multiformats/cid'
35
+ *
36
+ * const cid = CID.parse('bafyFoo') // some image file
37
+ * const response = await verifiedFetch(cid)
38
+ * const json = await response.json()
39
+ * ```
40
+ *
41
+ * @example Using IPFS protocol to fetch an image
42
+ *
43
+ * ```typescript
44
+ * import { verifiedFetch } from '@helia/verified-fetch'
45
+ *
46
+ * const response = await verifiedFetch('ipfs://bafyFoo') // CID for some image file
47
+ * const blob = await response.blob()
48
+ * const image = document.createElement('img')
49
+ * image.src = URL.createObjectURL(blob)
50
+ * document.body.appendChild(image)
51
+ * ```
52
+ *
53
+ * @example Using IPNS protocol to stream a big file
54
+ *
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
73
+ * import { createVerifiedFetch } from '@helia/verified-fetch'
74
+ *
75
+ * const fetch = await createVerifiedFetch({
76
+ * gateways: ['https://trustless-gateway.link'],
77
+ * routers: ['http://delegated-ipfs.dev']
78
+ * })
79
+ *
80
+ * const resp = await fetch('ipfs://bafy...')
81
+ *
82
+ * const json = await resp.json()
83
+ *```
84
+ *
85
+ * ### Usage with customized Helia
86
+ *
87
+ * For full control of how `@helia/verified-fetch` fetches content from the distributed web you can pass a preconfigured Helia node to `createVerifiedFetch`.
88
+ *
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.
92
+ *
93
+ * ```typescript
94
+ * import { trustlessGateway } from '@helia/block-brokers'
95
+ * import { createHeliaHTTP } from '@helia/http'
96
+ * import { delegatedHTTPRouting } from '@helia/routers'
97
+ * import { createVerifiedFetch } from '@helia/verified-fetch'
98
+ *
99
+ * const fetch = await createVerifiedFetch(
100
+ * await createHeliaHTTP({
101
+ * blockBrokers: [
102
+ * trustlessGateway({
103
+ * gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
104
+ * })
105
+ * ],
106
+ * routers: ['http://delegated-ipfs.dev'].map((routerUrl) => delegatedHTTPRouting(routerUrl))
107
+ * })
108
+ * )
109
+ *
110
+ * const resp = await fetch('ipfs://bafy...')
111
+ *
112
+ * const json = await resp.json()
113
+ * ```
114
+ *
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.
118
+ *
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.
144
+ *
145
+ * [The `fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/fetch) takes two parameters:
146
+ *
147
+ * 1. A [resource](https://developer.mozilla.org/en-US/docs/Web/API/fetch#resource)
148
+ * 2. An [options object](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)
149
+ *
150
+ * ### Resource argument
151
+ *
152
+ * This library supports the following methods of fetching web3 content from IPFS:
153
+ *
154
+ * 1. IPFS protocol: `ipfs://<cidv0>` & `ipfs://<cidv0>`
155
+ * 2. IPNS protocol: `ipns://<peerId>` & `ipns://<publicKey>` & `ipns://<hostUri_Supporting_DnsLink_TxtRecords>`
156
+ * 3. CID instances: An actual CID instance `CID.parse('bafy...')`
157
+ *
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).
159
+ *
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.
161
+ *
162
+ * ### Options argument
163
+ *
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.
165
+ *
166
+ * Some of those header specifications are:
167
+ *
168
+ * 1. https://specs.ipfs.tech/http-gateways/path-gateway/#request-headers
169
+ * 2. https://specs.ipfs.tech/http-gateways/trustless-gateway/#request-headers
170
+ * 3. https://specs.ipfs.tech/http-gateways/subdomain-gateway/#request-headers
171
+ *
172
+ * Where possible, options and Helia internals will be automatically configured to the appropriate codec & content type based on the `verified-fetch` configuration and `options` argument passed.
173
+ *
174
+ * Known Fetch API options that will be supported:
175
+ *
176
+ * 1. `signal` - An AbortSignal that a user can use to abort the request.
177
+ * 2. `redirect` - A string that specifies the redirect type. One of `follow`, `error`, or `manual`. Defaults to `follow`. Best effort to adhere to the [Fetch API redirect](https://developer.mozilla.org/en-US/docs/Web/API/fetch#redirect) parameter.
178
+ * 3. `headers` - An object of headers to be sent with the request. Best effort to adhere to the [Fetch API headers](https://developer.mozilla.org/en-US/docs/Web/API/fetch#headers) parameter.
179
+ * - `accept` - A string that specifies the accept header. Relevant values:
180
+ * - [`vnd.ipld.raw`](https://www.iana.org/assignments/media-types/application/vnd.ipld.raw). (default)
181
+ * - [`vnd.ipld.car`](https://www.iana.org/assignments/media-types/application/vnd.ipld.car)
182
+ * - [`vnd.ipfs.ipns-record`](https://www.iana.org/assignments/media-types/application/vnd.ipfs.ipns-record)
183
+ * 4. `method` - A string that specifies the HTTP method to use for the request. Defaults to `GET`. Best effort to adhere to the [Fetch API method](https://developer.mozilla.org/en-US/docs/Web/API/fetch#method) parameter.
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.
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.
186
+ *
187
+ * Non-Fetch API options that will be supported:
188
+ *
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:
190
+ * - `helia:verified-fetch:error` - An error occurred during the request.
191
+ * - `helia:verified-fetch:request:start` - The request has been sent
192
+ * - `helia:verified-fetch:request:complete` - The request has been sent
193
+ * - `helia:verified-fetch:request:error` - An error occurred during the request.
194
+ * - `helia:verified-fetch:request:abort` - The request was aborted prior to completion.
195
+ * - `helia:verified-fetch:response:start` - The initial HTTP Response headers have been set, and response stream is started.
196
+ * - `helia:verified-fetch:response:complete` - The response stream has completed.
197
+ * - `helia:verified-fetch:response:error` - An error occurred while building the response.
198
+ *
199
+ * Some in-flight specs (IPIPs) that will affect the options object this library supports in the future can be seen at https://specs.ipfs.tech/ipips, a subset are:
200
+ *
201
+ * 1. [IPIP-0412: Signaling Block Order in CARs on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0412/)
202
+ * 2. [IPIP-0402: Partial CAR Support on Trustless Gateways](https://specs.ipfs.tech/ipips/ipip-0402/)
203
+ * 3. [IPIP-0386: Subdomain Gateway Interop with _redirects](https://specs.ipfs.tech/ipips/ipip-0386/)
204
+ * 4. [IPIP-0328: JSON and CBOR Response Formats on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0328/)
205
+ * 5. [IPIP-0288: TAR Response Format on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0288/)
206
+ *
207
+ * ### Response types
208
+ *
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.
210
+ *
211
+ * All content we retrieve from the IPFS network is obtained via an AsyncIterable, and will be set as the [body of the HTTP Response](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#body) via a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#consuming_a_fetch_as_a_stream) or other efficient method that avoids loading the entire response into memory or getting the entire response from the network before returning a response to the user.
212
+ *
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.
214
+ *
215
+ * #### Handling response types
216
+ *
217
+ * For handling responses we want to follow conventions/abstractions from Fetch API where possible:
218
+ *
219
+ * - For JSON, assuming you abstract any differences between dag-json/dag-cbor/json/and json-file-on-unixfs, you would call `.json()` to get a JSON object.
220
+ * - For images (or other web-relevant asset) you want to add to the DOM, use `.blob()` or `.arrayBuffer()` to get the raw bytes.
221
+ * - For plain text in utf-8, you would call `.text()`
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).
223
+ *
224
+ * #### Unsupported response types
225
+ *
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.
227
+ * * Others? Open an issue or PR!
228
+ *
229
+ * ### Response headers
230
+ *
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/).
232
+ *
233
+ * Some known header specifications:
234
+ *
235
+ * * https://specs.ipfs.tech/http-gateways/path-gateway/#response-headers
236
+ * * https://specs.ipfs.tech/http-gateways/trustless-gateway/#response-headers
237
+ * * https://specs.ipfs.tech/http-gateways/subdomain-gateway/#response-headers
238
+ *
239
+ * ### Possible Scenarios that could cause confusion
240
+ *
241
+ * #### Attempting to fetch the CID for content that does not make sense
242
+ *
243
+ * If you request `bafybeiaysi4s6lnjev27ln5icwm6tueaw2vdykrtjkwiphwekaywqhcjze`, which points to the root of the en.wikipedia.org mirror, a response object does not make sense.
244
+ *
245
+ * ### Errors
246
+ *
247
+ * Known Errors that can be thrown:
248
+ *
249
+ * 1. `TypeError` - If the resource argument is not a string, CID, or CID string.
250
+ * 2. `TypeError` - If the options argument is passed and not an object.
251
+ * 3. `TypeError` - If the options argument is passed and is malformed.
252
+ * 4. `AbortError` - If the content request is aborted due to user aborting provided AbortSignal.
253
+ */
254
+
255
+ import { trustlessGateway } from '@helia/block-brokers'
256
+ import { createHeliaHTTP } from '@helia/http'
257
+ import { delegatedHTTPRouting } from '@helia/routers'
258
+ import { VerifiedFetch as VerifiedFetchClass } from './verified-fetch.js'
259
+ import type { Helia } from '@helia/interface'
260
+ import type { IPNSRoutingEvents, ResolveDnsLinkProgressEvents, ResolveProgressEvents } from '@helia/ipns'
261
+ import type { GetEvents } from '@helia/unixfs'
262
+ import type { CID } from 'multiformats/cid'
263
+ import type { ProgressEvent, ProgressOptions } from 'progress-events'
264
+
265
+ /**
266
+ * The types for the first argument of the `verifiedFetch` function.
267
+ */
268
+ export type Resource = string | CID
269
+
270
+ export interface CIDDetail {
271
+ cid: string
272
+ path: string
273
+ }
274
+
275
+ export interface CIDDetailError extends CIDDetail {
276
+ error: Error
277
+ }
278
+
279
+ export interface VerifiedFetch {
280
+ (resource: Resource, options?: VerifiedFetchInit): Promise<Response>
281
+ start(): Promise<void>
282
+ stop(): Promise<void>
283
+ }
284
+
285
+ /**
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.
288
+ */
289
+ export interface CreateVerifiedFetchInit {
290
+ gateways: string[]
291
+ routers?: string[]
292
+ }
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
+
318
+ export type BubbledProgressEvents =
319
+ // unixfs
320
+ GetEvents |
321
+ // ipns
322
+ ResolveProgressEvents | ResolveDnsLinkProgressEvents | IPNSRoutingEvents
323
+
324
+ export type VerifiedFetchProgressEvents =
325
+ ProgressEvent<'verified-fetch:request:start', CIDDetail> |
326
+ ProgressEvent<'verified-fetch:request:info', string> |
327
+ ProgressEvent<'verified-fetch:request:progress:chunk', CIDDetail> |
328
+ ProgressEvent<'verified-fetch:request:end', CIDDetail> |
329
+ ProgressEvent<'verified-fetch:request:error', CIDDetailError>
330
+
331
+ /**
332
+ * Options for the `fetch` function returned by `createVerifiedFetch`.
333
+ *
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.
337
+ */
338
+ export interface VerifiedFetchInit extends RequestInit, ProgressOptions<BubbledProgressEvents | VerifiedFetchProgressEvents> {
339
+ }
340
+
341
+ /**
342
+ * Create and return a Helia node
343
+ */
344
+ export async function createVerifiedFetch (init?: Helia | CreateVerifiedFetchInit, options?: CreateVerifiedFetchOptions): Promise<VerifiedFetch> {
345
+ const contentTypeParser: ContentTypeParser | undefined = options?.contentTypeParser
346
+
347
+ if (!isHelia(init)) {
348
+ init = await createHeliaHTTP({
349
+ blockBrokers: [
350
+ trustlessGateway({
351
+ gateways: init?.gateways
352
+ })
353
+ ],
354
+ routers: (init?.routers ?? ['https://delegated-ipfs.dev']).map((routerUrl) => delegatedHTTPRouting(routerUrl))
355
+ })
356
+ }
357
+
358
+ const verifiedFetchInstance = new VerifiedFetchClass({ helia: init }, { contentTypeParser })
359
+ async function verifiedFetch (resource: Resource, options?: VerifiedFetchInit): Promise<Response> {
360
+ return verifiedFetchInstance.fetch(resource, options)
361
+ }
362
+ verifiedFetch.stop = verifiedFetchInstance.stop.bind(verifiedFetchInstance)
363
+ verifiedFetch.start = verifiedFetchInstance.start.bind(verifiedFetchInstance)
364
+
365
+ return verifiedFetch
366
+ }
367
+
368
+ export { verifiedFetch } from './singleton.js'
369
+
370
+ function isHelia (obj: any): obj is Helia {
371
+ // test for the presence of known Helia properties, return a boolean value
372
+ return obj?.blockstore != null &&
373
+ obj?.datastore != null &&
374
+ obj?.gc != null &&
375
+ obj?.stop != null &&
376
+ obj?.start != null
377
+ }
@@ -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
+ }
@@ -0,0 +1,45 @@
1
+ import { CustomProgressEvent } from 'progress-events'
2
+ import type { VerifiedFetchInit } from '../index.js'
3
+ import type { ComponentLogger } from '@libp2p/interface'
4
+
5
+ /**
6
+ * Converts an async iterator of Uint8Array bytes to a stream and returns the first chunk of bytes
7
+ */
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')
10
+ const reader = iterator[Symbol.asyncIterator]()
11
+ const { value: firstChunk, done } = await reader.next()
12
+
13
+ if (done === true) {
14
+ log.error('No content found for path', path)
15
+ throw new Error('No content found')
16
+ }
17
+
18
+ const stream = new ReadableStream({
19
+ async start (controller) {
20
+ // the initial value is already available
21
+ options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
22
+ controller.enqueue(firstChunk)
23
+ },
24
+ async pull (controller) {
25
+ const { value, done } = await reader.next()
26
+
27
+ if (done === true) {
28
+ if (value != null) {
29
+ options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
30
+ controller.enqueue(value)
31
+ }
32
+ controller.close()
33
+ return
34
+ }
35
+
36
+ options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
37
+ controller.enqueue(value)
38
+ }
39
+ })
40
+
41
+ return {
42
+ stream,
43
+ firstChunk
44
+ }
45
+ }
@@ -0,0 +1,40 @@
1
+ import { CID } from 'multiformats/cid'
2
+ import { parseUrlString } from './parse-url-string.js'
3
+ import type { ParsedUrlStringResults } from './parse-url-string.js'
4
+ import type { Resource } from '../index.js'
5
+ import type { IPNS, IPNSRoutingEvents, ResolveDnsLinkProgressEvents, ResolveProgressEvents } from '@helia/ipns'
6
+ import type { ComponentLogger } from '@libp2p/interface'
7
+ import type { ProgressOptions } from 'progress-events'
8
+
9
+ export interface ParseResourceComponents {
10
+ ipns: IPNS
11
+ logger: ComponentLogger
12
+ }
13
+
14
+ export interface ParseResourceOptions extends ProgressOptions<ResolveProgressEvents | IPNSRoutingEvents | ResolveDnsLinkProgressEvents> {
15
+
16
+ }
17
+ /**
18
+ * Handles the different use cases for the `resource` argument.
19
+ * The resource can represent an IPFS path, IPNS path, or CID.
20
+ * If the resource represents an IPNS path, we need to resolve it to a CID.
21
+ */
22
+ export async function parseResource (resource: Resource, { ipns, logger }: ParseResourceComponents, options?: ParseResourceOptions): Promise<ParsedUrlStringResults> {
23
+ if (typeof resource === 'string') {
24
+ return parseUrlString({ urlString: resource, ipns, logger }, { onProgress: options?.onProgress })
25
+ }
26
+
27
+ const cid = CID.asCID(resource)
28
+
29
+ if (cid != null) {
30
+ // an actual CID
31
+ return {
32
+ cid,
33
+ protocol: 'ipfs',
34
+ path: '',
35
+ query: {}
36
+ }
37
+ }
38
+
39
+ throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${resource}`)
40
+ }
@@ -0,0 +1,139 @@
1
+ import { peerIdFromString } from '@libp2p/peer-id'
2
+ import { CID } from 'multiformats/cid'
3
+ import { TLRU } from './tlru.js'
4
+ import type { IPNS, IPNSRoutingEvents, ResolveDnsLinkProgressEvents, ResolveProgressEvents, ResolveResult } from '@helia/ipns'
5
+ import type { ComponentLogger } from '@libp2p/interface'
6
+ import type { ProgressOptions } from 'progress-events'
7
+
8
+ const ipnsCache = new TLRU<ResolveResult>(1000)
9
+
10
+ export interface ParseUrlStringInput {
11
+ urlString: string
12
+ ipns: IPNS
13
+ logger: ComponentLogger
14
+ }
15
+ export interface ParseUrlStringOptions extends ProgressOptions<ResolveProgressEvents | IPNSRoutingEvents | ResolveDnsLinkProgressEvents> {
16
+
17
+ }
18
+
19
+ export interface ParsedUrlStringResults {
20
+ protocol: string
21
+ path: string
22
+ cid: CID
23
+ query: Record<string, string>
24
+ }
25
+
26
+ const URL_REGEX = /^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/$?]+)\/?(?<path>[^$?]*)\??(?<queryString>.*)$/
27
+
28
+ /**
29
+ * A function that parses ipfs:// and ipns:// URLs, returning an object with easily recognizable properties.
30
+ *
31
+ * After determining the protocol successfully, we process the cidOrPeerIdOrDnsLink:
32
+ * * If it's ipfs, it parses the CID or throws an Aggregate error
33
+ * * If it's ipns, it attempts to resolve the PeerId and then the DNSLink. If both fail, an Aggregate error is thrown.
34
+ */
35
+ export async function parseUrlString ({ urlString, ipns, logger }: ParseUrlStringInput, options?: ParseUrlStringOptions): Promise<ParsedUrlStringResults> {
36
+ const log = logger.forComponent('helia:verified-fetch:parse-url-string')
37
+ const match = urlString.match(URL_REGEX)
38
+
39
+ if (match == null || match.groups == null) {
40
+ throw new TypeError(`Invalid URL: ${urlString}, please use ipfs:// or ipns:// URLs only.`)
41
+ }
42
+
43
+ const { protocol, cidOrPeerIdOrDnsLink, path: urlPath, queryString } = match.groups
44
+
45
+ let cid: CID | undefined
46
+ let resolvedPath: string | undefined
47
+ const errors: Error[] = []
48
+
49
+ if (protocol === 'ipfs') {
50
+ try {
51
+ cid = CID.parse(cidOrPeerIdOrDnsLink)
52
+ } catch (err) {
53
+ log.error(err)
54
+ errors.push(new TypeError('Invalid CID for ipfs://<cid> URL'))
55
+ }
56
+ } else {
57
+ let resolveResult = ipnsCache.get(cidOrPeerIdOrDnsLink)
58
+
59
+ if (resolveResult != null) {
60
+ cid = resolveResult.cid
61
+ resolvedPath = resolveResult.path
62
+ log.trace('resolved %s to %c from cache', cidOrPeerIdOrDnsLink, cid)
63
+ } else {
64
+ // protocol is ipns
65
+ log.trace('Attempting to resolve PeerId for %s', cidOrPeerIdOrDnsLink)
66
+ let peerId = null
67
+
68
+ try {
69
+ peerId = peerIdFromString(cidOrPeerIdOrDnsLink)
70
+ resolveResult = await ipns.resolve(peerId, { onProgress: options?.onProgress })
71
+ cid = resolveResult?.cid
72
+ resolvedPath = resolveResult?.path
73
+ log.trace('resolved %s to %c', cidOrPeerIdOrDnsLink, cid)
74
+ ipnsCache.set(cidOrPeerIdOrDnsLink, resolveResult, 60 * 1000 * 2)
75
+ } catch (err) {
76
+ if (peerId == null) {
77
+ log.error('Could not parse PeerId string "%s"', cidOrPeerIdOrDnsLink, err)
78
+ errors.push(new TypeError(`Could not parse PeerId in ipns url "${cidOrPeerIdOrDnsLink}", ${(err as Error).message}`))
79
+ } else {
80
+ log.error('Could not resolve PeerId %c', peerId, err)
81
+ errors.push(new TypeError(`Could not resolve PeerId "${cidOrPeerIdOrDnsLink}", ${(err as Error).message}`))
82
+ }
83
+ }
84
+
85
+ if (cid == null) {
86
+ log.trace('Attempting to resolve DNSLink for %s', cidOrPeerIdOrDnsLink)
87
+
88
+ try {
89
+ resolveResult = await ipns.resolveDns(cidOrPeerIdOrDnsLink, { onProgress: options?.onProgress })
90
+ cid = resolveResult?.cid
91
+ resolvedPath = resolveResult?.path
92
+ log.trace('resolved %s to %c', cidOrPeerIdOrDnsLink, cid)
93
+ ipnsCache.set(cidOrPeerIdOrDnsLink, resolveResult, 60 * 1000 * 2)
94
+ } catch (err) {
95
+ log.error('Could not resolve DnsLink for "%s"', cidOrPeerIdOrDnsLink, err)
96
+ errors.push(err as Error)
97
+ }
98
+ }
99
+ }
100
+ }
101
+
102
+ if (cid == null) {
103
+ throw new AggregateError(errors, `Invalid resource. Cannot determine CID from URL "${urlString}"`)
104
+ }
105
+
106
+ // parse query string
107
+ const query: Record<string, string> = {}
108
+
109
+ if (queryString != null && queryString.length > 0) {
110
+ const queryParts = queryString.split('&')
111
+ for (const part of queryParts) {
112
+ const [key, value] = part.split('=')
113
+ query[key] = decodeURIComponent(value)
114
+ }
115
+ }
116
+
117
+ /**
118
+ * join the path from resolve result & given path.
119
+ * e.g. /ipns/<peerId>/ that is resolved to /ipfs/<cid>/<path1>, when requested as /ipns/<peerId>/<path2>, should be
120
+ * resolved to /ipfs/<cid>/<path1>/<path2>
121
+ */
122
+ const pathParts = []
123
+
124
+ if (urlPath.length > 0) {
125
+ pathParts.push(urlPath)
126
+ }
127
+
128
+ if (resolvedPath != null && resolvedPath.length > 0) {
129
+ pathParts.push(resolvedPath)
130
+ }
131
+ const path = pathParts.join('/')
132
+
133
+ return {
134
+ protocol,
135
+ cid,
136
+ path,
137
+ query
138
+ }
139
+ }
@@ -0,0 +1,52 @@
1
+ import hashlru from 'hashlru'
2
+
3
+ /**
4
+ * Time Aware Least Recent Used Cache
5
+ *
6
+ * @see https://arxiv.org/pdf/1801.00390
7
+ */
8
+ export class TLRU<T> {
9
+ private readonly lru: ReturnType<typeof hashlru>
10
+
11
+ constructor (maxSize: number) {
12
+ this.lru = hashlru(maxSize)
13
+ }
14
+
15
+ get (key: string): T | undefined {
16
+ const value = this.lru.get(key)
17
+
18
+ if (value != null) {
19
+ if (value.expire != null && value.expire < Date.now()) {
20
+ this.lru.remove(key)
21
+
22
+ return undefined
23
+ }
24
+
25
+ return value.value
26
+ }
27
+
28
+ return undefined
29
+ }
30
+
31
+ set (key: string, value: T, ttl: number): void {
32
+ this.lru.set(key, { value, expire: Date.now() + ttl })
33
+ }
34
+
35
+ has (key: string): boolean {
36
+ const value = this.get(key)
37
+
38
+ if (value != null) {
39
+ return true
40
+ }
41
+
42
+ return false
43
+ }
44
+
45
+ remove (key: string): void {
46
+ this.lru.remove(key)
47
+ }
48
+
49
+ clear (): void {
50
+ this.lru.clear()
51
+ }
52
+ }