-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbee-api.listener.ts
303 lines (252 loc) · 9.94 KB
/
bee-api.listener.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
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
import { createSubdomainUrl, isLocalhost, subdomainToBzzResource } from '../../utils/bzz-link'
import { fakeUrl } from '../../utils/fake-url'
import { getItem, StoreObserver } from '../../utils/storage'
import { SWARM_SESSION_ID_KEY, unpackSwarmSessionIdFromUrl } from '../../utils/swarm-session-id'
import { DEFAULT_BEE_API_ADDRESS } from '../constants/addresses'
export class BeeApiListener {
private _beeApiUrl: string
private _globalPostageBatchEnabled: boolean
private _globalPostageBatchId: string
private _web2OriginEnabled: boolean
public constructor(private storeObserver: StoreObserver) {
this._beeApiUrl = DEFAULT_BEE_API_ADDRESS
this._globalPostageBatchEnabled = false
this._web2OriginEnabled = false
this._globalPostageBatchId = 'undefined' // it is not necessary to check later, if it is enabled it will insert
this.addStoreListeners()
this.asyncInit()
this.addBzzListeners()
}
public get beeApiUrl(): string {
return this._beeApiUrl
}
/**
* Handles postage batch id header replacement with global batch id
*/
private globalPostageStampHeaderListener = (
details: chrome.webRequest.WebRequestHeadersDetails,
): void | chrome.webRequest.BlockingResponse => {
if (!this._globalPostageBatchEnabled || !details.requestHeaders) return
try {
const postageBatchIdHeader = details.requestHeaders.find(
header => header.name.toLowerCase() === 'swarm-postage-batch-id',
)
if (!postageBatchIdHeader) return
console.log(
`Postage Batch: ${this._globalPostageBatchId} Batch ID will be used instead of ` + postageBatchIdHeader.value,
)
postageBatchIdHeader.value = this._globalPostageBatchId
return { requestHeaders: details.requestHeaders }
} catch (e) {
console.error(`request header error problem`, e, details.requestHeaders)
return
}
}
private sandboxListener = (
details: chrome.webRequest.WebResponseHeadersDetails,
): void | chrome.webRequest.BlockingResponse => {
console.log('web2OriginEnabled', this._web2OriginEnabled)
if (this._web2OriginEnabled) return { responseHeaders: details.responseHeaders }
const urlArray = details.url.toString().split('/')
if (urlArray[3] === 'bzz' && urlArray[4]) {
details.responseHeaders?.push({
name: 'Content-Security-Policy',
value: 'sandbox allow-scripts allow-modals allow-popups allow-forms',
})
}
console.log('responseHeaders', details.responseHeaders)
return { responseHeaders: details.responseHeaders }
}
private addBeeNodeListeners(beeApiUrl: string) {
chrome.webRequest.onBeforeSendHeaders.addListener(
this.globalPostageStampHeaderListener,
{
urls: [`${beeApiUrl}/*`],
},
['blocking', 'requestHeaders'],
)
chrome.webRequest.onHeadersReceived.addListener(
this.sandboxListener,
{
urls: [`${beeApiUrl}/*`],
},
['blocking', 'responseHeaders', 'extraHeaders'],
)
}
private removeBeeNodeListeners() {
console.log('remove bee node listeners')
chrome.webRequest.onBeforeSendHeaders.removeListener(this.globalPostageStampHeaderListener)
}
private addBzzListeners() {
/**
* New Swarm page load request
*
* it listens on a fake URL which will redirect the current tab
* to the desired address.
* it will attach the API key later
*/
chrome.webRequest.onBeforeRequest.addListener(
(details: chrome.webRequest.WebRequestBodyDetails) => {
const urlArray = details.url.split(`${fakeUrl.openDapp}/`)
if (urlArray.length !== 2) {
console.error(`Invalid Fake URL usage. Got: ${details.url}`)
return // invalid fake url usage
}
this.redirectToBzzReference(urlArray[1], details.tabId)
},
{ urls: [`${fakeUrl.openDapp}/*`] },
)
/**
* {contentReference}.bzz.link has two ways to request:
*
* 1. typing to address bar
* 2. can be referred from dApp
*/
/**
* this listener automatically cancels all requests towards .bzz.link URLs
* it relates to the 2nd scenario
*/
chrome.webRequest.onBeforeRequest.addListener(
() => {
return { cancel: true }
},
{ urls: ['https://*.bzz.link/*', 'http://*.bzz.link/*'] },
)
/**
* it force-redirects to the fakeURL of the bzz resource.
* it solves the 1st scenario
*/
chrome.webNavigation.onBeforeNavigate.addListener(
details => {
const { url, tabId } = details
const urlObject = new URL(url)
const subdomain = urlObject.host.split('.')[0]
const pathWithParams = url.substring(urlObject.origin.length)
const bzzReference = subdomainToBzzResource(subdomain) + pathWithParams
console.log('bzz link redirect', bzzReference, url, pathWithParams)
this.redirectToBzzReference(bzzReference, tabId)
},
{ url: [{ hostSuffix: '.bzz.link' }] },
)
// 'bzz://{content-address}' URI in search bar triggers redirect to gateway BZZ address
// NOTE: works only if google search is set as default search engine
chrome.webRequest.onBeforeRequest.addListener(
(details: chrome.webRequest.WebRequestBodyDetails) => {
console.log('Original BZZ Url', details.url)
const urlParams = new URLSearchParams(new URL(details.url).search)
const query = decodeURI(urlParams.get('oq') || urlParams.get('q') || '')
if (!query || !query.startsWith('bzz://')) return
this.redirectToBzzReference(query.substr(6), details.tabId)
},
{
urls: ['https://www.google.com/search?*'],
},
)
// Used to load page resources like images
// Always have to have session ID in the URL Param
chrome.webRequest.onBeforeRequest.addListener(
details => {
let { url } = details
let swarmSessionId: string
try {
const { sessionId, originalUrl } = unpackSwarmSessionIdFromUrl(url)
swarmSessionId = sessionId
url = originalUrl
} catch (e) {
console.error(`There is no valid '${SWARM_SESSION_ID_KEY}' passed to the bzz reference: ${url}`)
return {
cancel: true,
}
}
// get the full referenced BZZ address from the modified url (without bzz address)
const urlArray = url.toString().split(`${fakeUrl.bzzProtocol}/`)
const redirectUrl = `${this._beeApiUrl}/bzz/${urlArray[1]}`
console.log(`bzz redirect to ${redirectUrl} from ${details.url}. Session ID: ${swarmSessionId}`)
return {
redirectUrl,
}
},
{ urls: [`${fakeUrl.bzzProtocol}/*`] },
['blocking'],
)
// Redirect the Bee API calls with swarm-session-id query param
// The swarm-session-id query parameter can be between the path and the host
chrome.webRequest.onBeforeRequest.addListener(
details => {
let { url } = details
try {
const { originalUrl } = unpackSwarmSessionIdFromUrl(url)
url = originalUrl
} catch (e) {
console.error(`There is no valid '${SWARM_SESSION_ID_KEY}' passed to the bzz reference: ${url}`)
return {
cancel: true,
}
}
// get the full referenced BZZ address from the modified url (without bzz address)
const urlArray = url.split(`${fakeUrl.beeApiAddress}/`)
const redirectUrl = `${this._beeApiUrl}/${urlArray[1]}`
console.log(`Bee API client request redirect to ${redirectUrl} from ${url}`)
return {
redirectUrl,
}
},
{ urls: [`${fakeUrl.beeApiAddress}*`] },
['blocking'],
)
}
private async asyncInit() {
const storedBeeApiUrl = await getItem('beeApiUrl')
const storedGlobalPostageBatchEnabled = await getItem('globalPostageStampEnabled')
const storedGlobalPostageBatchId = await getItem('globalPostageBatch')
const storedWeb2OriginEnabled = await getItem('web2OriginEnabled')
if (storedBeeApiUrl) this._beeApiUrl = storedBeeApiUrl
if (storedGlobalPostageBatchEnabled) this._globalPostageBatchEnabled = storedGlobalPostageBatchEnabled
if (storedGlobalPostageBatchId) this._globalPostageBatchId = storedGlobalPostageBatchId
if (storedWeb2OriginEnabled) this._web2OriginEnabled = storedWeb2OriginEnabled
// register listeners that have to be after async init
this.addBeeNodeListeners(this._beeApiUrl)
}
private addStoreListeners(): void {
this.storeObserver.addListener('beeApiUrl', newValue => {
console.log('Bee API URL changed to', newValue)
this._beeApiUrl = newValue
this.removeBeeNodeListeners()
this.addBeeNodeListeners(this._beeApiUrl)
})
this.storeObserver.addListener('globalPostageStampEnabled', newValue => {
this._globalPostageBatchEnabled = Boolean(newValue)
})
this.storeObserver.addListener('globalPostageBatch', newValue => {
this._globalPostageBatchId = newValue
})
this.storeObserver.addListener<boolean>('web2OriginEnabled', newValue => {
console.log('web2OriginEnabled changed to', newValue)
this._web2OriginEnabled = newValue
})
}
/**
* Redirects the tab or create a new tab for the dApp under the given BZZ reference
*
* @param bzzReference in form of $ROOT_HASH<$PATH><$QUERY>
* @param tabId the tab will be navigated to the dApp page
*/
private redirectToBzzReference(bzzReference: string, tabId: number) {
let url: string
if (!isLocalhost(this._beeApiUrl)) {
url = `${this._beeApiUrl}/bzz/${bzzReference}`
} else {
const [hash, path] = bzzReference.split(/\/(.*)/s)
let subdomain = hash
if (subdomain.endsWith('.eth')) {
subdomain = subdomain.substring(0, subdomain.length - 4)
}
url = createSubdomainUrl(this._beeApiUrl, subdomain)
if (path) {
url += `/${path}`
}
}
console.log(`Fake URL redirection to ${url} on tabId ${tabId}`)
chrome.tabs.update(tabId, { active: true, url })
}
}