diff --git a/assets/highlight.css b/assets/highlight.css index ef67147e..a3cd9949 100644 --- a/assets/highlight.css +++ b/assets/highlight.css @@ -1,32 +1,32 @@ :root { - --light-hl-0: #AF00DB; - --dark-hl-0: #C586C0; - --light-hl-1: #000000; - --dark-hl-1: #D4D4D4; - --light-hl-2: #001080; - --dark-hl-2: #9CDCFE; - --light-hl-3: #A31515; - --dark-hl-3: #CE9178; - --light-hl-4: #0000FF; - --dark-hl-4: #569CD6; - --light-hl-5: #0070C1; - --dark-hl-5: #4FC1FF; - --light-hl-6: #795E26; - --dark-hl-6: #DCDCAA; - --light-hl-7: #008000; - --dark-hl-7: #6A9955; - --light-hl-8: #267F99; - --dark-hl-8: #4EC9B0; - --light-hl-9: #800000; - --dark-hl-9: #808080; - --light-hl-10: #800000; - --dark-hl-10: #569CD6; - --light-hl-11: #000000FF; - --dark-hl-11: #D4D4D4; - --light-hl-12: #E50000; - --dark-hl-12: #9CDCFE; - --light-hl-13: #0000FF; - --dark-hl-13: #CE9178; + --light-hl-0: #000000; + --dark-hl-0: #D4D4D4; + --light-hl-1: #800000; + --dark-hl-1: #808080; + --light-hl-2: #800000; + --dark-hl-2: #569CD6; + --light-hl-3: #000000FF; + --dark-hl-3: #D4D4D4; + --light-hl-4: #E50000; + --dark-hl-4: #9CDCFE; + --light-hl-5: #0000FF; + --dark-hl-5: #CE9178; + --light-hl-6: #AF00DB; + --dark-hl-6: #C586C0; + --light-hl-7: #001080; + --dark-hl-7: #9CDCFE; + --light-hl-8: #A31515; + --dark-hl-8: #CE9178; + --light-hl-9: #0000FF; + --dark-hl-9: #569CD6; + --light-hl-10: #0070C1; + --dark-hl-10: #4FC1FF; + --light-hl-11: #795E26; + --dark-hl-11: #DCDCAA; + --light-hl-12: #008000; + --dark-hl-12: #6A9955; + --light-hl-13: #267F99; + --dark-hl-13: #4EC9B0; --light-hl-14: #098658; --dark-hl-14: #B5CEA8; --light-code-background: #FFFFFF; diff --git a/assets/navigation.js b/assets/navigation.js index 7e768254..d5998b74 100644 --- a/assets/navigation.js +++ b/assets/navigation.js @@ -1 +1 @@ -window.navigationData = "data:application/octet-stream;base64,H4sIAAAAAAAAA5XSX0/CMBSH4e/Sa3RCBOIuBUx2JTGEG+NF6X5zjbNdTs8IxPjdjcQ/dCsd3G7vnrOd9flDMHYsUjHL5nOw1JUYiFpyKVKhDYMKqeCSv7vXJb9/J2/a5CIdjSefgy6xILIUdw5JFLOGYXi1r7GU5HDCa1dRkiAZa5AuNPIHsCozozkMh9sL+ceatTXu3Ak/eWzIE5xtSCHyr/wkhnnDg5ZXnE2d3OpF+7xvNpsK+ZLsK8G5xRaGj1bJ+xouCUYt9eZuOhyPAktsY7/X+573PiP+fpG0b4rqHpB/vWiMOhyWJJD58uT2CN32cV5wNexQL1/pfXDoMwQAAA==" \ No newline at end of file +window.navigationData = "data:application/octet-stream;base64,H4sIAAAAAAAAA6WU0U6DMBRA/+U+g7rFzciT0c1kTy7G+LIY0pXLaISWlMuUGP/djDA2WGF0hkd6zmlzm65+gPCbwIOHCGPBwAEeiTjQKMFb1T+3qEUoMHBDJB65G0b4xQqXKxkqnTDJERxIGUXgQaKCPMbs2i+F/h71S9SvUP8IvYooicGBTyED8Ma/Tkd2YKKlMx/oaTGbITERH6RCEuqQ8U5vzbQKk+nRlutFc62VvsRegr0JJQklvRUpLpnO0KrSZntDGhnhe2V43gkWUpBNzmywjL6kJJTM/tetJH3pV8xUrjla34wm2JdobMmi0OAGByynZTWnx3y9jjFYarXRmGXzLUo6GhEVaWfHiLZaN/d3o8nYMJxhif3qc9bGkS85S4/gXJufXtJDM8wlLy9sR9cAN3vTW8NDahlpYO7oJPCx+/4AnBAD/UMGAAA=" \ No newline at end of file diff --git a/assets/search.js b/assets/search.js index a9f2e440..6d942839 100644 --- a/assets/search.js +++ b/assets/search.js @@ -1 +1 @@ -window.searchData = "data:application/octet-stream;base64,H4sIAAAAAAAAA61ZXW+rOBD9L84rTfEQyMfj9t6VKl1pr3ar+4KiFQWnQUsA2U673Sj/fWU+wpjYhKR5qlrOnBnP8YzH7oHw4kOQVXgg/6R5QlbBzCF5tGNkRWLOIsl+MZ5uUpb8zmS8JQ7Z84ysyGafxzItcvFoQE23cpcRh8RZJAQTZEXI0WkdgLucUx9OXv5kotjzmJ2o5WfJxGP752EuPzjj+cZklGYntjSXjG+iGFHWiEFi6kKXB96PcJhzgvCI3CFlxFkuz0M1r+fp+Zt9KaeP41cRp8llpkmNMofdRWRxUUZyO8JHAxvvxJiW75wXfNBbhRifIHYF4aQFX1hEHeSNiiB3fVmkSB5S8ZDmW8ZTyZLrnV/UCnk/E+wm91hFc1NBYVzTT2aLE6+QEZfj+CYt1iyhHqHVXVGO9lZBr3SGN/55n33OU+NiLdDxpfAWSfYRfYprySfI0FIZllXYWm+xl4xfH0dnd5cwklyonp293xJLz/guAW0jsb0lls7uLmFEWVZ8/CjiyHxIDUWimd4vmOdcsHjPjWf15XiQ9V1CytLXEsqnIt+kb1dH1DO+NaALPeSPshrjRkbXoK+YOopcsly+fJbsZ8QFMx+ww44mJpLR6WgXaAlQMCHSIn+K4i37K/1v7MbR4jNw3Dm8l5cfu1s0mvTsvxBWf27/bf/6mrHkJy/eOBPi+zvLpegN8UbMVbcDLahBXwPI0XeIUafrF87VRo3xrJPOYsTkcHurvr1J3689f6kxj+6Ao/pRHzSoMLoxv1+4K2vfH+itc+0w4YXBVo9xzGB70d3AZNvztnZImifsX7I6qE/V1l4RmHrTJXHIJmVZoh4j6jAcEhe7neJZN99+sVgWXCFqyKNLnNB1PJi6vr9eO2FrUX2o/lDBKHFC6kAwXc4CDUY1GBAnBBMbaDDPxuZpsBlxQs/ENtNgPnHCmYnN12ABcULfBAs02Jw4YWByOtdgC+KEcxNsocGWttiWenpdW3C0p4PK98II1JWgKuNLI1DXglZiuEakLgdVaafUtGiqK0JV5qlxI1BdFKqST40iU10XqvJPZ0akLg1VElDfiNTVoUoFGhjXrgsESgY6NyFBVwiqUlkYi6BXLEoIujQidY1ACQFGjUDXCJQQYNQIdI1ACQHmYtU1AiUEGDUCXSNQQoBRI9A1AiUEGDUCXSNQQoCxIkHXyHOtanq6Rh61qunpGnlgzbzX62merTI9XSJvZqtMT1fI862V6dUKVYfBO+OSJc/1oRCG9ZiQno77A/m7OTDovD2dDgRcsjocHeJR9fPYHRTqN+WpYsnqwQVRBB0FXTYUroXitZ5dy2aSZM3M2bGBhwIKLCzVw11nM+tM/Nr/0m6YNM+/nTnyOLtk17xQdsZo8XObcT34qIG6bKYjtF4Xrddrsgc2pupK0Z7+m3oe6rgQlS3/Boa0msiRnhTpaU3IOU/R3nkR1RItzraoJBe8e8lBxkhWasvtmR5oPy8sNt1zGnIGyJlvMTy98yA7H9nZHNZvDnHz5oCMFyg9tqKrn4k7I+QwqLcLtYnd/csE+UTxNrvtgvV5waBc2UQ9PRUiz6jOqK2yTzcz5A2VGNgKu7GL1WOBqB4LEAFaM9g2dEMgZbbT+xFerG1jNHeDzgrtewpNmq2eq0kf5QmVMW07gs2ztRegrUVboW1KD7YDQBsObDtcYxho7qikwVjSa4eUacmyNGdkFa6Px/8BC3ZXmksdAAA="; \ No newline at end of file +window.searchData = "data:application/octet-stream;base64,H4sIAAAAAAAAA81aXW/bNhT9L/Qr7ZiXtvzxNCztgAAFVnRBXwTDUCQ6FiZLhiQny4L894ESZfLapGNb8ranpuk9h0fnXJEU2XeSZ68Fmfvv5M84jcgcKEmDjSBz8staJHFw9yLyeBWLqL8SZbjuPweleA3e+mGWrrJ8E6ShIJTs8oTMySaLdoko7pYVctkglxVyqZBLAzlYl5uEUBImQVGIgswJ+aBnKjlv1NMjjL39GPcPX76IMoiTPW+cliJfBaGTeg+xDELJNshFWjrVaxVsCKO9jDCOrhXQq7EXiNAELjnboFxfrUeB2wqypvQ1z7P8CmUV7j/PS6s4Cq0son5c9ON0LfK4FNEFntWeOISK1ob1GoqrAj0p7so2M7Qd9VqHPqIGzNJSpOXj21Z8D/JCXGLpIbRdGyJVuQhK8VOV/iYrH9K4vECbnaDDFyVIkuz1IS1EuMtFN8J6h5wXNabDslPyv2VhcMn68Kn2hvCGwqO0+CGKLHkRedGR9APKG4pXW4auhBt0NxS9Dop1d2ZrthtKTuKnLWzvs3QVP3ek+4DyhuLzbFd257dm61byJ9P179syztJ2D6E4utzdtFjtTuvr2ahbOt546HiYQhRFnKX3QbgWf8R/t1uE0LNYmP+VR3l8/LbprmV6B6ydP4L5CsgFZJeH4tJvLozrsNVzRdxKSs9gucS+AzfsliF3z5eJYC23nMPRVPdgGeQX7DCPZfQahkucwiY4pWXblsoqgk6EuRK8bIP+P9ya32BTftPteNcb8bPFqnm1tVLN05VMGM4mbKwP2n7dPT0lIvqeZ8+5KIqvLyIt9QJTvm2dkq3ItrMNFvfjcIY+pacp7lYC8vIKl07g2wn1jD3b8VK817bapWG1Kjv0WbCd6Xq5ShFC9dnN1q9rdFy1gGEbzlnArpR28Qp2oGxBSZxG4i8yf5fZVTPPnMCAD2aEklUskkjeG9SSKQmzzUayL9S//RRhmeWyoi65GxLqDynjA/A4Zc0PQNl4MIEZ5eqHxYL6DVmFqX5RMbCKAYYDj08pUz+geobqgVB/RDkfzIaAygCVcUL9MYXpYDz1UBlHZSNCfc9WNkJlY0L9iW3QMSrzXIN6qGxCqD+1sU1Q2dSlbYrKZoT6M1vZDPssbWdD27DsIBFpOGM2SoazYNJzBtZKHAeTtjNuHR0nwqTzzJoww6EwaT4bWytxLkz6zzxrJY6GyQiYNWqG02EyBWaNkeGAmDMhhiOCKqKZtblxRCBzAGuYcPC6yByAWStxRCBzAGuYgCMCmQNwayWOCGQOMLJW4ohA5gDWlwdwRCBzAGuYgCOCqbORAUcEM2cjA86IyyDA2iAcZ8SrjKwNwnFGHJzO84NZrcrI2iEcZ8RlENzaIRxnxMfONDnOiHvONDnOiE+cafI6o2ohehF5KaKHekHy/foDIN5/ZbyTpVqsGGtW0XfCGJm/f1ACU/nnh16k5N/kSBVLUu/9DQowKEBRzBwUT/XGd6s2c0JtBjUbTDUbZw6W6hZQY8YGpB7fcwMjdYSi4SMNh89w6lJPgycaPHaBzbt/jeQaOXQj5amf3CNv1amfxs80flY/NXO5Xm9Umx2L+v8AhpKhYeDofI64+iY3OsHgYc5nOubJmtNcg8poA+bqxygtcn2zYoANaxl3gI+SNEacODBHzrGDDClxtay6TEGt/nkD6CsYY0yjX5krrf09iIEzXhPm6lW81TXhw7Mftb7LCNVdhiHAMwS43tD6ZlqDDMyoHtbVDfow0bDY8BjU3MBdL3lDcDxDgJEzOOHNVYjxxMbswFxNtT+nMMYzcNzVGwoXymP0ojpGNwY2Jgf4hKAskw2ego2owRWy+pgzUOY0OlZWu1Kuv7cMsNGb4CmwyzDnPAbGew+qW7ir00/OZGC0HZyl48SKZmTBrbPRgpJtvBVJnAoy9xcfH/8A6hlPzGcmAAA="; \ No newline at end of file diff --git a/functions/_helia_verified_fetch.createVerifiedFetch.html b/functions/_helia_verified_fetch.createVerifiedFetch.html new file mode 100644 index 00000000..69032174 --- /dev/null +++ b/functions/_helia_verified_fetch.createVerifiedFetch.html @@ -0,0 +1,2 @@ +createVerifiedFetch | Helia Verified Fetch
\ No newline at end of file diff --git a/functions/verifiedFetch-1.html b/functions/_helia_verified_fetch.verifiedFetch-1.html similarity index 52% rename from functions/verifiedFetch-1.html rename to functions/_helia_verified_fetch.verifiedFetch-1.html index e44c210b..7e566288 100644 --- a/functions/verifiedFetch-1.html +++ b/functions/_helia_verified_fetch.verifiedFetch-1.html @@ -1,3 +1,3 @@ -verifiedFetch | @helia/verified-fetch

Methods

Methods

\ No newline at end of file +verifiedFetch | Helia Verified Fetch

Methods

Methods

\ No newline at end of file diff --git a/functions/createVerifiedFetch.html b/functions/createVerifiedFetch.html deleted file mode 100644 index e15032f5..00000000 --- a/functions/createVerifiedFetch.html +++ /dev/null @@ -1,2 +0,0 @@ -createVerifiedFetch | @helia/verified-fetch

Function createVerifiedFetch

\ No newline at end of file diff --git a/hierarchy.html b/hierarchy.html index 52cc950f..ae18bb5c 100644 --- a/hierarchy.html +++ b/hierarchy.html @@ -1 +1 @@ -@helia/verified-fetch

@helia/verified-fetch

Class Hierarchy

\ No newline at end of file +Helia Verified Fetch

Helia Verified Fetch

Class Hierarchy

\ No newline at end of file diff --git a/index.html b/index.html index 44cc5b91..25d5fb2f 100644 --- a/index.html +++ b/index.html @@ -1,249 +1,22 @@ -@helia/verified-fetch

@helia/verified-fetch

+Helia Verified Fetch

Helia Verified Fetch

Helia logo

-

@helia/verified-fetch

ipfs.tech +

helia-verified-fetch

ipfs.tech Discuss codecov CI

-
-

A fetch-like API for obtaining verified & trustless IPFS content on the web

-
-

About

- -

@helia/verified-fetch provides a fetch-like API for retrieving content from the IPFS network.

-

All content is retrieved in a trustless manner, and the integrity of all bytes are verified by comparing hashes of the data.

-

By default, providers for CIDs are found using delegated routing endpoints.

-

Data is retrieved using the following strategies:

-
    -
  • Directly from providers, using Bitswap over WebSockets and WebRTC if available.
  • -
  • Directly from providers exposing a trustless gateway over HTTPS.
  • -
  • As a fallback, if no providers reachable from a browser are found, data is retrieved using recursive gateways, e.g. trustless-gateway.link which can be configured.
  • -
-

This is a marked improvement over fetch which offers no such protections and is vulnerable to all sorts of attacks like Content Spoofing, DNS Hijacking, etc.

-

A verifiedFetch function is exported to get up and running quickly, and a createVerifiedFetch function is also available that allows customizing the underlying Helia node for complete control over how content is retrieved.

-

Browser-cache-friendly Response objects are returned which should be instantly familiar to web developers.

+

About

This monorepo contains the @helia/verified-fetch package and its corresponding interop tests.

+

Getting started

See the @helia/verified-fetch package for how to get started with the package including usage examples.

Learn more in the announcement blog post and check out the ready-to-run example.

-

You may use any supported resource argument to fetch content:

-
    -
  • CID instance
  • -
  • IPFS URL
  • -
  • IPNS URL
  • -
-

Example - Getting started

import { verifiedFetch } from '@helia/verified-fetch'

const resp = await verifiedFetch('ipfs://bafy...')

const json = await resp.json() -
-

Example - Using a CID instance to fetch JSON

import { verifiedFetch } from '@helia/verified-fetch'
import { CID } from 'multiformats/cid'

const cid = CID.parse('bafyFoo') // some json file
const response = await verifiedFetch(cid)
const json = await response.json() -
-

Example - Using IPFS protocol to fetch an image

import { verifiedFetch } from '@helia/verified-fetch'

const response = await verifiedFetch('ipfs://bafyFoo') // CID for some image file
const blob = await response.blob()
const image = document.createElement('img')
image.src = URL.createObjectURL(blob)
document.body.appendChild(image) -
-

Example - Using IPNS protocol to stream a big file

import { verifiedFetch } from '@helia/verified-fetch'

const response = await verifiedFetch('ipns://mydomain.com/path/to/very-long-file.log')
const bigFileStreamReader = await response.body?.getReader() -
-

Configuration

Custom HTTP gateways and routers

Out of the box @helia/verified-fetch uses a default set of trustless gateways for fetching blocks and HTTP delegated routers for performing routing tasks - looking up peers, resolving/publishing IPNS names, etc.

-

It's possible to override these by passing gateways and routers keys to the createVerifiedFetch function:

-

Example - Configuring gateways and routers

import { createVerifiedFetch } from '@helia/verified-fetch'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev']
})

const resp = await fetch('ipfs://bafy...')

const json = await resp.json() -
-

Usage with customized Helia

For full control of how @helia/verified-fetch fetches content from the distributed web you can pass a preconfigured Helia node to createVerifiedFetch.

-

The helia module is configured with a libp2p node that is suited for decentralized applications, alternatively @helia/http is available which uses HTTP gateways for all network operations.

-

You can see variations of Helia and js-libp2p configuration options at https://ipfs.github.io/helia/interfaces/helia.HeliaInit.html.

-
import { trustlessGateway } from '@helia/block-brokers'
import { createHeliaHTTP } from '@helia/http'
import { delegatedHTTPRouting, httpGatewayRouting } from '@helia/routers'
import { createVerifiedFetch } from '@helia/verified-fetch'

const fetch = await createVerifiedFetch(
await createHeliaHTTP({
blockBrokers: [
trustlessGateway()
],
routers: [
delegatedHTTPRouting('http://delegated-ipfs.dev'),
httpGatewayRouting({
gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
})
]
})
)

const resp = await fetch('ipfs://bafy...')

const json = await resp.json() -
-

Custom content-type parsing

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.

-

If you require an accurate content-type you can provide a contentTypeParser function as an option to createVerifiedFetch to handle parsing the content type.

-

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.

-

Example - Customizing content-type parsing

import { createVerifiedFetch } from '@helia/verified-fetch'
import { fileTypeFromBuffer } from '@sgtpooki/file-type'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev']
}, {
contentTypeParser: async (bytes) => {
// call to some magic-byte recognition library like magic-bytes, file-type, or your own custom byte recognition
const result = await fileTypeFromBuffer(bytes)
return result?.mime
}
}) -
-

Custom DNS resolvers

If you don't want to leak DNS queries to the default resolvers, you can provide your own list of DNS resolvers to createVerifiedFetch.

-

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.

-

Example - Customizing DNS resolvers

import { createVerifiedFetch } from '@helia/verified-fetch'
import { dnsJsonOverHttps, dnsOverHttps } from '@multiformats/dns/resolvers'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev'],
dnsResolvers: [
dnsJsonOverHttps('https://my-dns-resolver.example.com/dns-json'),
dnsOverHttps('https://my-dns-resolver.example.com/dns-query')
]
}) -
-

Example - Customizing DNS per-TLD resolvers

DNS resolvers can be configured to only service DNS queries for specific -TLDs:

-
import { createVerifiedFetch } from '@helia/verified-fetch'
import { dnsJsonOverHttps, dnsOverHttps } from '@multiformats/dns/resolvers'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev'],
dnsResolvers: {
// this resolver will only be used for `.com` domains (note - this could
// also be an array of resolvers)
'com.': dnsJsonOverHttps('https://my-dns-resolver.example.com/dns-json'),
// this resolver will be used for everything else (note - this could
// also be an array of resolvers)
'.': dnsOverHttps('https://my-dns-resolver.example.com/dns-query')
}
}) -
-

Custom Hashers

By default, @helia/verified-fetch supports sha256, sha512, and identity hashers.

-

If you need to use a different hasher, you can provide a custom hasher function as an option to createVerifiedFetch.

-

Example - Passing a custom hashing function

import { createVerifiedFetch } from '@helia/verified-fetch'
import { blake2b256 } from '@multiformats/blake2/blake2b'

const verifiedFetch = await createVerifiedFetch({
gateways: ['https://ipfs.io'],
hashers: [blake2b256]
})

const resp = await verifiedFetch('ipfs://cid-using-blake2b256') -
-

IPLD codec handling

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.

-

DAG-PB

DAG-PB is the codec we are most likely to encounter, it is what UnixFS uses under the hood.

-
Using the DAG-PB codec as a Blob
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const blob = await res.blob()

console.info(blob) // Blob { size: x, type: 'application/octet-stream' } -
-
Using the DAG-PB codec as an ArrayBuffer
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const buf = await res.arrayBuffer()

console.info(buf) // ArrayBuffer { [Uint8Contents]: < ... >, byteLength: x } -
-
Using the DAG-PB codec as a stream
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const reader = res.body?.getReader()

if (reader == null) {
throw new Error('Could not create reader from response body')
}

while (true) {
const next = await reader.read()

if (next?.done === true) {
break
}

if (next?.value != null) {
console.info(next.value) // Uint8Array(x) [ ... ]
}
} -
-
Content-Type

When fetching DAG-PB data, the content type will be set to application/octet-stream unless a custom content-type parser is configured.

-

JSON

The JSON codec is a very simple codec, a block parseable with this codec is a JSON string encoded into a Uint8Array.

-
Using the JSON codec
import * as json from 'multiformats/codecs/json'

const block = new TextEncoder().encode('{ "hello": "world" }')
const obj = json.decode(block)

console.info(obj) // { hello: 'world' } -
-
Content-Type

When the JSON codec is encountered, the Content-Type header of the response will be set to application/json.

-

DAG-JSON

DAG-JSON expands on the JSON codec, adding the ability to contain CIDs which act as links to other blocks, and byte arrays.

-

CIDs and byte arrays are represented using special object structures with a single "/" property.

-

Using DAG-JSON has two important caveats:

-
    -
  1. Your JSON structure cannot contain an object with only a "/" property, as it will be interpreted as a special type.
  2. -
  3. Since JSON has no technical limit on number sizes, DAG-JSON also allows numbers larger than Number.MAX_SAFE_INTEGER. JavaScript requires use of BigInts to represent numbers larger than this, and JSON.parse does not support them, so precision will be lost.
  4. -
-

Otherwise this codec follows the same rules as the JSON codec.

-
Using the DAG-JSON codec
import * as dagJson from '@ipld/dag-json'

const block = new TextEncoder().encode(`{
"hello": "world",
"cid": {
"/": "baeaaac3imvwgy3zao5xxe3de"
},
"buf": {
"/": {
"bytes": "AAECAwQ"
}
}
}`)

const obj = dagJson.decode(block)

console.info(obj)
// {
// hello: 'world',
// cid: CID(baeaaac3imvwgy3zao5xxe3de),
// buf: Uint8Array(5) [ 0, 1, 2, 3, 4 ]
// } -
-
Content-Type

When the DAG-JSON codec is encountered in the requested CID, the Content-Type header of the response will be set to application/json.

-

DAG-JSON data can be parsed from the response by using the .json() function, which will return CIDs/byte arrays as plain { "/": ... } objects:

-
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagJson from '@ipld/dag-json'

const res = await verifiedFetch('ipfs://bafyDAGJSON')

// either:
const obj = await res.json()
console.info(obj.cid) // { "/": "baeaaac3imvwgy3zao5xxe3de" }
console.info(obj.buf) // { "/": { "bytes": "AAECAwQ" } } -
-

Alternatively, it can be decoded using the @ipld/dag-json module and the .arrayBuffer() method, in which case you will get CID objects and Uint8Arrays:

-
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagJson from '@ipld/dag-json'

const res = await verifiedFetch('ipfs://bafyDAGJSON')

// or:
const obj = dagJson.decode<any>(await res.arrayBuffer())
console.info(obj.cid) // CID(baeaaac3imvwgy3zao5xxe3de)
console.info(obj.buf) // Uint8Array(5) [ 0, 1, 2, 3, 4 ] -
-

DAG-CBOR

DAG-CBOR uses the Concise Binary Object Representation format for serialization instead of JSON.

-

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.

-
Content-Type

Not all data types supported by DAG-CBOR can be successfully turned into JSON and back into the same binary form.

-

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.

-

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().

-
Detecting JSON-safe DAG-CBOR

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.

-
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagCbor from '@ipld/dag-cbor'

const res = await verifiedFetch('ipfs://bafyDagCborCID')
let obj

if (res.headers.get('Content-Type') === 'application/json') {
// DAG-CBOR data can be safely decoded as JSON
obj = await res.json()
} else {
// response contains non-JSON friendly data types
obj = dagCbor.decode(await res.arrayBuffer())
}

console.info(obj) // ... -
-

The Accept header

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.

-

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 response will be returned:

-
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyJPEGImageCID', {
headers: {
accept: 'image/png'
}
})

console.info(res.status) // 406 - the image was a JPEG but we specified PNG as the accept header -
-

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:

-
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyDAGCBORCID', {
headers: {
accept: 'application/octet-stream'
}
})

console.info(res.headers.get('accept')) // application/octet-stream
const buf = await res.arrayBuffer() // raw bytes, not processed as JSON -
-

Redirects

If a requested URL contains a path component, that path component resolves to -a UnixFS directory, but the URL does not have a trailing slash, one will be -added to form a canonical URL for that resource, otherwise the request will -be resolved as normal.

-
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir')

console.info(res.url) // ipfs://bafyfoo/path/to/dir/ -
-

It's possible to prevent this behaviour and/or handle a redirect manually -through use of the redirect -option.

-

Example - Redirect: follow

This is the default value and is what happens if no value is specified.

-
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'follow'
})

console.info(res.status) // 200
console.info(res.url) // ipfs://bafyfoo/path/to/dir/
console.info(res.redirected) // true -
-

Example - Redirect: error

This causes a TypeError to be thrown if a URL would cause a redirect.

-

import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'error'
})
// throw TypeError('Failed to fetch') -
-

Example - Redirect: manual

Manual redirects allow the user to process the redirect. A 301 -is returned, and the location to redirect to is available as the "location" -response header.

-

This differs slightly from HTTP fetch which returns an opaque response as the -browser itself is expected to process the redirect and hide all details from -the user.

-

import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'manual'
})

console.info(res.status) // 301
console.info(res.url) // ipfs://bafyfoo/path/to/dir
console.info(res.redirected) // false
console.info(res.headers.get('location')) // ipfs://bafyfoo/path/to/dir/ -
-

Comparison to fetch

This module attempts to act as similarly to the fetch() API as possible.

-

The fetch() API takes two parameters:

-
    -
  1. A resource
  2. -
  3. An options object
  4. -
-

Resource argument

This library supports the following methods of fetching web3 content from IPFS:

-
    -
  1. IPFS protocol: ipfs://<cidv0> & ipfs://<cidv1>
  2. -
  3. IPNS protocol: ipns://<peerId> & ipns://<publicKey> & ipns://<hostUri_Supporting_DnsLink_TxtRecords>
  4. -
  5. CID instances: An actual CID instance CID.parse('bafy...')
  6. -
-

As well as support for pathing & params for items 1 & 2 above according to IPFS - Path Gateway Specification & IPFS - Trustless Gateway Specification. Further refinement of those specifications specifically for web-based scenarios can be found in the Web Pathing Specification IPIP.

-

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.

-

Options argument

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 related to specifying the resultant shape of desired content.

-

Some of those header specifications are:

-
    -
  1. https://specs.ipfs.tech/http-gateways/path-gateway/#request-headers
  2. -
  3. https://specs.ipfs.tech/http-gateways/trustless-gateway/#request-headers
  4. -
  5. https://specs.ipfs.tech/http-gateways/subdomain-gateway/#request-headers
  6. -
-

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.

-

Known Fetch API options that will be supported:

-
    -
  1. signal - An AbortSignal that a user can use to abort the request.
  2. -
  3. 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 parameter.
  4. -
  5. headers - An object of headers to be sent with the request. Best effort to adhere to the Fetch API headers parameter. -
  6. -
  7. 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 parameter.
  8. -
  9. body - An object that specifies the body of the request. Best effort to adhere to the Fetch API body parameter.
  10. -
  11. cache - Will basically act as force-cache for the request. Best effort to adhere to the Fetch API cache parameter.
  12. -
-

Non-Fetch API options that will be supported:

-
    -
  1. onProgress - Similar to Helia onProgress options, this will be a function that will be called with a progress event. Supported progress events are:
      -
    • helia:verified-fetch:error - An error occurred during the request.
    • -
    • helia:verified-fetch:request:start - The request has been sent
    • -
    • helia:verified-fetch:request:complete - The request has been sent
    • -
    • helia:verified-fetch:request:error - An error occurred during the request.
    • -
    • helia:verified-fetch:request:abort - The request was aborted prior to completion.
    • -
    • helia:verified-fetch:response:start - The initial HTTP Response headers have been set, and response stream is started.
    • -
    • helia:verified-fetch:response:complete - The response stream has completed.
    • -
    • helia:verified-fetch:response:error - An error occurred while building the response.
    • -
    -
  2. -
-

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:

-
    -
  1. IPIP-0412: Signaling Block Order in CARs on HTTP Gateways
  2. -
  3. IPIP-0402: Partial CAR Support on Trustless Gateways
  4. -
  5. IPIP-0386: Subdomain Gateway Interop with _redirects
  6. -
  7. IPIP-0328: JSON and CBOR Response Formats on HTTP Gateways
  8. -
  9. IPIP-0288: TAR Response Format on HTTP Gateways
  10. -
-

Response types

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.

-

All content we retrieve from the IPFS network is obtained via an AsyncIterable, and will be set as the body of the HTTP Response via a ReadableStream 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.

-

If your content doesn't have a mime-type or an IPFS spec, this library will not support it, but you can use the helia library directly for those use cases. See Unsupported response types for more information.

-

Handling response types

For handling responses we want to follow conventions/abstractions from Fetch API where possible:

-
    -
  • 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.
  • -
  • For images (or other web-relevant asset) you want to add to the DOM, use .blob() or .arrayBuffer() to get the raw bytes.
  • -
  • For plain text in utf-8, you would call .text()
  • -
  • For streaming response data, use something like response.body.getReader() to get a ReadableStream.
  • -
-

Unsupported response types

    -
  • 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. Instead, users should request aplication/vnd.ipld.car or use the helia library directly for this use case.
  • -
  • Others? Open an issue or PR!
  • -
-

Response headers

This library will set the HTTP Response headers to the appropriate values for the content type according to the appropriate IPFS Specifications.

-

Some known header specifications:

-
\ No newline at end of file +
\ No newline at end of file diff --git a/interfaces/CIDDetail.html b/interfaces/CIDDetail.html deleted file mode 100644 index 60eba9c4..00000000 --- a/interfaces/CIDDetail.html +++ /dev/null @@ -1,3 +0,0 @@ -CIDDetail | @helia/verified-fetch
interface CIDDetail {
    cid: CID<unknown, number, number, Version>;
    path: string;
}

Hierarchy (view full)

Properties

Properties

cid: CID<unknown, number, number, Version>
path: string
\ No newline at end of file diff --git a/interfaces/CIDDetailError.html b/interfaces/CIDDetailError.html deleted file mode 100644 index 25dca14e..00000000 --- a/interfaces/CIDDetailError.html +++ /dev/null @@ -1,4 +0,0 @@ -CIDDetailError | @helia/verified-fetch

Interface CIDDetailError

interface CIDDetailError {
    cid: CID<unknown, number, number, Version>;
    error: Error;
    path: string;
}

Hierarchy (view full)

Properties

Properties

cid: CID<unknown, number, number, Version>
error: Error
path: string
\ No newline at end of file diff --git a/interfaces/ResourceDetail.html b/interfaces/ResourceDetail.html deleted file mode 100644 index 8de80d6a..00000000 --- a/interfaces/ResourceDetail.html +++ /dev/null @@ -1,2 +0,0 @@ -ResourceDetail | @helia/verified-fetch

Interface ResourceDetail

interface ResourceDetail {
    resource: Resource;
}

Properties

Properties

resource: Resource
\ No newline at end of file diff --git a/interfaces/VerifiedFetch.html b/interfaces/VerifiedFetch.html deleted file mode 100644 index 0487a289..00000000 --- a/interfaces/VerifiedFetch.html +++ /dev/null @@ -1,3 +0,0 @@ -VerifiedFetch | @helia/verified-fetch

Interface VerifiedFetch

interface VerifiedFetch {
    start(): Promise<void>;
    stop(): Promise<void>;
    (resource, options?): Promise<Response>;
}

Methods

Methods

\ No newline at end of file diff --git a/interfaces/_helia_verified_fetch.CIDDetail.html b/interfaces/_helia_verified_fetch.CIDDetail.html new file mode 100644 index 00000000..19b6773f --- /dev/null +++ b/interfaces/_helia_verified_fetch.CIDDetail.html @@ -0,0 +1,3 @@ +CIDDetail | Helia Verified Fetch
interface CIDDetail {
    cid: CID<unknown, number, number, Version>;
    path: string;
}

Hierarchy (view full)

Properties

Properties

cid: CID<unknown, number, number, Version>
path: string
\ No newline at end of file diff --git a/interfaces/_helia_verified_fetch.CIDDetailError.html b/interfaces/_helia_verified_fetch.CIDDetailError.html new file mode 100644 index 00000000..4c12a89b --- /dev/null +++ b/interfaces/_helia_verified_fetch.CIDDetailError.html @@ -0,0 +1,4 @@ +CIDDetailError | Helia Verified Fetch
interface CIDDetailError {
    cid: CID<unknown, number, number, Version>;
    error: Error;
    path: string;
}

Hierarchy (view full)

Properties

Properties

cid: CID<unknown, number, number, Version>
error: Error
path: string
\ No newline at end of file diff --git a/interfaces/ContentTypeParser.html b/interfaces/_helia_verified_fetch.ContentTypeParser.html similarity index 71% rename from interfaces/ContentTypeParser.html rename to interfaces/_helia_verified_fetch.ContentTypeParser.html index 8ca44b09..5d95d3de 100644 --- a/interfaces/ContentTypeParser.html +++ b/interfaces/_helia_verified_fetch.ContentTypeParser.html @@ -1,7 +1,7 @@ -ContentTypeParser | @helia/verified-fetch

Interface ContentTypeParser

A ContentTypeParser attempts to return the mime type of a given file. It +ContentTypeParser | Helia Verified Fetch

A ContentTypeParser attempts to return the mime type of a given file. It receives the first chunk of the file data and the file name, if it is available. The function can be sync or async and if it returns/resolves to undefined, application/octet-stream will be used.

interface ContentTypeParser ((bytes, fileName?) => undefined | string | Promise<undefined | string>)
  • Attempt to determine a mime type, either via of the passed bytes or the filename if it is available.

    -

    Parameters

    Returns undefined | string | Promise<undefined | string>

\ No newline at end of file +

Parameters

Returns undefined | string | Promise<undefined | string>

\ No newline at end of file diff --git a/interfaces/CreateVerifiedFetchInit.html b/interfaces/_helia_verified_fetch.CreateVerifiedFetchInit.html similarity index 54% rename from interfaces/CreateVerifiedFetchInit.html rename to interfaces/_helia_verified_fetch.CreateVerifiedFetchInit.html index 6dcdfc38..49eb5761 100644 --- a/interfaces/CreateVerifiedFetchInit.html +++ b/interfaces/_helia_verified_fetch.CreateVerifiedFetchInit.html @@ -1,40 +1,40 @@ -CreateVerifiedFetchInit | @helia/verified-fetch

Interface CreateVerifiedFetchInit

Instead of passing a Helia instance, you can pass a list of gateways and +CreateVerifiedFetchInit | Helia Verified Fetch

Instead of passing a Helia instance, you can pass a list of gateways and routers, and a HeliaHTTP instance will be created for you.

-
interface CreateVerifiedFetchInit {
    allowInsecure?: boolean;
    allowLocal?: boolean;
    dnsResolvers?: DNSResolver[] | DNSResolvers;
    gateways: string[];
    hashers?: MultihashHasher<number>[];
    libp2pConfig?: Partial<Libp2pOptions<ServiceMap>>;
    routers?: string[];
}

Properties

interface CreateVerifiedFetchInit {
    allowInsecure?: boolean;
    allowLocal?: boolean;
    dnsResolvers?: DNSResolver[] | DNSResolvers;
    gateways: string[];
    hashers?: MultihashHasher<number>[];
    libp2pConfig?: Partial<Libp2pOptions<ServiceMap>>;
    routers?: string[];
}

Properties

allowInsecure?: boolean

By default we will not connect to any gateways over HTTP addresses, requring HTTPS connections instead. This is because it will cause "mixed-content" errors to appear in the console when running in secure browser contexts.

Pass true here to connect to insecure Gateways as well, this may be useful in testing environments.

-

Default

false
+

Default

false
 
allowLocal?: boolean

By default we will not connect to any HTTP Gateways providers over local or loopback addresses, this is because they are typically running on remote peers that have published private addresses by mistate.

Pass true here to connect to local Gateways as well, this may be useful in testing environments.

-

Default

false
+

Default

false
 
-
dnsResolvers?: DNSResolver[] | DNSResolvers

In order to parse DNSLink records, we need to resolve DNS queries. You can +

dnsResolvers?: DNSResolver[] | DNSResolvers

In order to parse DNSLink records, we need to resolve DNS queries. You can pass a list of DNS resolvers that we will provide to the @helia/ipns instance for you. You must construct them using the dnsJsonOverHttps or dnsOverHttps functions exported from @helia/ipns/dns-resolvers.

We use cloudflare and google's dnsJsonOverHttps resolvers by default.

-

Default

[dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),dnsJsonOverHttps('https://dns.google/resolve')]
+

Default

[dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),dnsJsonOverHttps('https://dns.google/resolve')]
 
-
gateways: string[]
hashers?: MultihashHasher<number>[]

By default sha256, sha512 and identity hashes are supported for +

gateways: string[]
hashers?: MultihashHasher<number>[]

By default sha256, sha512 and identity hashes are supported for retrieval operations. To retrieve blocks by CIDs using other hashes pass appropriate MultihashHashers here.

-

We will instantiate a libp2p node for you, but if you want to override the libp2p configuration, +

We will instantiate a libp2p node for you, but if you want to override the libp2p configuration, you can pass it here.

WARNING: We use Object.assign to merge the default libp2p configuration from Helia with the one you pass here, which results in a shallow merge. If you need a deep merge, you should do it yourself before passing the configuration here.

-
routers?: string[]
\ No newline at end of file +
routers?: string[]
\ No newline at end of file diff --git a/interfaces/CreateVerifiedFetchOptions.html b/interfaces/_helia_verified_fetch.CreateVerifiedFetchOptions.html similarity index 55% rename from interfaces/CreateVerifiedFetchOptions.html rename to interfaces/_helia_verified_fetch.CreateVerifiedFetchOptions.html index bc580b61..52053f4c 100644 --- a/interfaces/CreateVerifiedFetchOptions.html +++ b/interfaces/_helia_verified_fetch.CreateVerifiedFetchOptions.html @@ -1,11 +1,11 @@ -CreateVerifiedFetchOptions | @helia/verified-fetch

Interface CreateVerifiedFetchOptions

interface CreateVerifiedFetchOptions {
    contentTypeParser?: ContentTypeParser;
    sessionCacheSize?: number;
    sessionTTLms?: number;
}

Properties

contentTypeParser?: ContentTypeParser

A function to handle parsing content type from bytes. The function you +CreateVerifiedFetchOptions | Helia Verified Fetch

interface CreateVerifiedFetchOptions {
    contentTypeParser?: ContentTypeParser;
    sessionCacheSize?: number;
    sessionTTLms?: number;
}

Properties

contentTypeParser?: ContentTypeParser

A function to handle parsing content type from bytes. The function you provide will be passed the first set of bytes we receive from the network, and should return a string that will be used as the value for the Content-Type header in the response.

-

Default

undefined
+

Default

undefined
 
sessionCacheSize?: number

Blockstore sessions are cached for reuse with requests with the same base URL or CID. This parameter controls how many to cache. Once this limit @@ -15,4 +15,4 @@

sessionTTLms?: number

How long each blockstore session should stay in the cache for.

Default

60000
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/interfaces/_helia_verified_fetch.ResourceDetail.html b/interfaces/_helia_verified_fetch.ResourceDetail.html new file mode 100644 index 00000000..ab65c941 --- /dev/null +++ b/interfaces/_helia_verified_fetch.ResourceDetail.html @@ -0,0 +1,2 @@ +ResourceDetail | Helia Verified Fetch
interface ResourceDetail {
    resource: Resource;
}

Properties

Properties

resource: Resource
\ No newline at end of file diff --git a/interfaces/_helia_verified_fetch.VerifiedFetch.html b/interfaces/_helia_verified_fetch.VerifiedFetch.html new file mode 100644 index 00000000..09342161 --- /dev/null +++ b/interfaces/_helia_verified_fetch.VerifiedFetch.html @@ -0,0 +1,3 @@ +VerifiedFetch | Helia Verified Fetch
interface VerifiedFetch {
    start(): Promise<void>;
    stop(): Promise<void>;
    (resource, options?): Promise<Response>;
}

Methods

Methods

\ No newline at end of file diff --git a/interfaces/VerifiedFetchInit.html b/interfaces/_helia_verified_fetch.VerifiedFetchInit.html similarity index 60% rename from interfaces/VerifiedFetchInit.html rename to interfaces/_helia_verified_fetch.VerifiedFetchInit.html index 3a8fe6bb..3904973e 100644 --- a/interfaces/VerifiedFetchInit.html +++ b/interfaces/_helia_verified_fetch.VerifiedFetchInit.html @@ -1,39 +1,39 @@ -VerifiedFetchInit | @helia/verified-fetch

Interface VerifiedFetchInit

Options for the fetch function returned by createVerifiedFetch.

+VerifiedFetchInit | Helia Verified Fetch

Options for the fetch function returned by createVerifiedFetch.

This interface contains all the same fields as the options object passed to fetch in browsers, plus an onProgress option to listen for progress events.

-
interface VerifiedFetchInit {
    allowInsecure?: boolean;
    allowLocal?: boolean;
    body?: null | BodyInit;
    cache?: RequestCache;
    credentials?: RequestCredentials;
    headers?: HeadersInit;
    integrity?: string;
    keepalive?: boolean;
    method?: string;
    mode?: RequestMode;
    onProgress?: ((evt) => void);
    priority?: RequestPriority;
    redirect?: RequestRedirect;
    referrer?: string;
    referrerPolicy?: ReferrerPolicy;
    session?: boolean;
    signal?: null | AbortSignal;
    window?: null;
}

Hierarchy

Properties

interface VerifiedFetchInit {
    allowInsecure?: boolean;
    allowLocal?: boolean;
    body?: null | BodyInit;
    cache?: RequestCache;
    credentials?: RequestCredentials;
    headers?: HeadersInit;
    integrity?: string;
    keepalive?: boolean;
    method?: string;
    mode?: RequestMode;
    onProgress?: ((evt) => void);
    priority?: RequestPriority;
    redirect?: RequestRedirect;
    referrer?: string;
    referrerPolicy?: ReferrerPolicy;
    session?: boolean;
    signal?: null | AbortSignal;
    window?: null;
}

Hierarchy

Properties

allowInsecure?: boolean

By default we will not connect to any gateways over HTTP addresses, requring HTTPS connections instead. This is because it will cause "mixed-content" errors to appear in the console when running in secure browser contexts.

Pass true here to connect to insecure Gateways as well, this may be useful in testing environments.

-

Default

false
+

Default

false
 
allowLocal?: boolean

By default we will not connect to any HTTP Gateways providers over local or loopback addresses, this is because they are typically running on remote peers that have published private addresses by mistate.

Pass true here to connect to local Gateways as well, this may be useful in testing environments.

-

Default

false
+

Default

false
 
body?: null | BodyInit

A BodyInit object or null to set request's body.

cache?: RequestCache

A string indicating how the request will interact with the browser's cache to set request's cache.

@@ -43,7 +43,7 @@
keepalive?: boolean

A boolean to set request's keepalive.

method?: string

A string to set request's method.

mode?: RequestMode

A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode.

-
onProgress?: ((evt) => void)

Type declaration

priority?: RequestPriority
redirect?: RequestRedirect

A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect.

+
onProgress?: ((evt) => void)

Type declaration

priority?: RequestPriority
redirect?: RequestRedirect

A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect.

referrer?: string

A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer.

referrerPolicy?: ReferrerPolicy

A referrer policy to set request's referrerPolicy.

session?: boolean

If true, try to create a blockstore session - this can reduce overall @@ -55,8 +55,8 @@ is, requests for https://qmfoo.ipfs.localhost/bar.txt and https://qmfoo.ipfs.localhost/baz.txt would use the same session, if this argument is true for both fetch requests.

-

Default

true
+

Default

true
 
signal?: null | AbortSignal

An AbortSignal to set request's signal.

window?: null

Can only be null. Used to disassociate request from any Window.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/modules.html b/modules.html deleted file mode 100644 index 4d55e4af..00000000 --- a/modules.html +++ /dev/null @@ -1,225 +0,0 @@ -@helia/verified-fetch

@helia/verified-fetch

@helia/verified-fetch provides a fetch-like API for retrieving content from the IPFS network.

-

All content is retrieved in a trustless manner, and the integrity of all bytes are verified by comparing hashes of the data.

-

By default, providers for CIDs are found using delegated routing endpoints.

-

Data is retrieved using the following strategies:

-
    -
  • Directly from providers, using Bitswap over WebSockets and WebRTC if available.
  • -
  • Directly from providers exposing a trustless gateway over HTTPS.
  • -
  • As a fallback, if no providers reachable from a browser are found, data is retrieved using recursive gateways, e.g. trustless-gateway.link which can be configured.
  • -
-

This is a marked improvement over fetch which offers no such protections and is vulnerable to all sorts of attacks like Content Spoofing, DNS Hijacking, etc.

-

A verifiedFetch function is exported to get up and running quickly, and a createVerifiedFetch function is also available that allows customizing the underlying Helia node for complete control over how content is retrieved.

-

Browser-cache-friendly Response objects are returned which should be instantly familiar to web developers.

-

Learn more in the announcement blog post and check out the ready-to-run example.

-

You may use any supported resource argument to fetch content:

-
    -
  • CID instance
  • -
  • IPFS URL
  • -
  • IPNS URL
  • -
-

Example: Getting started

import { verifiedFetch } from '@helia/verified-fetch'

const resp = await verifiedFetch('ipfs://bafy...')

const json = await resp.json() -
-

Example: Using a CID instance to fetch JSON

import { verifiedFetch } from '@helia/verified-fetch'
import { CID } from 'multiformats/cid'

const cid = CID.parse('bafyFoo') // some json file
const response = await verifiedFetch(cid)
const json = await response.json() -
-

Example: Using IPFS protocol to fetch an image

import { verifiedFetch } from '@helia/verified-fetch'

const response = await verifiedFetch('ipfs://bafyFoo') // CID for some image file
const blob = await response.blob()
const image = document.createElement('img')
image.src = URL.createObjectURL(blob)
document.body.appendChild(image) -
-

Example: Using IPNS protocol to stream a big file

import { verifiedFetch } from '@helia/verified-fetch'

const response = await verifiedFetch('ipns://mydomain.com/path/to/very-long-file.log')
const bigFileStreamReader = await response.body?.getReader() -
-

Configuration

Custom HTTP gateways and routers

Out of the box @helia/verified-fetch uses a default set of trustless gateways for fetching blocks and HTTP delegated routers for performing routing tasks - looking up peers, resolving/publishing IPNS names, etc.

-

It's possible to override these by passing gateways and routers keys to the createVerifiedFetch function:

-

Example: Configuring gateways and routers

import { createVerifiedFetch } from '@helia/verified-fetch'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev']
})

const resp = await fetch('ipfs://bafy...')

const json = await resp.json() -
-

Usage with customized Helia

For full control of how @helia/verified-fetch fetches content from the distributed web you can pass a preconfigured Helia node to createVerifiedFetch.

-

The helia module is configured with a libp2p node that is suited for decentralized applications, alternatively @helia/http is available which uses HTTP gateways for all network operations.

-

You can see variations of Helia and js-libp2p configuration options at https://ipfs.github.io/helia/interfaces/helia.HeliaInit.html.

-
import { trustlessGateway } from '@helia/block-brokers'
import { createHeliaHTTP } from '@helia/http'
import { delegatedHTTPRouting, httpGatewayRouting } from '@helia/routers'
import { createVerifiedFetch } from '@helia/verified-fetch'

const fetch = await createVerifiedFetch(
await createHeliaHTTP({
blockBrokers: [
trustlessGateway()
],
routers: [
delegatedHTTPRouting('http://delegated-ipfs.dev'),
httpGatewayRouting({
gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
})
]
})
)

const resp = await fetch('ipfs://bafy...')

const json = await resp.json() -
-

Custom content-type parsing

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.

-

If you require an accurate content-type you can provide a contentTypeParser function as an option to createVerifiedFetch to handle parsing the content type.

-

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.

-

Example: Customizing content-type parsing

import { createVerifiedFetch } from '@helia/verified-fetch'
import { fileTypeFromBuffer } from '@sgtpooki/file-type'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev']
}, {
contentTypeParser: async (bytes) => {
// call to some magic-byte recognition library like magic-bytes, file-type, or your own custom byte recognition
const result = await fileTypeFromBuffer(bytes)
return result?.mime
}
}) -
-

Custom DNS resolvers

If you don't want to leak DNS queries to the default resolvers, you can provide your own list of DNS resolvers to createVerifiedFetch.

-

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.

-

Example: Customizing DNS resolvers

import { createVerifiedFetch } from '@helia/verified-fetch'
import { dnsJsonOverHttps, dnsOverHttps } from '@multiformats/dns/resolvers'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev'],
dnsResolvers: [
dnsJsonOverHttps('https://my-dns-resolver.example.com/dns-json'),
dnsOverHttps('https://my-dns-resolver.example.com/dns-query')
]
}) -
-

Example: Customizing DNS per-TLD resolvers

DNS resolvers can be configured to only service DNS queries for specific -TLDs:

-
import { createVerifiedFetch } from '@helia/verified-fetch'
import { dnsJsonOverHttps, dnsOverHttps } from '@multiformats/dns/resolvers'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev'],
dnsResolvers: {
// this resolver will only be used for `.com` domains (note - this could
// also be an array of resolvers)
'com.': dnsJsonOverHttps('https://my-dns-resolver.example.com/dns-json'),
// this resolver will be used for everything else (note - this could
// also be an array of resolvers)
'.': dnsOverHttps('https://my-dns-resolver.example.com/dns-query')
}
}) -
-

Custom Hashers

By default, @helia/verified-fetch supports sha256, sha512, and identity hashers.

-

If you need to use a different hasher, you can provide a custom hasher function as an option to createVerifiedFetch.

-

Example: Passing a custom hashing function

import { createVerifiedFetch } from '@helia/verified-fetch'
import { blake2b256 } from '@multiformats/blake2/blake2b'

const verifiedFetch = await createVerifiedFetch({
gateways: ['https://ipfs.io'],
hashers: [blake2b256]
})

const resp = await verifiedFetch('ipfs://cid-using-blake2b256') -
-

IPLD codec handling

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.

-

DAG-PB

DAG-PB is the codec we are most likely to encounter, it is what UnixFS uses under the hood.

-
Using the DAG-PB codec as a Blob
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const blob = await res.blob()

console.info(blob) // Blob { size: x, type: 'application/octet-stream' } -
-
Using the DAG-PB codec as an ArrayBuffer
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const buf = await res.arrayBuffer()

console.info(buf) // ArrayBuffer { [Uint8Contents]: < ... >, byteLength: x } -
-
Using the DAG-PB codec as a stream
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const reader = res.body?.getReader()

if (reader == null) {
throw new Error('Could not create reader from response body')
}

while (true) {
const next = await reader.read()

if (next?.done === true) {
break
}

if (next?.value != null) {
console.info(next.value) // Uint8Array(x) [ ... ]
}
} -
-
Content-Type

When fetching DAG-PB data, the content type will be set to application/octet-stream unless a custom content-type parser is configured.

-

JSON

The JSON codec is a very simple codec, a block parseable with this codec is a JSON string encoded into a Uint8Array.

-
Using the JSON codec
import * as json from 'multiformats/codecs/json'

const block = new TextEncoder().encode('{ "hello": "world" }')
const obj = json.decode(block)

console.info(obj) // { hello: 'world' } -
-
Content-Type

When the JSON codec is encountered, the Content-Type header of the response will be set to application/json.

-

DAG-JSON

DAG-JSON expands on the JSON codec, adding the ability to contain CIDs which act as links to other blocks, and byte arrays.

-

CIDs and byte arrays are represented using special object structures with a single "/" property.

-

Using DAG-JSON has two important caveats:

-
    -
  1. Your JSON structure cannot contain an object with only a "/" property, as it will be interpreted as a special type.
  2. -
  3. Since JSON has no technical limit on number sizes, DAG-JSON also allows numbers larger than Number.MAX_SAFE_INTEGER. JavaScript requires use of BigInts to represent numbers larger than this, and JSON.parse does not support them, so precision will be lost.
  4. -
-

Otherwise this codec follows the same rules as the JSON codec.

-
Using the DAG-JSON codec
import * as dagJson from '@ipld/dag-json'

const block = new TextEncoder().encode(`{
"hello": "world",
"cid": {
"/": "baeaaac3imvwgy3zao5xxe3de"
},
"buf": {
"/": {
"bytes": "AAECAwQ"
}
}
}`)

const obj = dagJson.decode(block)

console.info(obj)
// {
// hello: 'world',
// cid: CID(baeaaac3imvwgy3zao5xxe3de),
// buf: Uint8Array(5) [ 0, 1, 2, 3, 4 ]
// } -
-
Content-Type

When the DAG-JSON codec is encountered in the requested CID, the Content-Type header of the response will be set to application/json.

-

DAG-JSON data can be parsed from the response by using the .json() function, which will return CIDs/byte arrays as plain { "/": ... } objects:

-
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagJson from '@ipld/dag-json'

const res = await verifiedFetch('ipfs://bafyDAGJSON')

// either:
const obj = await res.json()
console.info(obj.cid) // { "/": "baeaaac3imvwgy3zao5xxe3de" }
console.info(obj.buf) // { "/": { "bytes": "AAECAwQ" } } -
-

Alternatively, it can be decoded using the @ipld/dag-json module and the .arrayBuffer() method, in which case you will get CID objects and Uint8Arrays:

-
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagJson from '@ipld/dag-json'

const res = await verifiedFetch('ipfs://bafyDAGJSON')

// or:
const obj = dagJson.decode<any>(await res.arrayBuffer())
console.info(obj.cid) // CID(baeaaac3imvwgy3zao5xxe3de)
console.info(obj.buf) // Uint8Array(5) [ 0, 1, 2, 3, 4 ] -
-

DAG-CBOR

DAG-CBOR uses the Concise Binary Object Representation format for serialization instead of JSON.

-

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.

-
Content-Type

Not all data types supported by DAG-CBOR can be successfully turned into JSON and back into the same binary form.

-

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.

-

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().

-
Detecting JSON-safe DAG-CBOR

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.

-
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagCbor from '@ipld/dag-cbor'

const res = await verifiedFetch('ipfs://bafyDagCborCID')
let obj

if (res.headers.get('Content-Type') === 'application/json') {
// DAG-CBOR data can be safely decoded as JSON
obj = await res.json()
} else {
// response contains non-JSON friendly data types
obj = dagCbor.decode(await res.arrayBuffer())
}

console.info(obj) // ... -
-

The Accept header

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.

-

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 response will be returned:

-
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyJPEGImageCID', {
headers: {
accept: 'image/png'
}
})

console.info(res.status) // 406 - the image was a JPEG but we specified PNG as the accept header -
-

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:

-
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyDAGCBORCID', {
headers: {
accept: 'application/octet-stream'
}
})

console.info(res.headers.get('accept')) // application/octet-stream
const buf = await res.arrayBuffer() // raw bytes, not processed as JSON -
-

Redirects

If a requested URL contains a path component, that path component resolves to -a UnixFS directory, but the URL does not have a trailing slash, one will be -added to form a canonical URL for that resource, otherwise the request will -be resolved as normal.

-
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir')

console.info(res.url) // ipfs://bafyfoo/path/to/dir/ -
-

It's possible to prevent this behaviour and/or handle a redirect manually -through use of the redirect -option.

-

Example: Redirect: follow

This is the default value and is what happens if no value is specified.

-
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'follow'
})

console.info(res.status) // 200
console.info(res.url) // ipfs://bafyfoo/path/to/dir/
console.info(res.redirected) // true -
-

Example: Redirect: error

This causes a TypeError to be thrown if a URL would cause a redirect.

-

import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'error'
})
// throw TypeError('Failed to fetch') -
-

Example: Redirect: manual

Manual redirects allow the user to process the redirect. A 301 -is returned, and the location to redirect to is available as the "location" -response header.

-

This differs slightly from HTTP fetch which returns an opaque response as the -browser itself is expected to process the redirect and hide all details from -the user.

-

import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'manual'
})

console.info(res.status) // 301
console.info(res.url) // ipfs://bafyfoo/path/to/dir
console.info(res.redirected) // false
console.info(res.headers.get('location')) // ipfs://bafyfoo/path/to/dir/ -
-

Comparison to fetch

This module attempts to act as similarly to the fetch() API as possible.

-

The fetch() API takes two parameters:

-
    -
  1. A resource
  2. -
  3. An options object
  4. -
-

Resource argument

This library supports the following methods of fetching web3 content from IPFS:

-
    -
  1. IPFS protocol: ipfs://<cidv0> & ipfs://<cidv1>
  2. -
  3. IPNS protocol: ipns://<peerId> & ipns://<publicKey> & ipns://<hostUri_Supporting_DnsLink_TxtRecords>
  4. -
  5. CID instances: An actual CID instance CID.parse('bafy...')
  6. -
-

As well as support for pathing & params for items 1 & 2 above according to IPFS - Path Gateway Specification & IPFS - Trustless Gateway Specification. Further refinement of those specifications specifically for web-based scenarios can be found in the Web Pathing Specification IPIP.

-

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.

-

Options argument

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 related to specifying the resultant shape of desired content.

-

Some of those header specifications are:

-
    -
  1. https://specs.ipfs.tech/http-gateways/path-gateway/#request-headers
  2. -
  3. https://specs.ipfs.tech/http-gateways/trustless-gateway/#request-headers
  4. -
  5. https://specs.ipfs.tech/http-gateways/subdomain-gateway/#request-headers
  6. -
-

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.

-

Known Fetch API options that will be supported:

-
    -
  1. signal - An AbortSignal that a user can use to abort the request.
  2. -
  3. 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 parameter.
  4. -
  5. headers - An object of headers to be sent with the request. Best effort to adhere to the Fetch API headers parameter. -
  6. -
  7. 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 parameter.
  8. -
  9. body - An object that specifies the body of the request. Best effort to adhere to the Fetch API body parameter.
  10. -
  11. cache - Will basically act as force-cache for the request. Best effort to adhere to the Fetch API cache parameter.
  12. -
-

Non-Fetch API options that will be supported:

-
    -
  1. onProgress - Similar to Helia onProgress options, this will be a function that will be called with a progress event. Supported progress events are:
      -
    • helia:verified-fetch:error - An error occurred during the request.
    • -
    • helia:verified-fetch:request:start - The request has been sent
    • -
    • helia:verified-fetch:request:complete - The request has been sent
    • -
    • helia:verified-fetch:request:error - An error occurred during the request.
    • -
    • helia:verified-fetch:request:abort - The request was aborted prior to completion.
    • -
    • helia:verified-fetch:response:start - The initial HTTP Response headers have been set, and response stream is started.
    • -
    • helia:verified-fetch:response:complete - The response stream has completed.
    • -
    • helia:verified-fetch:response:error - An error occurred while building the response.
    • -
    -
  2. -
-

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:

-
    -
  1. IPIP-0412: Signaling Block Order in CARs on HTTP Gateways
  2. -
  3. IPIP-0402: Partial CAR Support on Trustless Gateways
  4. -
  5. IPIP-0386: Subdomain Gateway Interop with _redirects
  6. -
  7. IPIP-0328: JSON and CBOR Response Formats on HTTP Gateways
  8. -
  9. IPIP-0288: TAR Response Format on HTTP Gateways
  10. -
-

Response types

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.

-

All content we retrieve from the IPFS network is obtained via an AsyncIterable, and will be set as the body of the HTTP Response via a ReadableStream 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.

-

If your content doesn't have a mime-type or an IPFS spec, this library will not support it, but you can use the helia library directly for those use cases. See Unsupported response types for more information.

-

Handling response types

For handling responses we want to follow conventions/abstractions from Fetch API where possible:

-
    -
  • 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.
  • -
  • For images (or other web-relevant asset) you want to add to the DOM, use .blob() or .arrayBuffer() to get the raw bytes.
  • -
  • For plain text in utf-8, you would call .text()
  • -
  • For streaming response data, use something like response.body.getReader() to get a ReadableStream.
  • -
-

Unsupported response types

    -
  • 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. Instead, users should request aplication/vnd.ipld.car or use the helia library directly for this use case.
  • -
  • Others? Open an issue or PR!
  • -
-

Response headers

This library will set the HTTP Response headers to the appropriate values for the content type according to the appropriate IPFS Specifications.

-

Some known header specifications:

- -

Possible Scenarios that could cause confusion

Attempting to fetch the CID for content that does not make sense

If you request bafybeiaysi4s6lnjev27ln5icwm6tueaw2vdykrtjkwiphwekaywqhcjze, which points to the root of the en.wikipedia.org mirror, a response object does not make sense.

-

Errors

Known Errors that can be thrown:

-
    -
  1. TypeError - If the resource argument is not a string, CID, or CID string.
  2. -
  3. TypeError - If the options argument is passed and not an object.
  4. -
  5. TypeError - If the options argument is passed and is malformed.
  6. -
  7. AbortError - If the content request is aborted due to user aborting provided AbortSignal. Note that this is a AbortError from @libp2p/interface and not the standard AbortError from the Fetch API.
  8. -
-

Index

Interfaces

Type Aliases

Functions

\ No newline at end of file diff --git a/modules/_helia_verified_fetch.html b/modules/_helia_verified_fetch.html new file mode 100644 index 00000000..4f0a82d9 --- /dev/null +++ b/modules/_helia_verified_fetch.html @@ -0,0 +1,482 @@ +@helia/verified-fetch | Helia Verified Fetch

Module @helia/verified-fetch

@helia/verified-fetch provides a fetch-like API for retrieving content from the IPFS network.

+

All content is retrieved in a trustless manner, and the integrity of all bytes are verified by comparing hashes of the data.

+

By default, providers for CIDs are found using delegated routing endpoints.

+

Data is retrieved using the following strategies:

+
    +
  • Directly from providers, using Bitswap over WebSockets and WebRTC if available.
  • +
  • Directly from providers exposing a trustless gateway over HTTPS.
  • +
  • As a fallback, if no providers reachable from a browser are found, data is retrieved using recursive gateways, e.g. trustless-gateway.link which can be configured.
  • +
+

This is a marked improvement over fetch which offers no such protections and is vulnerable to all sorts of attacks like Content Spoofing, DNS Hijacking, etc.

+

A verifiedFetch function is exported to get up and running quickly, and a createVerifiedFetch function is also available that allows customizing the underlying Helia node for complete control over how content is retrieved.

+

Browser-cache-friendly Response objects are returned which should be instantly familiar to web developers.

+

Learn more in the announcement blog post and check out the ready-to-run example.

+

You may use any supported resource argument to fetch content:

+
    +
  • CID instance
  • +
  • IPFS URL
  • +
  • IPNS URL
  • +
+

Example: Getting started

import { verifiedFetch } from '@helia/verified-fetch'

const resp = await verifiedFetch('ipfs://bafy...')

const json = await resp.json() +
+

Example: Using a CID instance to fetch JSON

import { verifiedFetch } from '@helia/verified-fetch'
import { CID } from 'multiformats/cid'

const cid = CID.parse('bafyFoo') // some json file
const response = await verifiedFetch(cid)
const json = await response.json() +
+

Example: Using IPFS protocol to fetch an image

import { verifiedFetch } from '@helia/verified-fetch'

const response = await verifiedFetch('ipfs://bafyFoo') // CID for some image file
const blob = await response.blob()
const image = document.createElement('img')
image.src = URL.createObjectURL(blob)
document.body.appendChild(image) +
+

Example: Using IPNS protocol to stream a big file

import { verifiedFetch } from '@helia/verified-fetch'

const response = await verifiedFetch('ipns://mydomain.com/path/to/very-long-file.log')
const bigFileStreamReader = await response.body?.getReader() +
+

Configuration

Custom HTTP gateways and routers

Out of the box @helia/verified-fetch uses a default set of trustless gateways for fetching blocks and HTTP delegated routers for performing routing tasks - looking up peers, resolving/publishing IPNS names, etc.

+

It's possible to override these by passing gateways and routers keys to the createVerifiedFetch function:

+

Example: Configuring gateways and routers

import { createVerifiedFetch } from '@helia/verified-fetch'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev']
})

const resp = await fetch('ipfs://bafy...')

const json = await resp.json() +
+

Usage with customized Helia

For full control of how @helia/verified-fetch fetches content from the distributed web you can pass a preconfigured Helia node to createVerifiedFetch.

+

The helia module is configured with a libp2p node that is suited for decentralized applications, alternatively @helia/http is available which uses HTTP gateways for all network operations.

+

You can see variations of Helia and js-libp2p configuration options at https://ipfs.github.io/helia/interfaces/helia.HeliaInit.html.

+
import { trustlessGateway } from '@helia/block-brokers'
import { createHeliaHTTP } from '@helia/http'
import { delegatedHTTPRouting, httpGatewayRouting } from '@helia/routers'
import { createVerifiedFetch } from '@helia/verified-fetch'

const fetch = await createVerifiedFetch(
await createHeliaHTTP({
blockBrokers: [
trustlessGateway()
],
routers: [
delegatedHTTPRouting('http://delegated-ipfs.dev'),
httpGatewayRouting({
gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
})
]
})
)

const resp = await fetch('ipfs://bafy...')

const json = await resp.json() +
+

Custom content-type parsing

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.

+

If you require an accurate content-type you can provide a contentTypeParser function as an option to createVerifiedFetch to handle parsing the content type.

+

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.

+

Example: Customizing content-type parsing

import { createVerifiedFetch } from '@helia/verified-fetch'
import { fileTypeFromBuffer } from '@sgtpooki/file-type'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev']
}, {
contentTypeParser: async (bytes) => {
// call to some magic-byte recognition library like magic-bytes, file-type, or your own custom byte recognition
const result = await fileTypeFromBuffer(bytes)
return result?.mime
}
}) +
+

Custom DNS resolvers

If you don't want to leak DNS queries to the default resolvers, you can provide your own list of DNS resolvers to createVerifiedFetch.

+

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.

+

Example: Customizing DNS resolvers

import { createVerifiedFetch } from '@helia/verified-fetch'
import { dnsJsonOverHttps, dnsOverHttps } from '@multiformats/dns/resolvers'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev'],
dnsResolvers: [
dnsJsonOverHttps('https://my-dns-resolver.example.com/dns-json'),
dnsOverHttps('https://my-dns-resolver.example.com/dns-query')
]
}) +
+

Example: Customizing DNS per-TLD resolvers

DNS resolvers can be configured to only service DNS queries for specific +TLDs:

+
import { createVerifiedFetch } from '@helia/verified-fetch'
import { dnsJsonOverHttps, dnsOverHttps } from '@multiformats/dns/resolvers'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev'],
dnsResolvers: {
// this resolver will only be used for `.com` domains (note - this could
// also be an array of resolvers)
'com.': dnsJsonOverHttps('https://my-dns-resolver.example.com/dns-json'),
// this resolver will be used for everything else (note - this could
// also be an array of resolvers)
'.': dnsOverHttps('https://my-dns-resolver.example.com/dns-query')
}
}) +
+

Custom Hashers

By default, @helia/verified-fetch supports sha256, sha512, and identity hashers.

+

If you need to use a different hasher, you can provide a custom hasher function as an option to createVerifiedFetch.

+

Example: Passing a custom hashing function

import { createVerifiedFetch } from '@helia/verified-fetch'
import { blake2b256 } from '@multiformats/blake2/blake2b'

const verifiedFetch = await createVerifiedFetch({
gateways: ['https://ipfs.io'],
hashers: [blake2b256]
})

const resp = await verifiedFetch('ipfs://cid-using-blake2b256') +
+

IPLD codec handling

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.

+

DAG-PB

DAG-PB is the codec we are most likely to encounter, it is what UnixFS uses under the hood.

+
Using the DAG-PB codec as a Blob
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const blob = await res.blob()

console.info(blob) // Blob { size: x, type: 'application/octet-stream' } +
+
Using the DAG-PB codec as an ArrayBuffer
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const buf = await res.arrayBuffer()

console.info(buf) // ArrayBuffer { [Uint8Contents]: < ... >, byteLength: x } +
+
Using the DAG-PB codec as a stream
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const reader = res.body?.getReader()

if (reader == null) {
throw new Error('Could not create reader from response body')
}

while (true) {
const next = await reader.read()

if (next?.done === true) {
break
}

if (next?.value != null) {
console.info(next.value) // Uint8Array(x) [ ... ]
}
} +
+
Content-Type

When fetching DAG-PB data, the content type will be set to application/octet-stream unless a custom content-type parser is configured.

+

JSON

The JSON codec is a very simple codec, a block parseable with this codec is a JSON string encoded into a Uint8Array.

+
Using the JSON codec
import * as json from 'multiformats/codecs/json'

const block = new TextEncoder().encode('{ "hello": "world" }')
const obj = json.decode(block)

console.info(obj) // { hello: 'world' } +
+
Content-Type

When the JSON codec is encountered, the Content-Type header of the response will be set to application/json.

+

DAG-JSON

DAG-JSON expands on the JSON codec, adding the ability to contain CIDs which act as links to other blocks, and byte arrays.

+

CIDs and byte arrays are represented using special object structures with a single "/" property.

+

Using DAG-JSON has two important caveats:

+
    +
  1. Your JSON structure cannot contain an object with only a "/" property, as it will be interpreted as a special type.
  2. +
  3. Since JSON has no technical limit on number sizes, DAG-JSON also allows numbers larger than Number.MAX_SAFE_INTEGER. JavaScript requires use of BigInts to represent numbers larger than this, and JSON.parse does not support them, so precision will be lost.
  4. +
+

Otherwise this codec follows the same rules as the JSON codec.

+
Using the DAG-JSON codec
import * as dagJson from '@ipld/dag-json'

const block = new TextEncoder().encode(`{
"hello": "world",
"cid": {
"/": "baeaaac3imvwgy3zao5xxe3de"
},
"buf": {
"/": {
"bytes": "AAECAwQ"
}
}
}`)

const obj = dagJson.decode(block)

console.info(obj)
// {
// hello: 'world',
// cid: CID(baeaaac3imvwgy3zao5xxe3de),
// buf: Uint8Array(5) [ 0, 1, 2, 3, 4 ]
// } +
+
Content-Type

When the DAG-JSON codec is encountered in the requested CID, the Content-Type header of the response will be set to application/json.

+

DAG-JSON data can be parsed from the response by using the .json() function, which will return CIDs/byte arrays as plain { "/": ... } objects:

+
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagJson from '@ipld/dag-json'

const res = await verifiedFetch('ipfs://bafyDAGJSON')

// either:
const obj = await res.json()
console.info(obj.cid) // { "/": "baeaaac3imvwgy3zao5xxe3de" }
console.info(obj.buf) // { "/": { "bytes": "AAECAwQ" } } +
+

Alternatively, it can be decoded using the @ipld/dag-json module and the .arrayBuffer() method, in which case you will get CID objects and Uint8Arrays:

+
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagJson from '@ipld/dag-json'

const res = await verifiedFetch('ipfs://bafyDAGJSON')

// or:
const obj = dagJson.decode<any>(await res.arrayBuffer())
console.info(obj.cid) // CID(baeaaac3imvwgy3zao5xxe3de)
console.info(obj.buf) // Uint8Array(5) [ 0, 1, 2, 3, 4 ] +
+

DAG-CBOR

DAG-CBOR uses the Concise Binary Object Representation format for serialization instead of JSON.

+

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.

+
Content-Type

Not all data types supported by DAG-CBOR can be successfully turned into JSON and back into the same binary form.

+

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.

+

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().

+
Detecting JSON-safe DAG-CBOR

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.

+
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagCbor from '@ipld/dag-cbor'

const res = await verifiedFetch('ipfs://bafyDagCborCID')
let obj

if (res.headers.get('Content-Type') === 'application/json') {
// DAG-CBOR data can be safely decoded as JSON
obj = await res.json()
} else {
// response contains non-JSON friendly data types
obj = dagCbor.decode(await res.arrayBuffer())
}

console.info(obj) // ... +
+

The Accept header

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.

+

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 response will be returned:

+
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyJPEGImageCID', {
headers: {
accept: 'image/png'
}
})

console.info(res.status) // 406 - the image was a JPEG but we specified PNG as the accept header +
+

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:

+
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyDAGCBORCID', {
headers: {
accept: 'application/octet-stream'
}
})

console.info(res.headers.get('accept')) // application/octet-stream
const buf = await res.arrayBuffer() // raw bytes, not processed as JSON +
+

Redirects

If a requested URL contains a path component, that path component resolves to +a UnixFS directory, but the URL does not have a trailing slash, one will be +added to form a canonical URL for that resource, otherwise the request will +be resolved as normal.

+
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir')

console.info(res.url) // ipfs://bafyfoo/path/to/dir/ +
+

It's possible to prevent this behaviour and/or handle a redirect manually +through use of the redirect +option.

+

Example: Redirect: follow

This is the default value and is what happens if no value is specified.

+
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'follow'
})

console.info(res.status) // 200
console.info(res.url) // ipfs://bafyfoo/path/to/dir/
console.info(res.redirected) // true +
+

Example: Redirect: error

This causes a TypeError to be thrown if a URL would cause a redirect.

+

import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'error'
})
// throw TypeError('Failed to fetch') +
+

Example: Redirect: manual

Manual redirects allow the user to process the redirect. A 301 +is returned, and the location to redirect to is available as the "location" +response header.

+

This differs slightly from HTTP fetch which returns an opaque response as the +browser itself is expected to process the redirect and hide all details from +the user.

+

import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'manual'
})

console.info(res.status) // 301
console.info(res.url) // ipfs://bafyfoo/path/to/dir
console.info(res.redirected) // false
console.info(res.headers.get('location')) // ipfs://bafyfoo/path/to/dir/ +
+

Comparison to fetch

This module attempts to act as similarly to the fetch() API as possible.

+

The fetch() API takes two parameters:

+
    +
  1. A resource
  2. +
  3. An options object
  4. +
+

Resource argument

This library supports the following methods of fetching web3 content from IPFS:

+
    +
  1. IPFS protocol: ipfs://<cidv0> & ipfs://<cidv1>
  2. +
  3. IPNS protocol: ipns://<peerId> & ipns://<publicKey> & ipns://<hostUri_Supporting_DnsLink_TxtRecords>
  4. +
  5. CID instances: An actual CID instance CID.parse('bafy...')
  6. +
+

As well as support for pathing & params for items 1 & 2 above according to IPFS - Path Gateway Specification & IPFS - Trustless Gateway Specification. Further refinement of those specifications specifically for web-based scenarios can be found in the Web Pathing Specification IPIP.

+

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.

+

Options argument

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 related to specifying the resultant shape of desired content.

+

Some of those header specifications are:

+
    +
  1. https://specs.ipfs.tech/http-gateways/path-gateway/#request-headers
  2. +
  3. https://specs.ipfs.tech/http-gateways/trustless-gateway/#request-headers
  4. +
  5. https://specs.ipfs.tech/http-gateways/subdomain-gateway/#request-headers
  6. +
+

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.

+

Known Fetch API options that will be supported:

+
    +
  1. signal - An AbortSignal that a user can use to abort the request.
  2. +
  3. 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 parameter.
  4. +
  5. headers - An object of headers to be sent with the request. Best effort to adhere to the Fetch API headers parameter. +
  6. +
  7. 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 parameter.
  8. +
  9. body - An object that specifies the body of the request. Best effort to adhere to the Fetch API body parameter.
  10. +
  11. cache - Will basically act as force-cache for the request. Best effort to adhere to the Fetch API cache parameter.
  12. +
+

Non-Fetch API options that will be supported:

+
    +
  1. onProgress - Similar to Helia onProgress options, this will be a function that will be called with a progress event. Supported progress events are:
      +
    • helia:verified-fetch:error - An error occurred during the request.
    • +
    • helia:verified-fetch:request:start - The request has been sent
    • +
    • helia:verified-fetch:request:complete - The request has been sent
    • +
    • helia:verified-fetch:request:error - An error occurred during the request.
    • +
    • helia:verified-fetch:request:abort - The request was aborted prior to completion.
    • +
    • helia:verified-fetch:response:start - The initial HTTP Response headers have been set, and response stream is started.
    • +
    • helia:verified-fetch:response:complete - The response stream has completed.
    • +
    • helia:verified-fetch:response:error - An error occurred while building the response.
    • +
    +
  2. +
+

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:

+
    +
  1. IPIP-0412: Signaling Block Order in CARs on HTTP Gateways
  2. +
  3. IPIP-0402: Partial CAR Support on Trustless Gateways
  4. +
  5. IPIP-0386: Subdomain Gateway Interop with _redirects
  6. +
  7. IPIP-0328: JSON and CBOR Response Formats on HTTP Gateways
  8. +
  9. IPIP-0288: TAR Response Format on HTTP Gateways
  10. +
+

Response types

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.

+

All content we retrieve from the IPFS network is obtained via an AsyncIterable, and will be set as the body of the HTTP Response via a ReadableStream 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.

+

If your content doesn't have a mime-type or an IPFS spec, this library will not support it, but you can use the helia library directly for those use cases. See Unsupported response types for more information.

+

Handling response types

For handling responses we want to follow conventions/abstractions from Fetch API where possible:

+
    +
  • 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.
  • +
  • For images (or other web-relevant asset) you want to add to the DOM, use .blob() or .arrayBuffer() to get the raw bytes.
  • +
  • For plain text in utf-8, you would call .text()
  • +
  • For streaming response data, use something like response.body.getReader() to get a ReadableStream.
  • +
+

Unsupported response types

    +
  • 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. Instead, users should request aplication/vnd.ipld.car or use the helia library directly for this use case.
  • +
  • Others? Open an issue or PR!
  • +
+

Response headers

This library will set the HTTP Response headers to the appropriate values for the content type according to the appropriate IPFS Specifications.

+

Some known header specifications:

+ +

Possible Scenarios that could cause confusion

Attempting to fetch the CID for content that does not make sense

If you request bafybeiaysi4s6lnjev27ln5icwm6tueaw2vdykrtjkwiphwekaywqhcjze, which points to the root of the en.wikipedia.org mirror, a response object does not make sense.

+

Errors

Known Errors that can be thrown:

+
    +
  1. TypeError - If the resource argument is not a string, CID, or CID string.
  2. +
  3. TypeError - If the options argument is passed and not an object.
  4. +
  5. TypeError - If the options argument is passed and is malformed.
  6. +
  7. AbortError - If the content request is aborted due to user aborting provided AbortSignal. Note that this is a AbortError from @libp2p/interface and not the standard AbortError from the Fetch API.
  8. +
+

+ + Helia logo + +

+ +

@helia/verified-fetch

ipfs.tech +Discuss +codecov +CI

+
+

A fetch-like API for obtaining verified & trustless IPFS content on the web

+
+

About

+ +

@helia/verified-fetch provides a fetch-like API for retrieving content from the IPFS network.

+

All content is retrieved in a trustless manner, and the integrity of all bytes are verified by comparing hashes of the data.

+

By default, providers for CIDs are found using delegated routing endpoints.

+

Data is retrieved using the following strategies:

+
    +
  • Directly from providers, using Bitswap over WebSockets and WebRTC if available.
  • +
  • Directly from providers exposing a trustless gateway over HTTPS.
  • +
  • As a fallback, if no providers reachable from a browser are found, data is retrieved using recursive gateways, e.g. trustless-gateway.link which can be configured.
  • +
+

This is a marked improvement over fetch which offers no such protections and is vulnerable to all sorts of attacks like Content Spoofing, DNS Hijacking, etc.

+

A verifiedFetch function is exported to get up and running quickly, and a createVerifiedFetch function is also available that allows customizing the underlying Helia node for complete control over how content is retrieved.

+

Browser-cache-friendly Response objects are returned which should be instantly familiar to web developers.

+

Learn more in the announcement blog post and check out the ready-to-run example.

+

You may use any supported resource argument to fetch content:

+
    +
  • CID instance
  • +
  • IPFS URL
  • +
  • IPNS URL
  • +
+

Example - Getting started

import { verifiedFetch } from '@helia/verified-fetch'

const resp = await verifiedFetch('ipfs://bafy...')

const json = await resp.json() +
+

Example - Using a CID instance to fetch JSON

import { verifiedFetch } from '@helia/verified-fetch'
import { CID } from 'multiformats/cid'

const cid = CID.parse('bafyFoo') // some json file
const response = await verifiedFetch(cid)
const json = await response.json() +
+

Example - Using IPFS protocol to fetch an image

import { verifiedFetch } from '@helia/verified-fetch'

const response = await verifiedFetch('ipfs://bafyFoo') // CID for some image file
const blob = await response.blob()
const image = document.createElement('img')
image.src = URL.createObjectURL(blob)
document.body.appendChild(image) +
+

Example - Using IPNS protocol to stream a big file

import { verifiedFetch } from '@helia/verified-fetch'

const response = await verifiedFetch('ipns://mydomain.com/path/to/very-long-file.log')
const bigFileStreamReader = await response.body?.getReader() +
+

Configuration

Custom HTTP gateways and routers

Out of the box @helia/verified-fetch uses a default set of trustless gateways for fetching blocks and HTTP delegated routers for performing routing tasks - looking up peers, resolving/publishing IPNS names, etc.

+

It's possible to override these by passing gateways and routers keys to the createVerifiedFetch function:

+

Example - Configuring gateways and routers

import { createVerifiedFetch } from '@helia/verified-fetch'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev']
})

const resp = await fetch('ipfs://bafy...')

const json = await resp.json() +
+

Usage with customized Helia

For full control of how @helia/verified-fetch fetches content from the distributed web you can pass a preconfigured Helia node to createVerifiedFetch.

+

The helia module is configured with a libp2p node that is suited for decentralized applications, alternatively @helia/http is available which uses HTTP gateways for all network operations.

+

You can see variations of Helia and js-libp2p configuration options at https://ipfs.github.io/helia/interfaces/helia.HeliaInit.html.

+
import { trustlessGateway } from '@helia/block-brokers'
import { createHeliaHTTP } from '@helia/http'
import { delegatedHTTPRouting, httpGatewayRouting } from '@helia/routers'
import { createVerifiedFetch } from '@helia/verified-fetch'

const fetch = await createVerifiedFetch(
await createHeliaHTTP({
blockBrokers: [
trustlessGateway()
],
routers: [
delegatedHTTPRouting('http://delegated-ipfs.dev'),
httpGatewayRouting({
gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
})
]
})
)

const resp = await fetch('ipfs://bafy...')

const json = await resp.json() +
+

Custom content-type parsing

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.

+

If you require an accurate content-type you can provide a contentTypeParser function as an option to createVerifiedFetch to handle parsing the content type.

+

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.

+

Example - Customizing content-type parsing

import { createVerifiedFetch } from '@helia/verified-fetch'
import { fileTypeFromBuffer } from '@sgtpooki/file-type'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev']
}, {
contentTypeParser: async (bytes) => {
// call to some magic-byte recognition library like magic-bytes, file-type, or your own custom byte recognition
const result = await fileTypeFromBuffer(bytes)
return result?.mime
}
}) +
+

Custom DNS resolvers

If you don't want to leak DNS queries to the default resolvers, you can provide your own list of DNS resolvers to createVerifiedFetch.

+

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.

+

Example - Customizing DNS resolvers

import { createVerifiedFetch } from '@helia/verified-fetch'
import { dnsJsonOverHttps, dnsOverHttps } from '@multiformats/dns/resolvers'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev'],
dnsResolvers: [
dnsJsonOverHttps('https://my-dns-resolver.example.com/dns-json'),
dnsOverHttps('https://my-dns-resolver.example.com/dns-query')
]
}) +
+

Example - Customizing DNS per-TLD resolvers

DNS resolvers can be configured to only service DNS queries for specific +TLDs:

+
import { createVerifiedFetch } from '@helia/verified-fetch'
import { dnsJsonOverHttps, dnsOverHttps } from '@multiformats/dns/resolvers'

const fetch = await createVerifiedFetch({
gateways: ['https://trustless-gateway.link'],
routers: ['http://delegated-ipfs.dev'],
dnsResolvers: {
// this resolver will only be used for `.com` domains (note - this could
// also be an array of resolvers)
'com.': dnsJsonOverHttps('https://my-dns-resolver.example.com/dns-json'),
// this resolver will be used for everything else (note - this could
// also be an array of resolvers)
'.': dnsOverHttps('https://my-dns-resolver.example.com/dns-query')
}
}) +
+

Custom Hashers

By default, @helia/verified-fetch supports sha256, sha512, and identity hashers.

+

If you need to use a different hasher, you can provide a custom hasher function as an option to createVerifiedFetch.

+

Example - Passing a custom hashing function

import { createVerifiedFetch } from '@helia/verified-fetch'
import { blake2b256 } from '@multiformats/blake2/blake2b'

const verifiedFetch = await createVerifiedFetch({
gateways: ['https://ipfs.io'],
hashers: [blake2b256]
})

const resp = await verifiedFetch('ipfs://cid-using-blake2b256') +
+

IPLD codec handling

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.

+

DAG-PB

DAG-PB is the codec we are most likely to encounter, it is what UnixFS uses under the hood.

+
Using the DAG-PB codec as a Blob
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const blob = await res.blob()

console.info(blob) // Blob { size: x, type: 'application/octet-stream' } +
+
Using the DAG-PB codec as an ArrayBuffer
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const buf = await res.arrayBuffer()

console.info(buf) // ArrayBuffer { [Uint8Contents]: < ... >, byteLength: x } +
+
Using the DAG-PB codec as a stream
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://Qmfoo')
const reader = res.body?.getReader()

if (reader == null) {
throw new Error('Could not create reader from response body')
}

while (true) {
const next = await reader.read()

if (next?.done === true) {
break
}

if (next?.value != null) {
console.info(next.value) // Uint8Array(x) [ ... ]
}
} +
+
Content-Type

When fetching DAG-PB data, the content type will be set to application/octet-stream unless a custom content-type parser is configured.

+

JSON

The JSON codec is a very simple codec, a block parseable with this codec is a JSON string encoded into a Uint8Array.

+
Using the JSON codec
import * as json from 'multiformats/codecs/json'

const block = new TextEncoder().encode('{ "hello": "world" }')
const obj = json.decode(block)

console.info(obj) // { hello: 'world' } +
+
Content-Type

When the JSON codec is encountered, the Content-Type header of the response will be set to application/json.

+

DAG-JSON

DAG-JSON expands on the JSON codec, adding the ability to contain CIDs which act as links to other blocks, and byte arrays.

+

CIDs and byte arrays are represented using special object structures with a single "/" property.

+

Using DAG-JSON has two important caveats:

+
    +
  1. Your JSON structure cannot contain an object with only a "/" property, as it will be interpreted as a special type.
  2. +
  3. Since JSON has no technical limit on number sizes, DAG-JSON also allows numbers larger than Number.MAX_SAFE_INTEGER. JavaScript requires use of BigInts to represent numbers larger than this, and JSON.parse does not support them, so precision will be lost.
  4. +
+

Otherwise this codec follows the same rules as the JSON codec.

+
Using the DAG-JSON codec
import * as dagJson from '@ipld/dag-json'

const block = new TextEncoder().encode(`{
"hello": "world",
"cid": {
"/": "baeaaac3imvwgy3zao5xxe3de"
},
"buf": {
"/": {
"bytes": "AAECAwQ"
}
}
}`)

const obj = dagJson.decode(block)

console.info(obj)
// {
// hello: 'world',
// cid: CID(baeaaac3imvwgy3zao5xxe3de),
// buf: Uint8Array(5) [ 0, 1, 2, 3, 4 ]
// } +
+
Content-Type

When the DAG-JSON codec is encountered in the requested CID, the Content-Type header of the response will be set to application/json.

+

DAG-JSON data can be parsed from the response by using the .json() function, which will return CIDs/byte arrays as plain { "/": ... } objects:

+
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagJson from '@ipld/dag-json'

const res = await verifiedFetch('ipfs://bafyDAGJSON')

// either:
const obj = await res.json()
console.info(obj.cid) // { "/": "baeaaac3imvwgy3zao5xxe3de" }
console.info(obj.buf) // { "/": { "bytes": "AAECAwQ" } } +
+

Alternatively, it can be decoded using the @ipld/dag-json module and the .arrayBuffer() method, in which case you will get CID objects and Uint8Arrays:

+
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagJson from '@ipld/dag-json'

const res = await verifiedFetch('ipfs://bafyDAGJSON')

// or:
const obj = dagJson.decode<any>(await res.arrayBuffer())
console.info(obj.cid) // CID(baeaaac3imvwgy3zao5xxe3de)
console.info(obj.buf) // Uint8Array(5) [ 0, 1, 2, 3, 4 ] +
+

DAG-CBOR

DAG-CBOR uses the Concise Binary Object Representation format for serialization instead of JSON.

+

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.

+
Content-Type

Not all data types supported by DAG-CBOR can be successfully turned into JSON and back into the same binary form.

+

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.

+

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().

+
Detecting JSON-safe DAG-CBOR

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.

+
import { verifiedFetch } from '@helia/verified-fetch'
import * as dagCbor from '@ipld/dag-cbor'

const res = await verifiedFetch('ipfs://bafyDagCborCID')
let obj

if (res.headers.get('Content-Type') === 'application/json') {
// DAG-CBOR data can be safely decoded as JSON
obj = await res.json()
} else {
// response contains non-JSON friendly data types
obj = dagCbor.decode(await res.arrayBuffer())
}

console.info(obj) // ... +
+

The Accept header

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.

+

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 response will be returned:

+
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyJPEGImageCID', {
headers: {
accept: 'image/png'
}
})

console.info(res.status) // 406 - the image was a JPEG but we specified PNG as the accept header +
+

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:

+
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyDAGCBORCID', {
headers: {
accept: 'application/octet-stream'
}
})

console.info(res.headers.get('accept')) // application/octet-stream
const buf = await res.arrayBuffer() // raw bytes, not processed as JSON +
+

Redirects

If a requested URL contains a path component, that path component resolves to +a UnixFS directory, but the URL does not have a trailing slash, one will be +added to form a canonical URL for that resource, otherwise the request will +be resolved as normal.

+
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir')

console.info(res.url) // ipfs://bafyfoo/path/to/dir/ +
+

It's possible to prevent this behaviour and/or handle a redirect manually +through use of the redirect +option.

+

Example - Redirect: follow

This is the default value and is what happens if no value is specified.

+
import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'follow'
})

console.info(res.status) // 200
console.info(res.url) // ipfs://bafyfoo/path/to/dir/
console.info(res.redirected) // true +
+

Example - Redirect: error

This causes a TypeError to be thrown if a URL would cause a redirect.

+

import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'error'
})
// throw TypeError('Failed to fetch') +
+

Example - Redirect: manual

Manual redirects allow the user to process the redirect. A 301 +is returned, and the location to redirect to is available as the "location" +response header.

+

This differs slightly from HTTP fetch which returns an opaque response as the +browser itself is expected to process the redirect and hide all details from +the user.

+

import { verifiedFetch } from '@helia/verified-fetch'

const res = await verifiedFetch('ipfs://bafyfoo/path/to/dir', {
redirect: 'manual'
})

console.info(res.status) // 301
console.info(res.url) // ipfs://bafyfoo/path/to/dir
console.info(res.redirected) // false
console.info(res.headers.get('location')) // ipfs://bafyfoo/path/to/dir/ +
+

Comparison to fetch

This module attempts to act as similarly to the fetch() API as possible.

+

The fetch() API takes two parameters:

+
    +
  1. A resource
  2. +
  3. An options object
  4. +
+

Resource argument

This library supports the following methods of fetching web3 content from IPFS:

+
    +
  1. IPFS protocol: ipfs://<cidv0> & ipfs://<cidv1>
  2. +
  3. IPNS protocol: ipns://<peerId> & ipns://<publicKey> & ipns://<hostUri_Supporting_DnsLink_TxtRecords>
  4. +
  5. CID instances: An actual CID instance CID.parse('bafy...')
  6. +
+

As well as support for pathing & params for items 1 & 2 above according to IPFS - Path Gateway Specification & IPFS - Trustless Gateway Specification. Further refinement of those specifications specifically for web-based scenarios can be found in the Web Pathing Specification IPIP.

+

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.

+

Options argument

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 related to specifying the resultant shape of desired content.

+

Some of those header specifications are:

+
    +
  1. https://specs.ipfs.tech/http-gateways/path-gateway/#request-headers
  2. +
  3. https://specs.ipfs.tech/http-gateways/trustless-gateway/#request-headers
  4. +
  5. https://specs.ipfs.tech/http-gateways/subdomain-gateway/#request-headers
  6. +
+

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.

+

Known Fetch API options that will be supported:

+
    +
  1. signal - An AbortSignal that a user can use to abort the request.
  2. +
  3. 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 parameter.
  4. +
  5. headers - An object of headers to be sent with the request. Best effort to adhere to the Fetch API headers parameter. +
  6. +
  7. 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 parameter.
  8. +
  9. body - An object that specifies the body of the request. Best effort to adhere to the Fetch API body parameter.
  10. +
  11. cache - Will basically act as force-cache for the request. Best effort to adhere to the Fetch API cache parameter.
  12. +
+

Non-Fetch API options that will be supported:

+
    +
  1. onProgress - Similar to Helia onProgress options, this will be a function that will be called with a progress event. Supported progress events are:
      +
    • helia:verified-fetch:error - An error occurred during the request.
    • +
    • helia:verified-fetch:request:start - The request has been sent
    • +
    • helia:verified-fetch:request:complete - The request has been sent
    • +
    • helia:verified-fetch:request:error - An error occurred during the request.
    • +
    • helia:verified-fetch:request:abort - The request was aborted prior to completion.
    • +
    • helia:verified-fetch:response:start - The initial HTTP Response headers have been set, and response stream is started.
    • +
    • helia:verified-fetch:response:complete - The response stream has completed.
    • +
    • helia:verified-fetch:response:error - An error occurred while building the response.
    • +
    +
  2. +
+

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:

+
    +
  1. IPIP-0412: Signaling Block Order in CARs on HTTP Gateways
  2. +
  3. IPIP-0402: Partial CAR Support on Trustless Gateways
  4. +
  5. IPIP-0386: Subdomain Gateway Interop with _redirects
  6. +
  7. IPIP-0328: JSON and CBOR Response Formats on HTTP Gateways
  8. +
  9. IPIP-0288: TAR Response Format on HTTP Gateways
  10. +
+

Response types

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.

+

All content we retrieve from the IPFS network is obtained via an AsyncIterable, and will be set as the body of the HTTP Response via a ReadableStream 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.

+

If your content doesn't have a mime-type or an IPFS spec, this library will not support it, but you can use the helia library directly for those use cases. See Unsupported response types for more information.

+

Handling response types

For handling responses we want to follow conventions/abstractions from Fetch API where possible:

+
    +
  • 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.
  • +
  • For images (or other web-relevant asset) you want to add to the DOM, use .blob() or .arrayBuffer() to get the raw bytes.
  • +
  • For plain text in utf-8, you would call .text()
  • +
  • For streaming response data, use something like response.body.getReader() to get a ReadableStream.
  • +
+

Unsupported response types

    +
  • 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. Instead, users should request aplication/vnd.ipld.car or use the helia library directly for this use case.
  • +
  • Others? Open an issue or PR!
  • +
+

Response headers

This library will set the HTTP Response headers to the appropriate values for the content type according to the appropriate IPFS Specifications.

+

Some known header specifications:

+ +

Possible Scenarios that could cause confusion

Attempting to fetch the CID for content that does not make sense

If you request bafybeiaysi4s6lnjev27ln5icwm6tueaw2vdykrtjkwiphwekaywqhcjze, which points to the root of the en.wikipedia.org mirror, a response object does not make sense.

+

Errors

Known Errors that can be thrown:

+
    +
  1. TypeError - If the resource argument is not a string, CID, or CID string.
  2. +
  3. TypeError - If the options argument is passed and not an object.
  4. +
  5. TypeError - If the options argument is passed and is malformed.
  6. +
  7. AbortError - If the content request is aborted due to user aborting provided AbortSignal. Note that this is a AbortError from @libp2p/interface and not the standard AbortError from the Fetch API.
  8. +
+

Install

$ npm i @helia/verified-fetch
+
+

Browser <script> tag

Loading this module through a script tag will make it's exports available as HeliaVerifiedFetch in the global namespace.

+
<script src="https://unpkg.com/@helia/verified-fetch/dist/index.min.js"></script>
+
+

API Docs

+

License

Licensed under either of

+ +

Contribute

Contributions welcome! Please check out the issues.

+

Also see our contributing document for more information on how we work, and about contributing in general.

+

Please be aware that all interactions related to this repo are subject to the IPFS Code of Conduct.

+

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

+

+

Index

Interfaces

Type Aliases

Functions

\ No newline at end of file diff --git a/modules/_helia_verified_fetch_gateway_conformance.html b/modules/_helia_verified_fetch_gateway_conformance.html new file mode 100644 index 00000000..fd952559 --- /dev/null +++ b/modules/_helia_verified_fetch_gateway_conformance.html @@ -0,0 +1,32 @@ +@helia/verified-fetch-gateway-conformance | Helia Verified Fetch

Module @helia/verified-fetch-gateway-conformance

+ + Helia logo + +

+ +

@helia/verified-fetch-gateway-conformance

ipfs.tech +Discuss +codecov +CI

+
+

Gateway Conformance tests for @helia/verified-fetch

+
+

About

Runs Gateway Conformance tests against @helia/verified-fetch using Kubo as a backing trustless-gateway.

+

Example - Testing a new Kubo release

$ npm i @helia/verified-fetch-gateway-conformance
$ KUBO_BINARY=/path/to/kubo verified-fetch-gateway-conformance +
+

Install

$ npm i @helia/verified-fetch-gateway-conformance
+
+

Browser <script> tag

Loading this module through a script tag will make it's exports available as HeliaInterop in the global namespace.

+
<script src="https://unpkg.com/@helia/verified-fetch-gateway-conformance/dist/index.min.js"></script>
+
+

License

Licensed under either of

+ +

Contribute

Contributions welcome! Please check out the issues.

+

Also see our contributing document for more information on how we work, and about contributing in general.

+

Please be aware that all interactions related to this repo are subject to the IPFS Code of Conduct.

+

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

+

+
\ No newline at end of file diff --git a/types/BubbledProgressEvents.html b/types/BubbledProgressEvents.html deleted file mode 100644 index ef18d7b0..00000000 --- a/types/BubbledProgressEvents.html +++ /dev/null @@ -1 +0,0 @@ -BubbledProgressEvents | @helia/verified-fetch
\ No newline at end of file diff --git a/types/VerifiedFetchProgressEvents.html b/types/VerifiedFetchProgressEvents.html deleted file mode 100644 index 7e14f651..00000000 --- a/types/VerifiedFetchProgressEvents.html +++ /dev/null @@ -1 +0,0 @@ -VerifiedFetchProgressEvents | @helia/verified-fetch

Type alias VerifiedFetchProgressEvents

VerifiedFetchProgressEvents: ProgressEvent<"verified-fetch:request:start", CIDDetail> | ProgressEvent<"verified-fetch:request:info", string> | ProgressEvent<"verified-fetch:request:progress:chunk", CIDDetail> | ProgressEvent<"verified-fetch:request:end", CIDDetail> | ProgressEvent<"verified-fetch:request:error", CIDDetailError>
\ No newline at end of file diff --git a/types/_helia_verified_fetch.BubbledProgressEvents.html b/types/_helia_verified_fetch.BubbledProgressEvents.html new file mode 100644 index 00000000..9179fc4d --- /dev/null +++ b/types/_helia_verified_fetch.BubbledProgressEvents.html @@ -0,0 +1 @@ +BubbledProgressEvents | Helia Verified Fetch
\ No newline at end of file diff --git a/types/Resource.html b/types/_helia_verified_fetch.Resource.html similarity index 50% rename from types/Resource.html rename to types/_helia_verified_fetch.Resource.html index 8804262f..5525d6e2 100644 --- a/types/Resource.html +++ b/types/_helia_verified_fetch.Resource.html @@ -1,2 +1,2 @@ -Resource | @helia/verified-fetch
Resource: string | CID

The types for the first argument of the verifiedFetch function.

-
\ No newline at end of file +Resource | Helia Verified Fetch
Resource: string | CID

The types for the first argument of the verifiedFetch function.

+
\ No newline at end of file diff --git a/types/_helia_verified_fetch.VerifiedFetchProgressEvents.html b/types/_helia_verified_fetch.VerifiedFetchProgressEvents.html new file mode 100644 index 00000000..cfefee9d --- /dev/null +++ b/types/_helia_verified_fetch.VerifiedFetchProgressEvents.html @@ -0,0 +1 @@ +VerifiedFetchProgressEvents | Helia Verified Fetch
VerifiedFetchProgressEvents: ProgressEvent<"verified-fetch:request:start", CIDDetail> | ProgressEvent<"verified-fetch:request:info", string> | ProgressEvent<"verified-fetch:request:progress:chunk", CIDDetail> | ProgressEvent<"verified-fetch:request:end", CIDDetail> | ProgressEvent<"verified-fetch:request:error", CIDDetailError>
\ No newline at end of file