-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathparse-url-string.ts
More file actions
383 lines (335 loc) · 13.9 KB
/
parse-url-string.ts
File metadata and controls
383 lines (335 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import { AbortError } from '@libp2p/interface'
import { multiaddr } from '@multiformats/multiaddr'
import { CID } from 'multiformats/cid'
import { getPeerIdFromString } from './get-peer-id-from-string.js'
import { serverTiming } from './server-timing.js'
import { TLRU } from './tlru.js'
import type { ServerTimingResult } from './server-timing.js'
import type { RequestFormatShorthand } from '../types.js'
import type { DNSLinkResolveResult, IPNS, IPNSResolveResult, IPNSRoutingEvents, ResolveDNSLinkProgressEvents, ResolveProgressEvents, ResolveResult } from '@helia/ipns'
import type { AbortOptions, ComponentLogger, PeerId } from '@libp2p/interface'
import type { Multiaddr } from '@multiformats/multiaddr'
import type { ProgressOptions } from 'progress-events'
const ipnsCache = new TLRU<DNSLinkResolveResult | IPNSResolveResult>(1000)
export interface ParseUrlStringInput {
urlString: string
ipns: IPNS
logger: ComponentLogger
withServerTiming?: boolean
}
export interface ParseUrlStringOptions extends ProgressOptions<ResolveProgressEvents | IPNSRoutingEvents | ResolveDNSLinkProgressEvents>, AbortOptions {
}
export interface ParsedUrlQuery extends Record<string, string | unknown> {
format?: RequestFormatShorthand
download?: boolean
filename?: string
}
export interface ParsedUrlStringResults extends ResolveResult {
protocol: 'ipfs' | 'ipns'
query: ParsedUrlQuery
/**
* The value for the IPFS gateway spec compliant header `X-Ipfs-Path` on the
* response.
* The value of this header should be the original requested content path,
* prior to any path resolution or traversal.
*
* @see https://specs.ipfs.tech/http-gateways/path-gateway/#x-ipfs-path-response-header
*/
ipfsPath: string
/**
* seconds as a number
*/
ttl?: number
/**
* serverTiming items
*/
serverTimings: Array<ServerTimingResult<any>>
/**
* The providers hinted in the URL.
*/
providers: Array<Multiaddr>
}
const URL_REGEX = /^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/
const PATH_REGEX = /^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/
const PATH_GATEWAY_REGEX = /^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/
const SUBDOMAIN_GATEWAY_REGEX = /^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/
interface MatchUrlGroups {
protocol: 'ipfs' | 'ipns'
cidOrPeerIdOrDnsLink: string
path?: string
queryString?: string
}
function matchUrlGroupsGuard (groups?: null | { [key in string]: string; } | MatchUrlGroups): groups is MatchUrlGroups {
const protocol = groups?.protocol
if (protocol == null) { return false }
const cidOrPeerIdOrDnsLink = groups?.cidOrPeerIdOrDnsLink
if (cidOrPeerIdOrDnsLink == null) { return false }
const path = groups?.path
const queryString = groups?.queryString
return ['ipns', 'ipfs'].includes(protocol) &&
typeof cidOrPeerIdOrDnsLink === 'string' &&
(path == null || typeof path === 'string') &&
(queryString == null || typeof queryString === 'string')
}
export function matchURLString (urlString: string): MatchUrlGroups {
for (const pattern of [SUBDOMAIN_GATEWAY_REGEX, URL_REGEX, PATH_GATEWAY_REGEX, PATH_REGEX]) {
const match = urlString.match(pattern)
if (matchUrlGroupsGuard(match?.groups)) {
return match.groups satisfies MatchUrlGroups
}
}
throw new TypeError(`Invalid URL: ${urlString}, please use ipfs://, ipns://, or gateway URLs only`)
}
/**
* determines the TTL for the resolved resource that will be used for the `Cache-Control` header's `max-age` directive.
* max-age is in seconds
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#response_directives
*
* If we have ipnsTtlNs, it will be a BigInt representing "nanoseconds". We need to convert it back to seconds.
*
* For more TTL nuances:
*
* @see https://github.com/ipfs/js-ipns/blob/16e0e10682fa9a663e0bb493a44d3e99a5200944/src/index.ts#L200
* @see https://github.com/ipfs/js-ipns/pull/308
* @returns the ttl in seconds
*/
function calculateTtl (resolveResult?: IPNSResolveResult | DNSLinkResolveResult): number | undefined {
if (resolveResult == null) {
return undefined
}
const dnsLinkTtl = (resolveResult as DNSLinkResolveResult).answer?.TTL
const ipnsTtlNs = (resolveResult as IPNSResolveResult).record?.ttl
const ipnsTtl = ipnsTtlNs != null ? Number(ipnsTtlNs / BigInt(1e9)) : undefined
return dnsLinkTtl ?? ipnsTtl
}
/**
* For DNSLink see https://specs.ipfs.tech/http-gateways/subdomain-gateway/#host-request-header
* DNSLink names include . which means they must be inlined into a single DNS label to provide unique origin and work with wildcard TLS certificates.
*/
// DNS label can have up to 63 characters, consisting of alphanumeric
// characters or hyphens -, but it must not start or end with a hyphen.
const dnsLabelRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/
/**
* Checks if label looks like inlined DNSLink.
* (https://specs.ipfs.tech/http-gateways/subdomain-gateway/#host-request-header)
*/
function isInlinedDnsLink (label: string): boolean {
return dnsLabelRegex.test(label) && label.includes('-') && !label.includes('.')
}
/**
* DNSLink label decoding
* - Every standalone - is replaced with .
* - Every remaining -- is replaced with -
*
* @example en-wikipedia--on--ipfs-org.ipns.example.net -> example.net/ipns/en.wikipedia-on-ipfs.org
*/
function dnsLinkLabelDecoder (linkLabel: string): string {
return linkLabel.replace(/--/g, '%').replace(/-/g, '.').replace(/%/g, '-')
}
/**
* A function that parses ipfs:// and ipns:// URLs, returning an object with easily recognizable properties.
*
* After determining the protocol successfully, we process the cidOrPeerIdOrDnsLink:
* - If it's ipfs, it parses the CID or throws Error[]
* - If it's ipns, it attempts to resolve the PeerId and then the DNSLink. If both fail, Error[] is thrown.
*
* @todo we need to break out each step of this function (cid parsing, ipns resolving, dnslink resolving) into separate functions and then remove the eslint-disable comment
*
* @throws {Error[]}
*/
// eslint-disable-next-line complexity
export async function parseUrlString ({ urlString, ipns, logger, withServerTiming = false }: ParseUrlStringInput, options?: ParseUrlStringOptions): Promise<ParsedUrlStringResults> {
const log = logger.forComponent('helia:verified-fetch:parse-url-string')
const { protocol, cidOrPeerIdOrDnsLink, path: urlPath, queryString } = matchURLString(urlString)
let cid: CID | undefined
let resolvedPath: string | undefined
const errors: Error[] = []
let resolveResult: IPNSResolveResult | DNSLinkResolveResult | undefined
const serverTimings: Array<ServerTimingResult<any>> = []
if (protocol === 'ipfs') {
try {
cid = CID.parse(cidOrPeerIdOrDnsLink)
/**
* no ttl set. @link {setCacheControlHeader}
*/
} catch (err) {
log.error(err)
errors.push(new TypeError('Invalid CID for ipfs://<cid> URL'))
}
} else {
// protocol is ipns
resolveResult = ipnsCache.get(cidOrPeerIdOrDnsLink)
if (resolveResult != null) {
cid = resolveResult.cid
resolvedPath = resolveResult.path
log.trace('resolved %s to %c from cache', cidOrPeerIdOrDnsLink, cid)
} else {
log.trace('Attempting to resolve PeerId for %s', cidOrPeerIdOrDnsLink)
let peerId: PeerId | undefined
try {
// try resolving as an IPNS name
peerId = getPeerIdFromString(cidOrPeerIdOrDnsLink)
const pubKey = peerId?.publicKey
if (pubKey == null) {
throw new TypeError('cidOrPeerIdOrDnsLink contains no public key')
}
if (withServerTiming) {
const resolveIpns = async (): Promise<IPNSResolveResult> => {
return ipns.resolve(pubKey, options)
}
const resolveResultWithServerTiming = await serverTiming('ipns.resolve', `Resolve IPNS name ${cidOrPeerIdOrDnsLink}`, resolveIpns)
serverTimings.push(resolveResultWithServerTiming)
// eslint-disable-next-line max-depth
if (resolveResultWithServerTiming.error != null) {
throw resolveResultWithServerTiming.error
}
resolveResult = resolveResultWithServerTiming.result
} else {
resolveResult = await ipns.resolve(pubKey, options)
}
cid = resolveResult?.cid
resolvedPath = resolveResult?.path
log.trace('resolved %s to %c', cidOrPeerIdOrDnsLink, cid)
} catch (err) {
if (options?.signal?.aborted) {
throw new AbortError(options?.signal?.reason)
}
if (peerId == null) {
log.error('could not parse PeerId string "%s"', cidOrPeerIdOrDnsLink, err)
errors.push(new TypeError(`Could not parse PeerId in ipns url "${cidOrPeerIdOrDnsLink}", ${(err as Error).message}`))
} else {
log.error('could not resolve PeerId %c', peerId, err)
errors.push(new TypeError(`Could not resolve PeerId "${cidOrPeerIdOrDnsLink}": ${(err as Error).message}`))
}
}
if (cid == null) {
// cid is still null, try resolving as a DNSLink
let decodedDnsLinkLabel = cidOrPeerIdOrDnsLink
if (isInlinedDnsLink(cidOrPeerIdOrDnsLink)) {
decodedDnsLinkLabel = dnsLinkLabelDecoder(cidOrPeerIdOrDnsLink)
log.trace('decoded dnslink from "%s" to "%s"', cidOrPeerIdOrDnsLink, decodedDnsLinkLabel)
}
log.trace('Attempting to resolve DNSLink for %s', decodedDnsLinkLabel)
try {
// eslint-disable-next-line max-depth
if (withServerTiming) {
const resolveResultWithServerTiming = await serverTiming('ipns.resolveDNSLink', `Resolve DNSLink ${decodedDnsLinkLabel}`, ipns.resolveDNSLink.bind(ipns, decodedDnsLinkLabel, options))
serverTimings.push(resolveResultWithServerTiming)
// eslint-disable-next-line max-depth
if (resolveResultWithServerTiming.error != null) {
throw resolveResultWithServerTiming.error
}
resolveResult = resolveResultWithServerTiming.result
} else {
resolveResult = await ipns.resolveDNSLink(decodedDnsLinkLabel, options)
}
cid = resolveResult?.cid
resolvedPath = resolveResult?.path
log.trace('resolved %s to %c', decodedDnsLinkLabel, cid)
} catch (err: any) {
// eslint-disable-next-line max-depth
if (options?.signal?.aborted) {
throw new AbortError(options?.signal?.reason)
}
log.error('could not resolve DnsLink for "%s"', cidOrPeerIdOrDnsLink, err)
errors.push(err)
}
}
}
}
if (cid == null) {
if (errors.length === 1) {
throw errors[0]
}
errors.push(new Error(`Invalid resource. Cannot determine CID from URL "${urlString}".`))
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw errors
}
let ttl = calculateTtl(resolveResult)
if (resolveResult != null) {
// use the ttl for the resolved resource for the cache, but fallback to 2 minutes if not available
ttl = ttl ?? 60 * 2
log.trace('caching %s resolved to %s with TTL: %s', cidOrPeerIdOrDnsLink, cid, ttl)
// convert ttl from seconds to ms for the cache
ipnsCache.set(cidOrPeerIdOrDnsLink, resolveResult, ttl * 1000)
}
// parse query string
const query: Record<string, any> = {}
const providers: Array<Multiaddr> = []
if (queryString != null && queryString.length > 0) {
const queryParts = queryString.split('&')
for (const part of queryParts) {
const [key, value] = part.split('=')
// see https://github.com/ipfs/specs/pull/504
// provider is a special case, the parameter MAY be repeated
// if not provider just decode the value and keep iterating
if (key !== 'provider') {
query[key] = decodeURIComponent(value)
continue
}
if (query[key] == null) {
query[key] = []
}
const decodedValue = decodeURIComponent(value)
// if the provider value starts with /, it is a multiaddr
// otherwise it is a HTTP URL string
if (decodedValue.startsWith('/')) {
try {
// Must be a multiaddr to be used as Hint
const m = multiaddr(decodedValue)
providers.push(m)
;(query[key] as string[]).push(decodedValue)
} catch {
// Ignore invalid multiaddr
}
} else {
try {
const url = new URL(decodedValue)
const m = multiaddr(`/dns/${url.hostname}/tcp/${url.port || 443}/${url.protocol.replace(':', '')}`)
providers.push(m)
;(query[key] as string[]).push(decodedValue)
} catch {
// Ignore invalid URL
}
}
}
if (query.download != null) {
query.download = query.download === 'true'
}
if (query.filename != null) {
query.filename = query.filename.toString()
}
}
return {
protocol,
cid,
path: joinPaths(resolvedPath, urlPath ?? ''),
query,
ttl,
ipfsPath: `/${protocol}/${cidOrPeerIdOrDnsLink}${urlPath != null && urlPath !== '' ? `/${urlPath}` : ''}`,
providers,
serverTimings
} satisfies ParsedUrlStringResults
}
/**
* join the path from resolve result & given path.
* e.g. /ipns/<peerId>/ that is resolved to /ipfs/<cid>/<path1>, when requested as /ipns/<peerId>/<path2>, should be
* resolved to /ipfs/<cid>/<path1>/<path2>
*/
function joinPaths (resolvedPath: string | undefined, urlPath: string): string {
let path = ''
if (resolvedPath != null) {
path += resolvedPath
}
if (urlPath.length > 0) {
path = `${path.length > 0 ? `${path}/` : path}${urlPath}`
}
// replace duplicate forward slashes
path = path.replace(/\/(\/)+/g, '/')
// strip trailing forward slash if present
if (path.startsWith('/')) {
path = path.substring(1)
}
return path.split('/').map(decodeURIComponent).join('/')
}