@helia/verified-fetch 0.0.0-f58d467 → 1.0.0

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 (54) hide show
  1. package/README.md +285 -25
  2. package/dist/index.min.js +7 -4
  3. package/dist/src/index.d.ts +285 -25
  4. package/dist/src/index.d.ts.map +1 -1
  5. package/dist/src/index.js +267 -25
  6. package/dist/src/index.js.map +1 -1
  7. package/dist/src/types.d.ts +2 -0
  8. package/dist/src/types.d.ts.map +1 -0
  9. package/dist/src/types.js +2 -0
  10. package/dist/src/types.js.map +1 -0
  11. package/dist/src/utils/dag-cbor-to-safe-json.d.ts +7 -0
  12. package/dist/src/utils/dag-cbor-to-safe-json.d.ts.map +1 -0
  13. package/dist/src/utils/dag-cbor-to-safe-json.js +37 -0
  14. package/dist/src/utils/dag-cbor-to-safe-json.js.map +1 -0
  15. package/dist/src/utils/get-content-disposition-filename.d.ts +6 -0
  16. package/dist/src/utils/get-content-disposition-filename.d.ts.map +1 -0
  17. package/dist/src/utils/get-content-disposition-filename.js +16 -0
  18. package/dist/src/utils/get-content-disposition-filename.js.map +1 -0
  19. package/dist/src/utils/get-e-tag.d.ts +28 -0
  20. package/dist/src/utils/get-e-tag.d.ts.map +1 -0
  21. package/dist/src/utils/get-e-tag.js +18 -0
  22. package/dist/src/utils/get-e-tag.js.map +1 -0
  23. package/dist/src/utils/get-tar-stream.d.ts +4 -0
  24. package/dist/src/utils/get-tar-stream.d.ts.map +1 -0
  25. package/dist/src/utils/get-tar-stream.js +46 -0
  26. package/dist/src/utils/get-tar-stream.js.map +1 -0
  27. package/dist/src/utils/parse-url-string.d.ts +7 -1
  28. package/dist/src/utils/parse-url-string.d.ts.map +1 -1
  29. package/dist/src/utils/parse-url-string.js +6 -0
  30. package/dist/src/utils/parse-url-string.js.map +1 -1
  31. package/dist/src/utils/responses.d.ts +5 -0
  32. package/dist/src/utils/responses.d.ts.map +1 -0
  33. package/dist/src/utils/responses.js +27 -0
  34. package/dist/src/utils/responses.js.map +1 -0
  35. package/dist/src/utils/select-output-type.d.ts +12 -0
  36. package/dist/src/utils/select-output-type.d.ts.map +1 -0
  37. package/dist/src/utils/select-output-type.js +148 -0
  38. package/dist/src/utils/select-output-type.js.map +1 -0
  39. package/dist/src/verified-fetch.d.ts +19 -26
  40. package/dist/src/verified-fetch.d.ts.map +1 -1
  41. package/dist/src/verified-fetch.js +261 -142
  42. package/dist/src/verified-fetch.js.map +1 -1
  43. package/dist/typedoc-urls.json +27 -0
  44. package/package.json +49 -112
  45. package/src/index.ts +290 -29
  46. package/src/types.ts +1 -0
  47. package/src/utils/dag-cbor-to-safe-json.ts +44 -0
  48. package/src/utils/get-content-disposition-filename.ts +18 -0
  49. package/src/utils/get-e-tag.ts +36 -0
  50. package/src/utils/get-tar-stream.ts +68 -0
  51. package/src/utils/parse-url-string.ts +17 -2
  52. package/src/utils/responses.ts +29 -0
  53. package/src/utils/select-output-type.ts +167 -0
  54. package/src/verified-fetch.ts +310 -154
package/README.md CHANGED
@@ -4,18 +4,35 @@
4
4
  </a>
5
5
  </p>
6
6
 
7
+ # @helia/verified-fetch
8
+
7
9
  [![ipfs.tech](https://img.shields.io/badge/project-IPFS-blue.svg?style=flat-square)](https://ipfs.tech)
8
10
  [![Discuss](https://img.shields.io/discourse/https/discuss.ipfs.tech/posts.svg?style=flat-square)](https://discuss.ipfs.tech)
9
- [![codecov](https://img.shields.io/codecov/c/github/ipfs/helia.svg?style=flat-square)](https://codecov.io/gh/ipfs/helia)
10
- [![CI](https://img.shields.io/github/actions/workflow/status/ipfs/helia/main.yml?branch=main\&style=flat-square)](https://github.com/ipfs/helia/actions/workflows/main.yml?query=branch%3Amain)
11
+ [![codecov](https://img.shields.io/codecov/c/github/ipfs/helia-verified-fetch.svg?style=flat-square)](https://codecov.io/gh/ipfs/helia-verified-fetch)
12
+ [![CI](https://img.shields.io/github/actions/workflow/status/ipfs/helia-verified-fetch/js-test-and-release.yml?branch=main\&style=flat-square)](https://github.com/ipfs/helia-verified-fetch/actions/workflows/js-test-and-release.yml?query=branch%3Amain)
11
13
 
12
- > A fetch-like API for obtaining verified & trustless IPFS content on the web.
14
+ > A fetch-like API for obtaining verified & trustless IPFS content on the web
13
15
 
14
16
  # About
15
17
 
18
+ <!--
19
+
20
+ !IMPORTANT!
21
+
22
+ Everything in this README between "# About" and "# Install" is automatically
23
+ generated and will be overwritten the next time the doc generator is run.
24
+
25
+ To make changes to this section, please update the @packageDocumentation section
26
+ of src/index.js or src/index.ts
27
+
28
+ To experiment with formatting, please run "npm run docs" from the root of this
29
+ repo and examine the changes made.
30
+
31
+ -->
32
+
16
33
  `@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.
17
34
 
18
- 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.
35
+ 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. By default, CIDs are retrieved over HTTP from [trustless gateways](https://specs.ipfs.tech/http-gateways/trustless-gateway/).
19
36
 
20
37
  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.
21
38
 
@@ -45,7 +62,7 @@ const json = await resp.json()
45
62
  import { verifiedFetch } from '@helia/verified-fetch'
46
63
  import { CID } from 'multiformats/cid'
47
64
 
48
- const cid = CID.parse('bafyFoo') // some image file
65
+ const cid = CID.parse('bafyFoo') // some json file
49
66
  const response = await verifiedFetch(cid)
50
67
  const json = await response.json()
51
68
  ```
@@ -68,7 +85,7 @@ document.body.appendChild(image)
68
85
  import { verifiedFetch } from '@helia/verified-fetch'
69
86
 
70
87
  const response = await verifiedFetch('ipns://mydomain.com/path/to/very-long-file.log')
71
- const bigFileStreamReader = await response.body.getReader()
88
+ const bigFileStreamReader = await response.body?.getReader()
72
89
  ```
73
90
 
74
91
  ## Configuration
@@ -85,8 +102,8 @@ It's possible to override these by passing `gateways` and `routers` keys to the
85
102
  import { createVerifiedFetch } from '@helia/verified-fetch'
86
103
 
87
104
  const fetch = await createVerifiedFetch({
88
- gateways: ['https://trustless-gateway.link'],
89
- routers: ['http://delegated-ipfs.dev']
105
+ gateways: ['https://trustless-gateway.link'],
106
+ routers: ['http://delegated-ipfs.dev']
90
107
  })
91
108
 
92
109
  const resp = await fetch('ipfs://bafy...')
@@ -110,13 +127,13 @@ import { createVerifiedFetch } from '@helia/verified-fetch'
110
127
 
111
128
  const fetch = await createVerifiedFetch(
112
129
  await createHeliaHTTP({
113
- blockBrokers: [
114
- trustlessGateway({
115
- gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
116
- })
117
- ],
118
- routers: ['http://delegated-ipfs.dev'].map((routerUrl) => delegatedHTTPRouting(routerUrl))
119
- })
130
+ blockBrokers: [
131
+ trustlessGateway({
132
+ gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
133
+ })
134
+ ],
135
+ routers: ['http://delegated-ipfs.dev'].map((routerUrl) => delegatedHTTPRouting(routerUrl))
136
+ })
120
137
  )
121
138
 
122
139
  const resp = await fetch('ipfs://bafy...')
@@ -126,7 +143,7 @@ const json = await resp.json()
126
143
 
127
144
  ### Custom content-type parsing
128
145
 
129
- 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.
146
+ By default, if the response can be parsed as JSON, `@helia/verified-fetch` sets the `Content-Type` header as `application/json`, otherwise it sets it as `application/octet-stream` - this is because the `.json()`, `.text()`, `.blob()`, and `.arrayBuffer()` methods will usually work as expected without a detailed content type.
130
147
 
131
148
  If you require an accurate content-type you can provide a `contentTypeParser` function as an option to `createVerifiedFetch` to handle parsing the content type.
132
149
 
@@ -139,13 +156,256 @@ import { createVerifiedFetch } from '@helia/verified-fetch'
139
156
  import { fileTypeFromBuffer } from '@sgtpooki/file-type'
140
157
 
141
158
  const fetch = await createVerifiedFetch({
142
- gateways: ['https://trustless-gateway.link'],
143
- routers: ['http://delegated-ipfs.dev'],
144
- contentTypeParser: async (bytes) => {
145
- // call to some magic-byte recognition library like magic-bytes, file-type, or your own custom byte recognition
146
- return fileTypeFromBuffer(bytes)?.mime
147
- }
159
+ gateways: ['https://trustless-gateway.link'],
160
+ routers: ['http://delegated-ipfs.dev']
161
+ }, {
162
+ contentTypeParser: async (bytes) => {
163
+ // call to some magic-byte recognition library like magic-bytes, file-type, or your own custom byte recognition
164
+ const result = await fileTypeFromBuffer(bytes)
165
+ return result?.mime
166
+ }
167
+ })
168
+ ```
169
+
170
+ ### Custom DNS resolvers
171
+
172
+ If you don't want to leak DNS queries to the default resolvers, you can provide your own list of DNS resolvers to `createVerifiedFetch`.
173
+
174
+ Note that you do not need to provide both a DNS-over-HTTPS and a DNS-over-JSON resolver, and you should prefer `dnsJsonOverHttps` resolvers for usage in the browser for a smaller bundle size. See <https://github.com/ipfs/helia/tree/main/packages/ipns#example---using-dns-json-over-https> for more information.
175
+
176
+ ## Example - Customizing DNS resolvers
177
+
178
+ ```typescript
179
+ import { createVerifiedFetch } from '@helia/verified-fetch'
180
+ import { dnsJsonOverHttps, dnsOverHttps } from '@helia/ipns/dns-resolvers'
181
+
182
+ const fetch = await createVerifiedFetch({
183
+ gateways: ['https://trustless-gateway.link'],
184
+ routers: ['http://delegated-ipfs.dev'],
185
+ dnsResolvers: [
186
+ dnsJsonOverHttps('https://my-dns-resolver.example.com/dns-json'),
187
+ dnsOverHttps('https://my-dns-resolver.example.com/dns-query')
188
+ ]
189
+ })
190
+ ```
191
+
192
+ ### IPLD codec handling
193
+
194
+ IPFS supports several data formats (typically referred to as codecs) which are included in the CID. `@helia/verified-fetch` attempts to abstract away some of the details for easier consumption.
195
+
196
+ #### DAG-PB
197
+
198
+ [DAG-PB](https://ipld.io/docs/codecs/known/dag-pb/) is the codec we are most likely to encounter, it is what [UnixFS](https://github.com/ipfs/specs/blob/main/UNIXFS.md) uses under the hood.
199
+
200
+ ##### Using the DAG-PB codec as a Blob
201
+
202
+ ```typescript
203
+ import { verifiedFetch } from '@helia/verified-fetch'
204
+
205
+ const res = await verifiedFetch('ipfs://Qmfoo')
206
+ const blob = await res.blob()
207
+
208
+ console.info(blob) // Blob { size: x, type: 'application/octet-stream' }
209
+ ```
210
+
211
+ ##### Using the DAG-PB codec as an ArrayBuffer
212
+
213
+ ```typescript
214
+ import { verifiedFetch } from '@helia/verified-fetch'
215
+
216
+ const res = await verifiedFetch('ipfs://Qmfoo')
217
+ const buf = await res.arrayBuffer()
218
+
219
+ console.info(buf) // ArrayBuffer { [Uint8Contents]: < ... >, byteLength: x }
220
+ ```
221
+
222
+ ##### Using the DAG-PB codec as a stream
223
+
224
+ ```typescript
225
+ import { verifiedFetch } from '@helia/verified-fetch'
226
+
227
+ const res = await verifiedFetch('ipfs://Qmfoo')
228
+ const reader = res.body?.getReader()
229
+
230
+ if (reader == null) {
231
+ throw new Error('Could not create reader from response body')
232
+ }
233
+
234
+ while (true) {
235
+ const next = await reader.read()
236
+
237
+ if (next?.done === true) {
238
+ break
239
+ }
240
+
241
+ if (next?.value != null) {
242
+ console.info(next.value) // Uint8Array(x) [ ... ]
243
+ }
244
+ }
245
+ ```
246
+
247
+ ##### Content-Type
248
+
249
+ When fetching `DAG-PB` data, the content type will be set to `application/octet-stream` unless a custom content-type parser is configured.
250
+
251
+ #### JSON
252
+
253
+ The JSON codec is a very simple codec, a block parseable with this codec is a JSON string encoded into a `Uint8Array`.
254
+
255
+ ##### Using the JSON codec
256
+
257
+ ```typescript
258
+ import * as json from 'multiformats/codecs/json'
259
+
260
+ const block = new TextEncoder().encode('{ "hello": "world" }')
261
+ const obj = json.decode(block)
262
+
263
+ console.info(obj) // { hello: 'world' }
264
+ ```
265
+
266
+ ##### Content-Type
267
+
268
+ When the `JSON` codec is encountered, the `Content-Type` header of the response will be set to `application/json`.
269
+
270
+ ### DAG-JSON
271
+
272
+ [DAG-JSON](https://ipld.io/docs/codecs/known/dag-json/) expands on the `JSON` codec, adding the ability to contain [CID](https://docs.ipfs.tech/concepts/content-addressing/)s which act as links to other blocks, and byte arrays.
273
+
274
+ `CID`s and byte arrays are represented using special object structures with a single `"/"` property.
275
+
276
+ Using `DAG-JSON` has two important caveats:
277
+
278
+ 1. Your `JSON` structure cannot contain an object with only a `"/"` property, as it will be interpreted as a special type.
279
+ 2. Since `JSON` has no technical limit on number sizes, `DAG-JSON` also allows numbers larger than `Number.MAX_SAFE_INTEGER`. JavaScript requires use of `BigInt`s to represent numbers larger than this, and `JSON.parse` does not support them, so precision will be lost.
280
+
281
+ Otherwise this codec follows the same rules as the `JSON` codec.
282
+
283
+ ##### Using the DAG-JSON codec
284
+
285
+ ```typescript
286
+ import * as dagJson from '@ipld/dag-json'
287
+
288
+ const block = new TextEncoder().encode(`{
289
+ "hello": "world",
290
+ "cid": {
291
+ "/": "baeaaac3imvwgy3zao5xxe3de"
292
+ },
293
+ "buf": {
294
+ "/": {
295
+ "bytes": "AAECAwQ"
296
+ }
297
+ }
298
+ }`)
299
+
300
+ const obj = dagJson.decode(block)
301
+
302
+ console.info(obj)
303
+ // {
304
+ // hello: 'world',
305
+ // cid: CID(baeaaac3imvwgy3zao5xxe3de),
306
+ // buf: Uint8Array(5) [ 0, 1, 2, 3, 4 ]
307
+ // }
308
+ ```
309
+
310
+ ##### Content-Type
311
+
312
+ When the `DAG-JSON` codec is encountered in the requested CID, the `Content-Type` header of the response will be set to `application/json`.
313
+
314
+ `DAG-JSON` data can be parsed from the response by using the `.json()` function, which will return `CID`s/byte arrays as plain `{ "/": ... }` objects:
315
+
316
+ ```typescript
317
+ import { verifiedFetch } from '@helia/verified-fetch'
318
+ import * as dagJson from '@ipld/dag-json'
319
+
320
+ const res = await verifiedFetch('ipfs://bafyDAGJSON')
321
+
322
+ // either:
323
+ const obj = await res.json()
324
+ console.info(obj.cid) // { "/": "baeaaac3imvwgy3zao5xxe3de" }
325
+ console.info(obj.buf) // { "/": { "bytes": "AAECAwQ" } }
326
+ ```
327
+
328
+ Alternatively, it can be decoded using the `@ipld/dag-json` module and the `.arrayBuffer()` method, in which case you will get `CID` objects and `Uint8Array`s:
329
+
330
+ ```typescript
331
+ import { verifiedFetch } from '@helia/verified-fetch'
332
+ import * as dagJson from '@ipld/dag-json'
333
+
334
+ const res = await verifiedFetch('ipfs://bafyDAGJSON')
335
+
336
+ // or:
337
+ const obj = dagJson.decode<any>(await res.arrayBuffer())
338
+ console.info(obj.cid) // CID(baeaaac3imvwgy3zao5xxe3de)
339
+ console.info(obj.buf) // Uint8Array(5) [ 0, 1, 2, 3, 4 ]
340
+ ```
341
+
342
+ #### DAG-CBOR
343
+
344
+ [DAG-CBOR](https://ipld.io/docs/codecs/known/dag-cbor/) uses the [Concise Binary Object Representation](https://cbor.io/) format for serialization instead of JSON.
345
+
346
+ This supports more datatypes in a safer way than JSON and is smaller on the wire to boot so is usually preferable to JSON or DAG-JSON.
347
+
348
+ ##### Content-Type
349
+
350
+ Not all data types supported by `DAG-CBOR` can be successfully turned into JSON and back into the same binary form.
351
+
352
+ When a decoded block can be round-tripped to JSON, the `Content-Type` will be set to `application/json`. In this case the `.json()` method on the `Response` object can be used to obtain an object representation of the response.
353
+
354
+ When it cannot, the `Content-Type` will be `application/octet-stream` - in this case the `@ipld/dag-json` module must be used to deserialize the return value from `.arrayBuffer()`.
355
+
356
+ ##### Detecting JSON-safe DAG-CBOR
357
+
358
+ If the `Content-Type` header of the response is `application/json`, the `.json()` method may be used to access the response body in object form, otherwise the `.arrayBuffer()` method must be used to decode the raw bytes using the `@ipld/dag-cbor` module.
359
+
360
+ ```typescript
361
+ import { verifiedFetch } from '@helia/verified-fetch'
362
+ import * as dagCbor from '@ipld/dag-cbor'
363
+
364
+ const res = await verifiedFetch('ipfs://bafyDagCborCID')
365
+ let obj
366
+
367
+ if (res.headers.get('Content-Type') === 'application/json') {
368
+ // DAG-CBOR data can be safely decoded as JSON
369
+ obj = await res.json()
370
+ } else {
371
+ // response contains non-JSON friendly data types
372
+ obj = dagCbor.decode(await res.arrayBuffer())
373
+ }
374
+
375
+ console.info(obj) // ...
376
+ ```
377
+
378
+ ## The `Accept` header
379
+
380
+ The `Accept` header can be passed to override certain response processing, or to ensure that the final `Content-Type` of the response is the one that is expected.
381
+
382
+ If the final `Content-Type` does not match the `Accept` header, or if the content cannot be represented in the format dictated by the `Accept` header, or you have configured a custom content type parser, and that parser returns a value that isn't in the accept header, a [406: Not Acceptable](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/406) response will be returned:
383
+
384
+ ```typescript
385
+ import { verifiedFetch } from '@helia/verified-fetch'
386
+
387
+ const res = await verifiedFetch('ipfs://bafyJPEGImageCID', {
388
+ headers: {
389
+ accept: 'image/png'
390
+ }
391
+ })
392
+
393
+ console.info(res.status) // 406 - the image was a JPEG but we specified PNG as the accept header
394
+ ```
395
+
396
+ It can also be used to skip processing the data from some formats such as `DAG-CBOR` if you wish to handle decoding it yourself:
397
+
398
+ ```typescript
399
+ import { verifiedFetch } from '@helia/verified-fetch'
400
+
401
+ const res = await verifiedFetch('ipfs://bafyDAGCBORCID', {
402
+ headers: {
403
+ accept: 'application/octet-stream'
404
+ }
148
405
  })
406
+
407
+ console.info(res.headers.get('accept')) // application/octet-stream
408
+ const buf = await res.arrayBuffer() // raw bytes, not processed as JSON
149
409
  ```
150
410
 
151
411
  ## Comparison to fetch
@@ -165,7 +425,7 @@ This library supports the following methods of fetching web3 content from IPFS:
165
425
  2. IPNS protocol: `ipns://<peerId>` & `ipns://<publicKey>` & `ipns://<hostUri_Supporting_DnsLink_TxtRecords>`
166
426
  3. CID instances: An actual CID instance `CID.parse('bafy...')`
167
427
 
168
- 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).
428
+ As well as support for pathing & params for items 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).
169
429
 
170
430
  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.
171
431
 
@@ -277,7 +537,7 @@ Loading this module through a script tag will make it's exports available as `He
277
537
 
278
538
  # API Docs
279
539
 
280
- - <https://ipfs.github.io/helia/modules/_helia_verified_fetch.html>
540
+ - <https://ipfs.github.io/helia-verified-fetch/modules/_helia_verified_fetch.html>
281
541
 
282
542
  # License
283
543
 
@@ -288,7 +548,7 @@ Licensed under either of
288
548
 
289
549
  # Contribute
290
550
 
291
- Contributions welcome! Please check out [the issues](https://github.com/ipfs/helia/issues).
551
+ Contributions welcome! Please check out [the issues](https://github.com/ipfs/helia-verified-fetch/issues).
292
552
 
293
553
  Also see our [contributing document](https://github.com/ipfs/community/blob/master/CONTRIBUTING_JS.md) for more information on how we work, and about contributing in general.
294
554