@helia/verified-fetch 0.0.0-9b1ddf8 → 0.0.0-a04e041
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +238 -6
- package/dist/index.min.js +4 -4
- package/dist/src/index.d.ts +222 -4
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +219 -4
- package/dist/src/index.js.map +1 -1
- package/dist/src/types.d.ts +2 -0
- package/dist/src/types.d.ts.map +1 -0
- package/dist/src/types.js +2 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/utils/dag-cbor-to-safe-json.d.ts +7 -0
- package/dist/src/utils/dag-cbor-to-safe-json.d.ts.map +1 -0
- package/dist/src/utils/dag-cbor-to-safe-json.js +37 -0
- package/dist/src/utils/dag-cbor-to-safe-json.js.map +1 -0
- package/dist/src/utils/get-content-disposition-filename.d.ts +6 -0
- package/dist/src/utils/get-content-disposition-filename.d.ts.map +1 -0
- package/dist/src/utils/get-content-disposition-filename.js +16 -0
- package/dist/src/utils/get-content-disposition-filename.js.map +1 -0
- package/dist/src/utils/get-e-tag.d.ts +28 -0
- package/dist/src/utils/get-e-tag.d.ts.map +1 -0
- package/dist/src/utils/get-e-tag.js +18 -0
- package/dist/src/utils/get-e-tag.js.map +1 -0
- package/dist/src/utils/parse-url-string.d.ts +7 -1
- package/dist/src/utils/parse-url-string.d.ts.map +1 -1
- package/dist/src/utils/parse-url-string.js +6 -0
- package/dist/src/utils/parse-url-string.js.map +1 -1
- package/dist/src/utils/responses.d.ts +4 -0
- package/dist/src/utils/responses.d.ts.map +1 -0
- package/dist/src/utils/responses.js +21 -0
- package/dist/src/utils/responses.js.map +1 -0
- package/dist/src/utils/select-output-type.d.ts +12 -0
- package/dist/src/utils/select-output-type.d.ts.map +1 -0
- package/dist/src/utils/select-output-type.js +147 -0
- package/dist/src/utils/select-output-type.js.map +1 -0
- package/dist/src/verified-fetch.d.ts +17 -25
- package/dist/src/verified-fetch.d.ts.map +1 -1
- package/dist/src/verified-fetch.js +225 -142
- package/dist/src/verified-fetch.js.map +1 -1
- package/package.json +27 -15
- package/src/index.ts +223 -4
- package/src/types.ts +1 -0
- package/src/utils/dag-cbor-to-safe-json.ts +44 -0
- package/src/utils/get-content-disposition-filename.ts +18 -0
- package/src/utils/get-e-tag.ts +36 -0
- package/src/utils/parse-url-string.ts +17 -2
- package/src/utils/responses.ts +22 -0
- package/src/utils/select-output-type.ts +166 -0
- package/src/verified-fetch.ts +258 -152
package/src/index.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* `@helia/verified-fetch` provides a [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)-like API for retrieving content from the [IPFS](https://ipfs.tech/) network.
|
|
5
5
|
*
|
|
6
|
-
* All content is retrieved in a [trustless manner](https://www.techopedia.com/definition/trustless), and the integrity of all bytes are verified by comparing hashes of the data.
|
|
6
|
+
* All content is retrieved in a [trustless manner](https://www.techopedia.com/definition/trustless), and the integrity of all bytes are verified by comparing hashes of the data. By default, CIDs are retrieved over HTTP from [trustless gateways](https://specs.ipfs.tech/http-gateways/trustless-gateway/).
|
|
7
7
|
*
|
|
8
8
|
* This is a marked improvement over `fetch` which offers no such protections and is vulnerable to all sorts of attacks like [Content Spoofing](https://owasp.org/www-community/attacks/Content_Spoofing), [DNS Hijacking](https://en.wikipedia.org/wiki/DNS_hijacking), etc.
|
|
9
9
|
*
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
34
34
|
* import { CID } from 'multiformats/cid'
|
|
35
35
|
*
|
|
36
|
-
* const cid = CID.parse('bafyFoo') // some
|
|
36
|
+
* const cid = CID.parse('bafyFoo') // some json file
|
|
37
37
|
* const response = await verifiedFetch(cid)
|
|
38
38
|
* const json = await response.json()
|
|
39
39
|
* ```
|
|
@@ -114,7 +114,7 @@
|
|
|
114
114
|
*
|
|
115
115
|
* ### Custom content-type parsing
|
|
116
116
|
*
|
|
117
|
-
* By default, `@helia/verified-fetch` sets the `Content-Type` header as `application/octet-stream` - this is because the `.json()`, `.text()`, `.blob()`, and `.arrayBuffer()` methods will usually work as expected without a detailed content type.
|
|
117
|
+
* 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.
|
|
118
118
|
*
|
|
119
119
|
* If you require an accurate content-type you can provide a `contentTypeParser` function as an option to `createVerifiedFetch` to handle parsing the content type.
|
|
120
120
|
*
|
|
@@ -138,6 +138,221 @@
|
|
|
138
138
|
* })
|
|
139
139
|
* ```
|
|
140
140
|
*
|
|
141
|
+
* ### IPLD codec handling
|
|
142
|
+
*
|
|
143
|
+
* 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.
|
|
144
|
+
*
|
|
145
|
+
* #### DAG-PB
|
|
146
|
+
*
|
|
147
|
+
* [DAG-PB](https://ipld.io/docs/codecs/known/dag-pb/) is the codec we are most likely to encounter, it is what [UnixFS](https://github.com/ipfs/specs/blob/main/UNIXFS.md) uses under the hood.
|
|
148
|
+
*
|
|
149
|
+
* ##### Using the DAG-PB codec as a Blob
|
|
150
|
+
*
|
|
151
|
+
* ```typescript
|
|
152
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
153
|
+
*
|
|
154
|
+
* const res = await verifiedFetch('ipfs://Qmfoo')
|
|
155
|
+
* const blob = await res.blob()
|
|
156
|
+
*
|
|
157
|
+
* console.info(blob) // Blob { size: x, type: 'application/octet-stream' }
|
|
158
|
+
* ```
|
|
159
|
+
*
|
|
160
|
+
* ##### Using the DAG-PB codec as an ArrayBuffer
|
|
161
|
+
*
|
|
162
|
+
* ```typescript
|
|
163
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
164
|
+
*
|
|
165
|
+
* const res = await verifiedFetch('ipfs://Qmfoo')
|
|
166
|
+
* const buf = await res.arrayBuffer()
|
|
167
|
+
*
|
|
168
|
+
* console.info(buf) // ArrayBuffer { [Uint8Contents]: < ... >, byteLength: x }
|
|
169
|
+
* ```
|
|
170
|
+
*
|
|
171
|
+
* ##### Using the DAG-PB codec as a stream
|
|
172
|
+
*
|
|
173
|
+
* ```typescript
|
|
174
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
175
|
+
*
|
|
176
|
+
* const res = await verifiedFetch('ipfs://Qmfoo')
|
|
177
|
+
* const reader = res.body?.getReader()
|
|
178
|
+
*
|
|
179
|
+
* while (true) {
|
|
180
|
+
* const next = await reader.read()
|
|
181
|
+
*
|
|
182
|
+
* if (next?.done === true) {
|
|
183
|
+
* break
|
|
184
|
+
* }
|
|
185
|
+
*
|
|
186
|
+
* if (next?.value != null) {
|
|
187
|
+
* console.info(next.value) // Uint8Array(x) [ ... ]
|
|
188
|
+
* }
|
|
189
|
+
* }
|
|
190
|
+
* ```
|
|
191
|
+
*
|
|
192
|
+
* ##### Content-Type
|
|
193
|
+
*
|
|
194
|
+
* When fetching `DAG-PB` data, the content type will be set to `application/octet-stream` unless a custom content-type parser is configured.
|
|
195
|
+
*
|
|
196
|
+
* #### JSON
|
|
197
|
+
*
|
|
198
|
+
* The JSON codec is a very simple codec, a block parseable with this codec is a JSON string encoded into a `Uint8Array`.
|
|
199
|
+
*
|
|
200
|
+
* ##### Using the JSON codec
|
|
201
|
+
*
|
|
202
|
+
* ```typescript
|
|
203
|
+
* import * as json from 'multiformats/codecs/json'
|
|
204
|
+
*
|
|
205
|
+
* const block = new TextEncoder().encode('{ "hello": "world" }')
|
|
206
|
+
* const obj = json.decode(block)
|
|
207
|
+
*
|
|
208
|
+
* console.info(obj) // { hello: 'world' }
|
|
209
|
+
* ```
|
|
210
|
+
*
|
|
211
|
+
* ##### Content-Type
|
|
212
|
+
*
|
|
213
|
+
* When the `JSON` codec is encountered, the `Content-Type` header of the response will be set to `application/json`.
|
|
214
|
+
*
|
|
215
|
+
* ### DAG-JSON
|
|
216
|
+
*
|
|
217
|
+
* [DAG-JSON](https://ipld.io/docs/codecs/known/dag-json/) expands on the `JSON` codec, adding the ability to contain [CID](https://docs.ipfs.tech/concepts/content-addressing/)s which act as links to other blocks, and byte arrays.
|
|
218
|
+
*
|
|
219
|
+
* `CID`s and byte arrays are represented using special object structures with a single `"/"` property.
|
|
220
|
+
*
|
|
221
|
+
* Using `DAG-JSON` has two important caveats:
|
|
222
|
+
*
|
|
223
|
+
* 1. Your `JSON` structure cannot contain an object with only a `"/"` property, as it will be interpreted as a special type.
|
|
224
|
+
* 2. Since `JSON` has no technical limit on number sizes, `DAG-JSON` also allows numbers larger than `Number.MAX_SAFE_INTEGER`. JavaScript requires use of `BigInt`s to represent numbers larger than this, and `JSON.parse` does not support them, so precision will be lost.
|
|
225
|
+
*
|
|
226
|
+
* Otherwise this codec follows the same rules as the `JSON` codec.
|
|
227
|
+
*
|
|
228
|
+
* ##### Using the DAG-JSON codec
|
|
229
|
+
*
|
|
230
|
+
* ```typescript
|
|
231
|
+
* import * as dagJson from '@ipld/dag-json'
|
|
232
|
+
*
|
|
233
|
+
* const block = new TextEncoder().encode(`{
|
|
234
|
+
* "hello": "world",
|
|
235
|
+
* "cid": {
|
|
236
|
+
* "/": "baeaaac3imvwgy3zao5xxe3de"
|
|
237
|
+
* },
|
|
238
|
+
* "buf": {
|
|
239
|
+
* "/": {
|
|
240
|
+
* "bytes": "AAECAwQ"
|
|
241
|
+
* }
|
|
242
|
+
* }
|
|
243
|
+
* }`)
|
|
244
|
+
*
|
|
245
|
+
* const obj = dagJson.decode(block)
|
|
246
|
+
*
|
|
247
|
+
* console.info(obj)
|
|
248
|
+
* // {
|
|
249
|
+
* // hello: 'world',
|
|
250
|
+
* // cid: CID(baeaaac3imvwgy3zao5xxe3de),
|
|
251
|
+
* // buf: Uint8Array(5) [ 0, 1, 2, 3, 4 ]
|
|
252
|
+
* // }
|
|
253
|
+
* ```
|
|
254
|
+
*
|
|
255
|
+
* ##### Content-Type
|
|
256
|
+
*
|
|
257
|
+
* When the `DAG-JSON` codec is encountered in the requested CID, the `Content-Type` header of the response will be set to `application/json`.
|
|
258
|
+
*
|
|
259
|
+
* `DAG-JSON` data can be parsed from the response by using the `.json()` function, which will return `CID`s/byte arrays as plain `{ "/": ... }` objects:
|
|
260
|
+
*
|
|
261
|
+
* ```typescript
|
|
262
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
263
|
+
* import * as dagJson from '@ipld/dag-json'
|
|
264
|
+
*
|
|
265
|
+
* const res = await verifiedFetch('ipfs://bafyDAGJSON')
|
|
266
|
+
*
|
|
267
|
+
* // either:
|
|
268
|
+
* const obj = await res.json()
|
|
269
|
+
* console.info(obj.cid) // { "/": "baeaaac3imvwgy3zao5xxe3de" }
|
|
270
|
+
* console.info(obj.buf) // { "/": { "bytes": "AAECAwQ" } }
|
|
271
|
+
* ```
|
|
272
|
+
*
|
|
273
|
+
* Alternatively, it can be decoded using the `@ipld/dag-json` module and the `.arrayBuffer()` method, in which case you will get `CID` objects and `Uint8Array`s:
|
|
274
|
+
*
|
|
275
|
+
*```typescript
|
|
276
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
277
|
+
* import * as dagJson from '@ipld/dag-json'
|
|
278
|
+
*
|
|
279
|
+
* const res = await verifiedFetch('ipfs://bafyDAGJSON')
|
|
280
|
+
*
|
|
281
|
+
* // or:
|
|
282
|
+
* const obj = dagJson.decode(await res.arrayBuffer())
|
|
283
|
+
* console.info(obj.cid) // CID(baeaaac3imvwgy3zao5xxe3de)
|
|
284
|
+
* console.info(obj.buf) // Uint8Array(5) [ 0, 1, 2, 3, 4 ]
|
|
285
|
+
* ```
|
|
286
|
+
*
|
|
287
|
+
* #### DAG-CBOR
|
|
288
|
+
*
|
|
289
|
+
* [DAG-CBOR](https://ipld.io/docs/codecs/known/dag-cbor/) uses the [Concise Binary Object Representation](https://cbor.io/) format for serialization instead of JSON.
|
|
290
|
+
*
|
|
291
|
+
* 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.
|
|
292
|
+
*
|
|
293
|
+
* ##### Content-Type
|
|
294
|
+
*
|
|
295
|
+
* Not all data types supported by `DAG-CBOR` can be successfully turned into JSON and back into the same binary form.
|
|
296
|
+
*
|
|
297
|
+
* 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.
|
|
298
|
+
*
|
|
299
|
+
* 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()`.
|
|
300
|
+
*
|
|
301
|
+
* ##### Detecting JSON-safe DAG-CBOR
|
|
302
|
+
*
|
|
303
|
+
* 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.
|
|
304
|
+
*
|
|
305
|
+
* ```typescript
|
|
306
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
307
|
+
* import * as dagCbor from '@ipld/dag-cbor'
|
|
308
|
+
*
|
|
309
|
+
* const res = await verifiedFetch('ipfs://bafyDagCborCID')
|
|
310
|
+
* let obj
|
|
311
|
+
*
|
|
312
|
+
* if (res.headers.get('Content-Type') === 'application/json') {
|
|
313
|
+
* // DAG-CBOR data can be safely decoded as JSON
|
|
314
|
+
* obj = await res.json()
|
|
315
|
+
* } else {
|
|
316
|
+
* // response contains non-JSON friendly data types
|
|
317
|
+
* obj = dagCbor.decode(await res.arrayBuffer())
|
|
318
|
+
* }
|
|
319
|
+
*
|
|
320
|
+
* console.info(obj) // ...
|
|
321
|
+
* ```
|
|
322
|
+
*
|
|
323
|
+
* ## The `Accept` header
|
|
324
|
+
*
|
|
325
|
+
* 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.
|
|
326
|
+
*
|
|
327
|
+
* If the final `Content-Type` does not match the `Accept` header, or if the content cannot be represented in the format dictated by the `Accept` header, or you have configured a custom content type parser, and that parser returns a value that isn't in the accept header, a [406: Not Acceptable](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/406) response will be returned:
|
|
328
|
+
*
|
|
329
|
+
* ```typescript
|
|
330
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
331
|
+
*
|
|
332
|
+
* const res = await verifiedFetch('ipfs://bafyJPEGImageCID', {
|
|
333
|
+
* headers: {
|
|
334
|
+
* accept: 'image/png'
|
|
335
|
+
* }
|
|
336
|
+
* })
|
|
337
|
+
*
|
|
338
|
+
* console.info(res.status) // 406 - the image was a JPEG but we specified PNG as the accept header
|
|
339
|
+
* ```
|
|
340
|
+
*
|
|
341
|
+
* 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:
|
|
342
|
+
*
|
|
343
|
+
* ```typescript
|
|
344
|
+
* import { verifiedFetch } from '@helia/verified-fetch'
|
|
345
|
+
*
|
|
346
|
+
* const res = await verifiedFetch('ipfs://bafyDAGCBORCID', {
|
|
347
|
+
* headers: {
|
|
348
|
+
* accept: 'application/octet-stream'
|
|
349
|
+
* }
|
|
350
|
+
* })
|
|
351
|
+
*
|
|
352
|
+
* console.info(res.headers.get('accept')) // application/octet-stream
|
|
353
|
+
* const buf = await res.arrayBuffer() // raw bytes, not processed as JSON
|
|
354
|
+
* ```
|
|
355
|
+
*
|
|
141
356
|
* ## Comparison to fetch
|
|
142
357
|
*
|
|
143
358
|
* This module attempts to act as similarly to the `fetch()` API as possible.
|
|
@@ -155,7 +370,7 @@
|
|
|
155
370
|
* 2. IPNS protocol: `ipns://<peerId>` & `ipns://<publicKey>` & `ipns://<hostUri_Supporting_DnsLink_TxtRecords>`
|
|
156
371
|
* 3. CID instances: An actual CID instance `CID.parse('bafy...')`
|
|
157
372
|
*
|
|
158
|
-
* As well as support for pathing & params for
|
|
373
|
+
* As well as support for pathing & params for items 1 & 2 above according to [IPFS - Path Gateway Specification](https://specs.ipfs.tech/http-gateways/path-gateway) & [IPFS - Trustless Gateway Specification](https://specs.ipfs.tech/http-gateways/trustless-gateway/). Further refinement of those specifications specifically for web-based scenarios can be found in the [Web Pathing Specification IPIP](https://github.com/ipfs/specs/pull/453).
|
|
159
374
|
*
|
|
160
375
|
* If you pass a CID instance, it assumes you want the content for that specific CID only, and does not support pathing or params for that CID.
|
|
161
376
|
*
|
|
@@ -267,6 +482,10 @@ import type { ProgressEvent, ProgressOptions } from 'progress-events'
|
|
|
267
482
|
*/
|
|
268
483
|
export type Resource = string | CID
|
|
269
484
|
|
|
485
|
+
export interface ResourceDetail {
|
|
486
|
+
resource: Resource
|
|
487
|
+
}
|
|
488
|
+
|
|
270
489
|
export interface CIDDetail {
|
|
271
490
|
cid: CID
|
|
272
491
|
path: string
|
package/src/types.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type RequestFormatShorthand = 'raw' | 'car' | 'tar' | 'ipns-record' | 'dag-json' | 'dag-cbor' | 'json' | 'cbor'
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { decode } from 'cborg'
|
|
2
|
+
import { encode } from 'cborg/json'
|
|
3
|
+
import { CID } from 'multiformats/cid'
|
|
4
|
+
import type { TagDecoder } from 'cborg'
|
|
5
|
+
|
|
6
|
+
// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
|
|
7
|
+
const CID_CBOR_TAG = 0x2A
|
|
8
|
+
|
|
9
|
+
function cidDecoder (bytes: Uint8Array): CID {
|
|
10
|
+
if (bytes[0] !== 0) {
|
|
11
|
+
throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
return CID.decode(bytes.subarray(1)) // ignore leading 0x00
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Take a `DAG-CBOR` encoded `Uint8Array`, deserialize it as an object and
|
|
19
|
+
* re-serialize it in a form that can be passed to `JSON.serialize` and then
|
|
20
|
+
* `JSON.parse` without losing any data.
|
|
21
|
+
*/
|
|
22
|
+
export function dagCborToSafeJSON (buf: Uint8Array): string {
|
|
23
|
+
const tags: TagDecoder[] = []
|
|
24
|
+
tags[CID_CBOR_TAG] = cidDecoder
|
|
25
|
+
|
|
26
|
+
const obj = decode(buf, {
|
|
27
|
+
allowIndefinite: false,
|
|
28
|
+
coerceUndefinedToNull: true,
|
|
29
|
+
allowNaN: false,
|
|
30
|
+
allowInfinity: false,
|
|
31
|
+
strict: true,
|
|
32
|
+
useMaps: false,
|
|
33
|
+
rejectDuplicateMapKeys: true,
|
|
34
|
+
tags,
|
|
35
|
+
|
|
36
|
+
// this is different to `DAG-CBOR` - the reason we disallow BigInts is
|
|
37
|
+
// because we are about to re-encode to `JSON` which does not support
|
|
38
|
+
// BigInts. Blocks containing large numbers should be deserialized using a
|
|
39
|
+
// cbor decoder instead
|
|
40
|
+
allowBigInt: false
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
return new TextDecoder().decode(encode(obj))
|
|
44
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Takes a filename URL param and returns a string for use in a
|
|
3
|
+
* `Content-Disposition` header
|
|
4
|
+
*/
|
|
5
|
+
export function getContentDispositionFilename (filename: string): string {
|
|
6
|
+
const asciiOnly = replaceNonAsciiCharacters(filename)
|
|
7
|
+
|
|
8
|
+
if (asciiOnly === filename) {
|
|
9
|
+
return `filename="${filename}"`
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
return `filename="${asciiOnly}"; filename*=UTF-8''${encodeURIComponent(filename)}`
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function replaceNonAsciiCharacters (filename: string): string {
|
|
16
|
+
// eslint-disable-next-line no-control-regex
|
|
17
|
+
return filename.replace(/[^\x00-\x7F]/g, '_')
|
|
18
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { RequestFormatShorthand } from '../types.js'
|
|
2
|
+
import type { CID } from 'multiformats/cid'
|
|
3
|
+
|
|
4
|
+
interface GetETagArg {
|
|
5
|
+
cid: CID
|
|
6
|
+
reqFormat?: RequestFormatShorthand
|
|
7
|
+
rangeStart?: number
|
|
8
|
+
rangeEnd?: number
|
|
9
|
+
/**
|
|
10
|
+
* Weak Etag is used when we can't guarantee byte-for-byte-determinism (generated, or mutable content).
|
|
11
|
+
* Some examples:
|
|
12
|
+
* - IPNS requests
|
|
13
|
+
* - CAR streamed with blocks in non-deterministic order
|
|
14
|
+
* - TAR streamed with files in non-deterministic order
|
|
15
|
+
*/
|
|
16
|
+
weak?: boolean
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* etag
|
|
21
|
+
* you need to wrap cid with ""
|
|
22
|
+
* we use strong Etags for immutable responses and weak one (prefixed with W/ ) for mutable/generated ones (ipns and generated HTML).
|
|
23
|
+
* block and car responses should have different etag than deserialized one, so you can add some prefix like we do in existing gateway
|
|
24
|
+
*
|
|
25
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
|
|
26
|
+
* @see https://specs.ipfs.tech/http-gateways/path-gateway/#etag-response-header
|
|
27
|
+
*/
|
|
28
|
+
export function getETag ({ cid, reqFormat, weak, rangeStart, rangeEnd }: GetETagArg): string {
|
|
29
|
+
const prefix = weak === true ? 'W/' : ''
|
|
30
|
+
let suffix = reqFormat == null ? '' : `.${reqFormat}`
|
|
31
|
+
if (rangeStart != null || rangeEnd != null) {
|
|
32
|
+
suffix += `.${rangeStart ?? '0'}-${rangeEnd ?? 'N'}`
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return `${prefix}"${cid.toString()}${suffix}"`
|
|
36
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { peerIdFromString } from '@libp2p/peer-id'
|
|
2
2
|
import { CID } from 'multiformats/cid'
|
|
3
3
|
import { TLRU } from './tlru.js'
|
|
4
|
+
import type { RequestFormatShorthand } from '../types.js'
|
|
4
5
|
import type { IPNS, IPNSRoutingEvents, ResolveDnsLinkProgressEvents, ResolveProgressEvents, ResolveResult } from '@helia/ipns'
|
|
5
6
|
import type { ComponentLogger } from '@libp2p/interface'
|
|
6
7
|
import type { ProgressOptions } from 'progress-events'
|
|
@@ -16,11 +17,17 @@ export interface ParseUrlStringOptions extends ProgressOptions<ResolveProgressEv
|
|
|
16
17
|
|
|
17
18
|
}
|
|
18
19
|
|
|
20
|
+
export interface ParsedUrlQuery extends Record<string, string | unknown> {
|
|
21
|
+
format?: RequestFormatShorthand
|
|
22
|
+
download?: boolean
|
|
23
|
+
filename?: string
|
|
24
|
+
}
|
|
25
|
+
|
|
19
26
|
export interface ParsedUrlStringResults {
|
|
20
27
|
protocol: string
|
|
21
28
|
path: string
|
|
22
29
|
cid: CID
|
|
23
|
-
query:
|
|
30
|
+
query: ParsedUrlQuery
|
|
24
31
|
}
|
|
25
32
|
|
|
26
33
|
const URL_REGEX = /^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/$?]+)\/?(?<path>[^$?]*)\??(?<queryString>.*)$/
|
|
@@ -104,7 +111,7 @@ export async function parseUrlString ({ urlString, ipns, logger }: ParseUrlStrin
|
|
|
104
111
|
}
|
|
105
112
|
|
|
106
113
|
// parse query string
|
|
107
|
-
const query: Record<string,
|
|
114
|
+
const query: Record<string, any> = {}
|
|
108
115
|
|
|
109
116
|
if (queryString != null && queryString.length > 0) {
|
|
110
117
|
const queryParts = queryString.split('&')
|
|
@@ -112,6 +119,14 @@ export async function parseUrlString ({ urlString, ipns, logger }: ParseUrlStrin
|
|
|
112
119
|
const [key, value] = part.split('=')
|
|
113
120
|
query[key] = decodeURIComponent(value)
|
|
114
121
|
}
|
|
122
|
+
|
|
123
|
+
if (query.download != null) {
|
|
124
|
+
query.download = query.download === 'true'
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (query.filename != null) {
|
|
128
|
+
query.filename = query.filename.toString()
|
|
129
|
+
}
|
|
115
130
|
}
|
|
116
131
|
|
|
117
132
|
/**
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export function okResponse (body?: BodyInit | null): Response {
|
|
2
|
+
return new Response(body, {
|
|
3
|
+
status: 200,
|
|
4
|
+
statusText: 'OK'
|
|
5
|
+
})
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function notSupportedResponse (body?: BodyInit | null): Response {
|
|
9
|
+
const response = new Response(body, {
|
|
10
|
+
status: 501,
|
|
11
|
+
statusText: 'Not Implemented'
|
|
12
|
+
})
|
|
13
|
+
response.headers.set('X-Content-Type-Options', 'nosniff') // see https://specs.ipfs.tech/http-gateways/path-gateway/#x-content-type-options-response-header
|
|
14
|
+
return response
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function notAcceptableResponse (body?: BodyInit | null): Response {
|
|
18
|
+
return new Response(body, {
|
|
19
|
+
status: 406,
|
|
20
|
+
statusText: 'Not Acceptable'
|
|
21
|
+
})
|
|
22
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { code as dagCborCode } from '@ipld/dag-cbor'
|
|
2
|
+
import { code as dagJsonCode } from '@ipld/dag-json'
|
|
3
|
+
import { code as dagPbCode } from '@ipld/dag-pb'
|
|
4
|
+
import { code as jsonCode } from 'multiformats/codecs/json'
|
|
5
|
+
import { code as rawCode } from 'multiformats/codecs/raw'
|
|
6
|
+
import type { RequestFormatShorthand } from '../types.js'
|
|
7
|
+
import type { CID } from 'multiformats/cid'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* This maps supported response types for each codec supported by verified-fetch
|
|
11
|
+
*/
|
|
12
|
+
const CID_TYPE_MAP: Record<number, string[]> = {
|
|
13
|
+
[dagCborCode]: [
|
|
14
|
+
'application/json',
|
|
15
|
+
'application/vnd.ipld.dag-cbor',
|
|
16
|
+
'application/cbor',
|
|
17
|
+
'application/vnd.ipld.dag-json',
|
|
18
|
+
'application/octet-stream',
|
|
19
|
+
'application/vnd.ipld.raw',
|
|
20
|
+
'application/vnd.ipfs.ipns-record',
|
|
21
|
+
'application/vnd.ipld.car'
|
|
22
|
+
],
|
|
23
|
+
[dagJsonCode]: [
|
|
24
|
+
'application/json',
|
|
25
|
+
'application/vnd.ipld.dag-cbor',
|
|
26
|
+
'application/cbor',
|
|
27
|
+
'application/vnd.ipld.dag-json',
|
|
28
|
+
'application/octet-stream',
|
|
29
|
+
'application/vnd.ipld.raw',
|
|
30
|
+
'application/vnd.ipfs.ipns-record',
|
|
31
|
+
'application/vnd.ipld.car'
|
|
32
|
+
],
|
|
33
|
+
[jsonCode]: [
|
|
34
|
+
'application/json',
|
|
35
|
+
'application/vnd.ipld.dag-cbor',
|
|
36
|
+
'application/cbor',
|
|
37
|
+
'application/vnd.ipld.dag-json',
|
|
38
|
+
'application/octet-stream',
|
|
39
|
+
'application/vnd.ipld.raw',
|
|
40
|
+
'application/vnd.ipfs.ipns-record',
|
|
41
|
+
'application/vnd.ipld.car'
|
|
42
|
+
],
|
|
43
|
+
[dagPbCode]: [
|
|
44
|
+
'application/octet-stream',
|
|
45
|
+
'application/json',
|
|
46
|
+
'application/vnd.ipld.dag-cbor',
|
|
47
|
+
'application/cbor',
|
|
48
|
+
'application/vnd.ipld.dag-json',
|
|
49
|
+
'application/vnd.ipld.raw',
|
|
50
|
+
'application/vnd.ipfs.ipns-record',
|
|
51
|
+
'application/vnd.ipld.car',
|
|
52
|
+
'application/x-tar'
|
|
53
|
+
],
|
|
54
|
+
[rawCode]: [
|
|
55
|
+
'application/octet-stream',
|
|
56
|
+
'application/vnd.ipld.raw',
|
|
57
|
+
'application/vnd.ipfs.ipns-record',
|
|
58
|
+
'application/vnd.ipld.car'
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Selects an output mime-type based on the CID and a passed `Accept` header
|
|
64
|
+
*/
|
|
65
|
+
export function selectOutputType (cid: CID, accept?: string): string | undefined {
|
|
66
|
+
const cidMimeTypes = CID_TYPE_MAP[cid.code]
|
|
67
|
+
|
|
68
|
+
if (accept != null) {
|
|
69
|
+
return chooseMimeType(accept, cidMimeTypes)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function chooseMimeType (accept: string, validMimeTypes: string[]): string | undefined {
|
|
74
|
+
const requestedMimeTypes = accept
|
|
75
|
+
.split(',')
|
|
76
|
+
.map(s => {
|
|
77
|
+
const parts = s.trim().split(';')
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
mimeType: `${parts[0]}`.trim(),
|
|
81
|
+
weight: parseQFactor(parts[1])
|
|
82
|
+
}
|
|
83
|
+
})
|
|
84
|
+
.sort((a, b) => {
|
|
85
|
+
if (a.weight === b.weight) {
|
|
86
|
+
return 0
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (a.weight > b.weight) {
|
|
90
|
+
return -1
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return 1
|
|
94
|
+
})
|
|
95
|
+
.map(s => s.mimeType)
|
|
96
|
+
|
|
97
|
+
for (const headerFormat of requestedMimeTypes) {
|
|
98
|
+
for (const mimeType of validMimeTypes) {
|
|
99
|
+
if (headerFormat.includes(mimeType)) {
|
|
100
|
+
return mimeType
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (headerFormat === '*/*') {
|
|
104
|
+
return mimeType
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (headerFormat.startsWith('*/') && mimeType.split('/')[1] === headerFormat.split('/')[1]) {
|
|
108
|
+
return mimeType
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (headerFormat.endsWith('/*') && mimeType.split('/')[0] === headerFormat.split('/')[0]) {
|
|
112
|
+
return mimeType
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Parses q-factor weighting from the accept header to allow letting some mime
|
|
120
|
+
* types take precedence over others.
|
|
121
|
+
*
|
|
122
|
+
* If the q-factor for an acceptable mime representation is omitted it defaults
|
|
123
|
+
* to `1`.
|
|
124
|
+
*
|
|
125
|
+
* All specified values should be in the range 0-1.
|
|
126
|
+
*
|
|
127
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept#q
|
|
128
|
+
*/
|
|
129
|
+
function parseQFactor (str?: string): number {
|
|
130
|
+
if (str != null) {
|
|
131
|
+
str = str.trim()
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (str == null || !str.startsWith('q=')) {
|
|
135
|
+
return 1
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const factor = parseFloat(str.replace('q=', ''))
|
|
139
|
+
|
|
140
|
+
if (isNaN(factor)) {
|
|
141
|
+
return 0
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return factor
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const FORMAT_TO_MIME_TYPE: Record<RequestFormatShorthand, string> = {
|
|
148
|
+
raw: 'application/vnd.ipld.raw',
|
|
149
|
+
car: 'application/vnd.ipld.car',
|
|
150
|
+
'dag-json': 'application/vnd.ipld.dag-json',
|
|
151
|
+
'dag-cbor': 'application/vnd.ipld.dag-cbor',
|
|
152
|
+
json: 'application/json',
|
|
153
|
+
cbor: 'application/cbor',
|
|
154
|
+
'ipns-record': 'application/vnd.ipfs.ipns-record',
|
|
155
|
+
tar: 'application/x-tar'
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Converts a `format=...` query param to a mime type as would be found in the
|
|
160
|
+
* `Accept` header, if a valid mapping is available
|
|
161
|
+
*/
|
|
162
|
+
export function queryFormatToAcceptHeader (format?: RequestFormatShorthand): string | undefined {
|
|
163
|
+
if (format != null) {
|
|
164
|
+
return FORMAT_TO_MIME_TYPE[format]
|
|
165
|
+
}
|
|
166
|
+
}
|