forked from ipfs/public-gateway-checker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCors.ts
56 lines (47 loc) · 1.48 KB
/
Cors.ts
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
import fetchPonyfill from 'fetch-ponyfill'
import { CheckBase } from './CheckBase'
import { HASH_STRING, HASH_TO_TEST } from './constants'
import type { GatewayNode } from './GatewayNode'
import { Log } from './Log'
const { fetch } = fetchPonyfill()
const log = new Log('Cors')
class Cors extends CheckBase implements Checkable {
_className = 'Cors'
_tagName = 'div'
constructor (protected parent: GatewayNode) {
super(parent, 'div', 'Cors')
}
async check (): Promise<void> {
const now = Date.now()
const gatewayAndHash = this.parent.gateway.replace(':hash', HASH_TO_TEST)
const testUrl = `${gatewayAndHash}?now=${now}#x-ipfs-companion-no-redirect`
// response body can be accessed only if fetch was executed when
// liberal CORS is present (eg. '*')
try {
const response = await fetch(testUrl)
const { status } = response
const text = await response.text()
this.tag.title = `Response code: ${status}`
if (HASH_STRING === text.trim()) {
// this.parent.checked()
this.tag.asterisk()
this.parent.tag.classList.add('cors')
} else {
log.debug('The response text did not match the expected string')
this.onerror()
throw new Error(`URL '${testUrl} does not support CORS`)
}
} catch (err) {
log.error(err)
this.onerror()
throw err
}
}
checked (): void {
log.warn('Not implemented yet')
}
onerror (): void {
this.tag.empty()
}
}
export { Cors }