@helia/verified-fetch 0.0.0-3851fe2

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 (49) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +275 -0
  3. package/dist/index.min.js +140 -0
  4. package/dist/src/index.d.ts +271 -0
  5. package/dist/src/index.d.ts.map +1 -0
  6. package/dist/src/index.js +263 -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-content-type.d.ts +11 -0
  13. package/dist/src/utils/get-content-type.d.ts.map +1 -0
  14. package/dist/src/utils/get-content-type.js +43 -0
  15. package/dist/src/utils/get-content-type.js.map +1 -0
  16. package/dist/src/utils/get-stream-and-content-type.d.ts +10 -0
  17. package/dist/src/utils/get-stream-and-content-type.d.ts.map +1 -0
  18. package/dist/src/utils/get-stream-and-content-type.js +37 -0
  19. package/dist/src/utils/get-stream-and-content-type.js.map +1 -0
  20. package/dist/src/utils/parse-resource.d.ts +18 -0
  21. package/dist/src/utils/parse-resource.d.ts.map +1 -0
  22. package/dist/src/utils/parse-resource.js +24 -0
  23. package/dist/src/utils/parse-resource.js.map +1 -0
  24. package/dist/src/utils/parse-url-string.d.ts +26 -0
  25. package/dist/src/utils/parse-url-string.d.ts.map +1 -0
  26. package/dist/src/utils/parse-url-string.js +109 -0
  27. package/dist/src/utils/parse-url-string.js.map +1 -0
  28. package/dist/src/utils/tlru.d.ts +15 -0
  29. package/dist/src/utils/tlru.d.ts.map +1 -0
  30. package/dist/src/utils/tlru.js +40 -0
  31. package/dist/src/utils/tlru.js.map +1 -0
  32. package/dist/src/utils/walk-path.d.ts +13 -0
  33. package/dist/src/utils/walk-path.d.ts.map +1 -0
  34. package/dist/src/utils/walk-path.js +17 -0
  35. package/dist/src/utils/walk-path.js.map +1 -0
  36. package/dist/src/verified-fetch.d.ts +64 -0
  37. package/dist/src/verified-fetch.d.ts.map +1 -0
  38. package/dist/src/verified-fetch.js +261 -0
  39. package/dist/src/verified-fetch.js.map +1 -0
  40. package/package.json +175 -0
  41. package/src/index.ts +323 -0
  42. package/src/singleton.ts +20 -0
  43. package/src/utils/get-content-type.ts +55 -0
  44. package/src/utils/get-stream-and-content-type.ts +44 -0
  45. package/src/utils/parse-resource.ts +40 -0
  46. package/src/utils/parse-url-string.ts +139 -0
  47. package/src/utils/tlru.ts +52 -0
  48. package/src/utils/walk-path.ts +34 -0
  49. package/src/verified-fetch.ts +323 -0
package/src/index.ts ADDED
@@ -0,0 +1,323 @@
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
+ * ## Comparison to fetch
116
+ *
117
+ * This module attempts to act as similarly to the `fetch()` API as possible.
118
+ *
119
+ * [The `fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/fetch) takes two parameters:
120
+ *
121
+ * 1. A [resource](https://developer.mozilla.org/en-US/docs/Web/API/fetch#resource)
122
+ * 2. An [options object](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)
123
+ *
124
+ * ### Resource argument
125
+ *
126
+ * This library supports the following methods of fetching web3 content from IPFS:
127
+ *
128
+ * 1. IPFS protocol: `ipfs://<cidv0>` & `ipfs://<cidv0>`
129
+ * 2. IPNS protocol: `ipns://<peerId>` & `ipns://<publicKey>` & `ipns://<hostUri_Supporting_DnsLink_TxtRecords>`
130
+ * 3. CID instances: An actual CID instance `CID.parse('bafy...')`
131
+ *
132
+ * 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).
133
+ *
134
+ * 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.
135
+ *
136
+ * ### Options argument
137
+ *
138
+ * 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.
139
+ *
140
+ * Some of those header specifications are:
141
+ *
142
+ * 1. https://specs.ipfs.tech/http-gateways/path-gateway/#request-headers
143
+ * 2. https://specs.ipfs.tech/http-gateways/trustless-gateway/#request-headers
144
+ * 3. https://specs.ipfs.tech/http-gateways/subdomain-gateway/#request-headers
145
+ *
146
+ * 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.
147
+ *
148
+ * Known Fetch API options that will be supported:
149
+ *
150
+ * 1. `signal` - An AbortSignal that a user can use to abort the request.
151
+ * 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.
152
+ * 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.
153
+ * - `accept` - A string that specifies the accept header. Relevant values:
154
+ * - [`vnd.ipld.raw`](https://www.iana.org/assignments/media-types/application/vnd.ipld.raw). (default)
155
+ * - [`vnd.ipld.car`](https://www.iana.org/assignments/media-types/application/vnd.ipld.car)
156
+ * - [`vnd.ipfs.ipns-record`](https://www.iana.org/assignments/media-types/application/vnd.ipfs.ipns-record)
157
+ * 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.
158
+ * 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.
159
+ * 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.
160
+ *
161
+ * Non-Fetch API options that will be supported:
162
+ *
163
+ * 1. `onProgress` - Similar to Helia `onProgress` options, this will be a function that will be called with a progress event. Supported progress events are:
164
+ * - `helia:verified-fetch:error` - An error occurred during the request.
165
+ * - `helia:verified-fetch:request:start` - The request has been sent
166
+ * - `helia:verified-fetch:request:complete` - The request has been sent
167
+ * - `helia:verified-fetch:request:error` - An error occurred during the request.
168
+ * - `helia:verified-fetch:request:abort` - The request was aborted prior to completion.
169
+ * - `helia:verified-fetch:response:start` - The initial HTTP Response headers have been set, and response stream is started.
170
+ * - `helia:verified-fetch:response:complete` - The response stream has completed.
171
+ * - `helia:verified-fetch:response:error` - An error occurred while building the response.
172
+ *
173
+ * 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:
174
+ *
175
+ * 1. [IPIP-0412: Signaling Block Order in CARs on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0412/)
176
+ * 2. [IPIP-0402: Partial CAR Support on Trustless Gateways](https://specs.ipfs.tech/ipips/ipip-0402/)
177
+ * 3. [IPIP-0386: Subdomain Gateway Interop with _redirects](https://specs.ipfs.tech/ipips/ipip-0386/)
178
+ * 4. [IPIP-0328: JSON and CBOR Response Formats on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0328/)
179
+ * 5. [IPIP-0288: TAR Response Format on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0288/)
180
+ *
181
+ * ### Response types
182
+ *
183
+ * 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.
184
+ *
185
+ * 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.
186
+ *
187
+ * 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.
188
+ *
189
+ * #### Handling response types
190
+ *
191
+ * For handling responses we want to follow conventions/abstractions from Fetch API where possible:
192
+ *
193
+ * - 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.
194
+ * - For images (or other web-relevant asset) you want to add to the DOM, use `.blob()` or `.arrayBuffer()` to get the raw bytes.
195
+ * - For plain text in utf-8, you would call `.text()`
196
+ * - 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).
197
+ *
198
+ * #### Unsupported response types
199
+ *
200
+ * * 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.
201
+ * * Others? Open an issue or PR!
202
+ *
203
+ * ### Response headers
204
+ *
205
+ * 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/).
206
+ *
207
+ * Some known header specifications:
208
+ *
209
+ * * https://specs.ipfs.tech/http-gateways/path-gateway/#response-headers
210
+ * * https://specs.ipfs.tech/http-gateways/trustless-gateway/#response-headers
211
+ * * https://specs.ipfs.tech/http-gateways/subdomain-gateway/#response-headers
212
+ *
213
+ * ### Possible Scenarios that could cause confusion
214
+ *
215
+ * #### Attempting to fetch the CID for content that does not make sense
216
+ *
217
+ * If you request `bafybeiaysi4s6lnjev27ln5icwm6tueaw2vdykrtjkwiphwekaywqhcjze`, which points to the root of the en.wikipedia.org mirror, a response object does not make sense.
218
+ *
219
+ * ### Errors
220
+ *
221
+ * Known Errors that can be thrown:
222
+ *
223
+ * 1. `TypeError` - If the resource argument is not a string, CID, or CID string.
224
+ * 2. `TypeError` - If the options argument is passed and not an object.
225
+ * 3. `TypeError` - If the options argument is passed and is malformed.
226
+ * 4. `AbortError` - If the content request is aborted due to user aborting provided AbortSignal.
227
+ */
228
+
229
+ import { trustlessGateway } from '@helia/block-brokers'
230
+ import { createHeliaHTTP } from '@helia/http'
231
+ import { delegatedHTTPRouting } from '@helia/routers'
232
+ import { VerifiedFetch as VerifiedFetchClass } from './verified-fetch.js'
233
+ import type { Helia } from '@helia/interface'
234
+ import type { IPNSRoutingEvents, ResolveDnsLinkProgressEvents, ResolveProgressEvents } from '@helia/ipns'
235
+ import type { GetEvents } from '@helia/unixfs'
236
+ import type { CID } from 'multiformats/cid'
237
+ import type { ProgressEvent, ProgressOptions } from 'progress-events'
238
+
239
+ /**
240
+ * The types for the first argument of the `verifiedFetch` function.
241
+ */
242
+ export type Resource = string | CID
243
+
244
+ export interface CIDDetail {
245
+ cid: string
246
+ path: string
247
+ }
248
+
249
+ export interface CIDDetailError extends CIDDetail {
250
+ error: Error
251
+ }
252
+
253
+ export interface VerifiedFetch {
254
+ (resource: Resource, options?: VerifiedFetchInit): Promise<Response>
255
+ start(): Promise<void>
256
+ stop(): Promise<void>
257
+ }
258
+
259
+ /**
260
+ * Instead of passing a Helia instance, you can pass a list of gateways and routers, and a HeliaHTTP instance will be created for you.
261
+ */
262
+ export interface CreateVerifiedFetchWithOptions {
263
+ gateways: string[]
264
+ routers?: string[]
265
+ }
266
+
267
+ export type BubbledProgressEvents =
268
+ // unixfs
269
+ GetEvents |
270
+ // ipns
271
+ ResolveProgressEvents | ResolveDnsLinkProgressEvents | IPNSRoutingEvents
272
+
273
+ export type VerifiedFetchProgressEvents =
274
+ ProgressEvent<'verified-fetch:request:start', CIDDetail> |
275
+ ProgressEvent<'verified-fetch:request:info', string> |
276
+ ProgressEvent<'verified-fetch:request:progress:chunk', CIDDetail> |
277
+ ProgressEvent<'verified-fetch:request:end', CIDDetail> |
278
+ ProgressEvent<'verified-fetch:request:error', CIDDetailError>
279
+
280
+ /**
281
+ * Options for the `fetch` function returned by `createVerifiedFetch`.
282
+ *
283
+ * This method accepts all the same options as the `fetch` function in the browser, plus an `onProgress` option to
284
+ * listen for progress events.
285
+ */
286
+ export interface VerifiedFetchInit extends RequestInit, ProgressOptions<BubbledProgressEvents | VerifiedFetchProgressEvents> {
287
+ }
288
+
289
+ /**
290
+ * Create and return a Helia node
291
+ */
292
+ export async function createVerifiedFetch (init?: Helia | CreateVerifiedFetchWithOptions): Promise<VerifiedFetch> {
293
+ if (!isHelia(init)) {
294
+ init = await createHeliaHTTP({
295
+ blockBrokers: [
296
+ trustlessGateway({
297
+ gateways: init?.gateways
298
+ })
299
+ ],
300
+ routers: (init?.routers ?? ['https://delegated-ipfs.dev']).map((routerUrl) => delegatedHTTPRouting(routerUrl))
301
+ })
302
+ }
303
+
304
+ const verifiedFetchInstance = new VerifiedFetchClass({ helia: init })
305
+ async function verifiedFetch (resource: Resource, options?: VerifiedFetchInit): Promise<Response> {
306
+ return verifiedFetchInstance.fetch(resource, options)
307
+ }
308
+ verifiedFetch.stop = verifiedFetchInstance.stop.bind(verifiedFetchInstance)
309
+ verifiedFetch.start = verifiedFetchInstance.start.bind(verifiedFetchInstance)
310
+
311
+ return verifiedFetch
312
+ }
313
+
314
+ export { verifiedFetch } from './singleton.js'
315
+
316
+ function isHelia (obj: any): obj is Helia {
317
+ // test for the presence of known Helia properties, return a boolean value
318
+ return obj?.blockstore != null &&
319
+ obj?.datastore != null &&
320
+ obj?.gc != null &&
321
+ obj?.stop != null &&
322
+ obj?.start != null
323
+ }
@@ -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,55 @@
1
+ import mime from 'mime-types'
2
+
3
+ interface TestInput {
4
+ bytes: Uint8Array
5
+ path: string
6
+ }
7
+
8
+ type TestOutput = Promise<string | undefined>
9
+
10
+ export const DEFAULT_MIME_TYPE = 'application/octet-stream'
11
+
12
+ const xmlRegex = /^(<\?xml[^>]+>)?[^<^\w]+<svg/ig
13
+
14
+ /**
15
+ * Tests to determine the content type of the input.
16
+ * The order is important on this one.
17
+ */
18
+ const tests: Array<(input: TestInput) => TestOutput> = [
19
+ // svg
20
+ async ({ bytes }): TestOutput => xmlRegex.test(new TextDecoder().decode(bytes.slice(0, 64)))
21
+ ? 'image/svg+xml'
22
+ : undefined,
23
+ // testing file-type from path
24
+ async ({ path }): TestOutput => {
25
+ const mimeType = mime.lookup(path)
26
+ if (mimeType !== false) {
27
+ return mimeType
28
+ }
29
+ return undefined
30
+ }
31
+ ]
32
+
33
+ const overrides: Record<string, string> = {
34
+ 'video/quicktime': 'video/mp4'
35
+ }
36
+
37
+ /**
38
+ * Override the content type based on overrides.
39
+ */
40
+ function overrideContentType (type: string): string {
41
+ return overrides[type] ?? type
42
+ }
43
+
44
+ /**
45
+ * Get the content type from the input based on the tests.
46
+ */
47
+ export async function getContentType (input: TestInput): Promise<string> {
48
+ for (const test of tests) {
49
+ const type = await test(input)
50
+ if (type !== undefined) {
51
+ return overrideContentType(type)
52
+ }
53
+ }
54
+ return DEFAULT_MIME_TYPE
55
+ }
@@ -0,0 +1,44 @@
1
+ import { CustomProgressEvent } from 'progress-events'
2
+ import { getContentType } from './get-content-type.js'
3
+ import type { VerifiedFetchInit } from '../index.js'
4
+ import type { ComponentLogger } from '@libp2p/interface'
5
+
6
+ /**
7
+ * Converts an async iterator of Uint8Array bytes to a stream and attempts to determine the content type of those bytes.
8
+ */
9
+ export async function getStreamAndContentType (iterator: AsyncIterable<Uint8Array>, path: string, logger: ComponentLogger, options?: Pick<VerifiedFetchInit, 'onProgress'>): Promise<{ contentType: string, stream: ReadableStream<Uint8Array> }> {
10
+ const log = logger.forComponent('helia:verified-fetch:get-stream-and-content-type')
11
+ const reader = iterator[Symbol.asyncIterator]()
12
+ const { value, done } = await reader.next()
13
+
14
+ if (done === true) {
15
+ log.error('No content found for path', path)
16
+ throw new Error('No content found')
17
+ }
18
+
19
+ const contentType = await getContentType({ bytes: value, path })
20
+ const stream = new ReadableStream({
21
+ async start (controller) {
22
+ // the initial value is already available
23
+ options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
24
+ controller.enqueue(value)
25
+ },
26
+ async pull (controller) {
27
+ const { value, done } = await reader.next()
28
+
29
+ if (done === true) {
30
+ if (value != null) {
31
+ options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
32
+ controller.enqueue(value)
33
+ }
34
+ controller.close()
35
+ return
36
+ }
37
+
38
+ options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
39
+ controller.enqueue(value)
40
+ }
41
+ })
42
+
43
+ return { contentType, stream }
44
+ }
@@ -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
+ }