-
Notifications
You must be signed in to change notification settings - Fork 325
/
Copy pathblockOrObserve.ts
263 lines (239 loc) · 8.61 KB
/
blockOrObserve.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
import browser from 'webextension-polyfill'
import debug from 'debug'
import { CompanionState } from '../../types/companion.js'
// this won't work in webworker context. Needs to be enabled manually
// https://github.com/debug-js/debug/issues/916
const log = debug('ipfs-companion:redirect-handler:blockOrObserve')
log.error = debug('ipfs-companion:redirect-handler:blockOrObserve:error')
interface regexFilterMap {
id: number
regexSubstitution: string
}
interface redirectHandlerInput {
originUrl: string
redirectUrl: string
}
const savedRegexFilters: Map<string, regexFilterMap> = new Map()
const DEFAULT_LOCAL_RULES: redirectHandlerInput[] = [
{
originUrl: 'http://127.0.0.1',
redirectUrl: 'http://localhost'
},
{
originUrl: 'http://[::1]',
redirectUrl: 'http://localhost'
}
]
/**
* This function determines if the request is headed to a local IPFS gateway.
*
* @param url
* @returns
*/
export function isLocalHost (url: string): boolean {
return url.startsWith('http://127.0.0.1') ||
url.startsWith('http://localhost') ||
url.startsWith('http://[::1]')
}
/**
* Escape the characters that are allowed in the URL, but not in the regex.
*
* @param str URL string to escape
* @returns
*/
function escapeURLRegex (str: string): string {
// these characters are allowed in the URL, but not in the regex.
// eslint-disable-next-line no-useless-escape
const ALLOWED_CHARS_URL_REGEX = /([:\/\?#\[\]@!$&'\(\ )\*\+,;=-_\.~])/g
return str.replace(ALLOWED_CHARS_URL_REGEX, '\\$1')
}
/**
* Construct a regex filter and substitution for a redirect.
*
* @param originUrl
* @param redirectUrl
* @returns
*/
function constructRegexFilter ({ originUrl, redirectUrl }: redirectHandlerInput): {
regexSubstitution: string
regexFilter: string
} {
// We can traverse the URL from the end, and find the first character that is different.
let commonIdx = 1
while (commonIdx < Math.min(originUrl.length, redirectUrl.length)) {
if (originUrl[originUrl.length - commonIdx] !== redirectUrl[redirectUrl.length - commonIdx]) {
break
}
commonIdx += 1
}
// We can now construct the regex filter and substitution.
let regexSubstitution = redirectUrl.slice(0, redirectUrl.length - commonIdx + 1) + '\\1'
// We need to escape the characters that are allowed in the URL, but not in the regex.
const regexFilterFirst = escapeURLRegex(originUrl.slice(0, originUrl.length - commonIdx + 1))
// We need to match the rest of the URL, so we can use a wildcard.
const regexEnding = '((?:[^\\.]|$).*)$'
let regexFilter = `^${regexFilterFirst}${regexEnding}`.replace('https', 'https?')
// This method does not parse:
// originUrl: "https://awesome.ipfs.io/"
// redirectUrl: "http://localhost:8081/ipns/awesome.ipfs.io/"
// that ends up with capturing all urls which we do not want.
if (regexFilter === `^https?\\:\\/${regexEnding}`) {
const subdomain = new URL(originUrl).hostname
regexFilter = `^https?\\:\\/\\/${escapeURLRegex(subdomain)}${regexEnding}`
regexSubstitution = regexSubstitution.replace('\\1', `/${subdomain}\\1`)
}
return { regexSubstitution, regexFilter }
}
// We need to check if the browser supports the declarativeNetRequest API.
// TODO: replace with check for `Blocking` in `chrome.webRequest.OnBeforeRequestOptions`
// which is currently a bug https://bugs.chromium.org/p/chromium/issues/detail?id=1427952
export const supportsBlock = !(browser.declarativeNetRequest?.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES === 5000)
// If the browser supports the declarativeNetRequest API, we can block the request.
export function getExtraInfoSpec<T> (additionalParams: T[] = []): T[] {
if (supportsBlock) {
return ['blocking' as T, ...additionalParams]
}
return additionalParams
}
/**
* Validates if the rule has changed.
*
* @param rule
* @returns {boolean}
*/
function validateIfRuleChanged (rule: browser.DeclarativeNetRequest.Rule): boolean {
if (rule.condition.regexFilter !== undefined) {
const savedRule = savedRegexFilters.get(rule.condition.regexFilter)
if (savedRule !== undefined) {
return savedRule.id !== rule.id || savedRule.regexSubstitution !== rule.action.redirect?.regexSubstitution
}
}
return true
}
/**
* Reconciles the rules on fresh start.
*
* @param {CompanionState} state
*/
async function reconcileRulesAndRemoveOld (state: CompanionState): Promise<void> {
const rules = await browser.declarativeNetRequest.getDynamicRules()
const addRules: browser.DeclarativeNetRequest.Rule[] = []
const removeRuleIds: number[] = []
// parse the existing rules and remove the ones that are not needed.
for (const rule of rules) {
if (rule.action.type === 'redirect' &&
rule.condition.regexFilter !== undefined &&
rule.action.redirect?.regexSubstitution !== undefined) {
if (validateIfRuleChanged(rule)) {
// We need to remove the old rule.
removeRuleIds.push(rule.id)
savedRegexFilters.delete(rule.condition.regexFilter)
} else {
savedRegexFilters.set(rule.condition.regexFilter, {
id: rule.id,
regexSubstitution: rule.action.redirect?.regexSubstitution
})
}
}
}
// add the new rules.
for (const { originUrl, redirectUrl } of DEFAULT_LOCAL_RULES) {
const { port } = new URL(state.gwURLString)
const regexFilter = `^${escapeURLRegex(`${originUrl}:${port}`)}(.*)$`
const regexSubstitution = `${redirectUrl}:${port}\\1`
if (!savedRegexFilters.has(regexFilter)) {
// We need to add the new rule.
addRules.push(generateRule(regexFilter, regexSubstitution))
}
}
await browser.declarativeNetRequest.updateDynamicRules({ addRules, removeRuleIds })
}
/**
* Generates a rule for the declarativeNetRequest API.
*
* @param regexFilter - The regex filter for the rule.
* @param regexSubstitution - The regex substitution for the rule.
* @param excludedInitiatorDomains - The domains that are excluded from the rule.
* @returns
*/
function generateRule (
regexFilter: string,
regexSubstitution: string,
excludedInitiatorDomains: string[] = []
): browser.DeclarativeNetRequest.Rule {
// We need to generate a random ID for the rule.
const id = Math.floor(Math.random() * 29999)
// We need to save the regex filter and ID to check if the rule already exists later.
savedRegexFilters.set(regexFilter, { id, regexSubstitution })
return {
id,
priority: 1,
action: {
type: 'redirect',
redirect: { regexSubstitution }
},
condition: {
regexFilter,
excludedInitiatorDomains,
resourceTypes: [
'csp_report',
'font',
'image',
'main_frame',
'media',
'object',
'other',
'ping',
'script',
'stylesheet',
'sub_frame',
'webbundle',
'websocket',
'webtransport',
'xmlhttprequest'
]
}
}
}
/**
* Register a redirect rule in the dynamic rule set.
*
* @param {redirectHandlerInput} input
* @returns {Promise<void>}
*/
export function addRuleToDynamicRuleSetGenerator (
getState: () => CompanionState): (input: redirectHandlerInput) => Promise<void> {
// returning a closure to avoid passing `getState` as an argument to `addRuleToDynamicRuleSet`.
return async function ({ originUrl, redirectUrl }: redirectHandlerInput): Promise<void> {
const state = getState()
const redirectIsOrigin = originUrl === redirectUrl
const redirectIsLocal = isLocalHost(originUrl) && isLocalHost(redirectUrl)
const badOriginRedirect = originUrl.includes(state.gwURL.host) && !redirectUrl.includes('recovery')
// We don't want to redirect to the same URL. Or to the gateway.
if (redirectIsOrigin || badOriginRedirect || redirectIsLocal
) {
return
}
// We need to construct the regex filter and substitution.
const { regexSubstitution, regexFilter } = constructRegexFilter({ originUrl, redirectUrl })
const savedRule = savedRegexFilters.get(regexFilter)
if (savedRule === undefined || savedRule.regexSubstitution !== regexSubstitution) {
const removeRuleIds: number[] = []
if (savedRule !== undefined) {
// We need to remove the old rule because the substitution has changed.
removeRuleIds.push(savedRule.id)
savedRegexFilters.delete(regexFilter)
}
await browser.declarativeNetRequest.updateDynamicRules(
{
// We need to add the new rule.
addRules: [generateRule(regexFilter, regexSubstitution)],
// We need to remove the old rules.
removeRuleIds
}
)
}
// async call to reconcile rules and remove old ones.
await reconcileRulesAndRemoveOld(state)
}
}