Skip to content

Commit

Permalink
wip: 🔕 temporary commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tarampampam committed Apr 29, 2024
1 parent 316be22 commit 212d75f
Show file tree
Hide file tree
Showing 13 changed files with 130 additions and 257 deletions.
1 change: 0 additions & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
},
"default_title": "__MSG_manifest_action_default_title__"
},

"commands": {
"renew-useragent": {
"description": "__MSG_manifest_command_renew_useragent__",
Expand Down
36 changes: 12 additions & 24 deletions src/entrypoints/background/api/filters.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import Rule = chrome.declarativeNetRequest.Rule
import type { ContentScriptPayload, ReadonlySettingsState, ReadonlyUserAgentState } from '~/shared/types'
import { setBridgeData, setRequestHeaders, unsetRequestHeaders } from '../hooks'
import type { ReadonlySettingsState, ReadonlyUserAgentState } from '~/shared/types'
import { setRequestHeaders, unsetRequestHeaders } from '../hooks'

/**
* Returns true if the extension is applicable for the given domain name.
*
* Note: Keep this function implementation in sync with the `isApplicableToDomain()` function (which is defined in the
* `content/content.ts` file).
*/
/** Returns true if the extension is applicable for the given domain name. */
export async function isApplicableForDomain(settings: ReadonlySettingsState, domain: string): Promise<boolean> {
const isInList = settings.blacklist.domains.some((item): boolean => item === domain || domain.endsWith(`.${item}`))

Expand All @@ -24,24 +19,17 @@ export async function isApplicableForDomain(settings: ReadonlySettingsState, dom
export async function reloadRequestHeadersAndBridge(
settings: ReadonlySettingsState,
current: ReadonlyUserAgentState | undefined
): Promise<readonly [Array<Rule>, ContentScriptPayload | undefined] | void> {
): Promise<Array<Rule> | void> {
if (settings.enabled && current) {
return await Promise.all([
// if the extension is disabled or current user-agent is not set, we do not need to update the
// browser request headers
setRequestHeaders(
current,
settings.blacklist.mode === 'blacklist'
? { exceptDomains: settings.blacklist.domains }
: { applyToDomains: settings.blacklist.domains }
),
// if the extension is disabled or current user-agent is not set, we do not need to update the
// browser request headers
return await setRequestHeaders(
current,
settings.blacklist.mode === 'blacklist'
? { exceptDomains: settings.blacklist.domains }
: { applyToDomains: settings.blacklist.domains },
settings.jsProtection.enabled
? setBridgeData(current, {
applyToDomains: settings.blacklist.mode === 'blacklist' ? undefined : settings.blacklist.domains,
exceptDomains: settings.blacklist.mode === 'blacklist' ? settings.blacklist.domains : undefined,
})
: undefined,
])
)
}

// otherwise, we need to unset the request headers
Expand Down
64 changes: 0 additions & 64 deletions src/entrypoints/background/hooks/content-script-bridge.ts

This file was deleted.

55 changes: 42 additions & 13 deletions src/entrypoints/background/hooks/http-requests.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { browserBrands, isMobile, platform } from '~/shared/client-hint'
import { canonizeDomain } from '~/shared'
import type { ReadonlyUserAgentState } from '~/shared/types'
import type { ContentScriptPayload, ReadonlyUserAgentState } from '~/shared/types'
import ResourceType = chrome.declarativeNetRequest.ResourceType
import Rule = chrome.declarativeNetRequest.Rule

Expand All @@ -25,9 +25,10 @@ enum HeaderOperation {

// Note: the rule IDs must be unique, and do not change them after the extension is published.
// The rule IDs are used to remove the existing rules before adding new ones.
const RuleIDs: { readonly [_ in 'ReplaceUserAgent' | 'ReplaceClientHints']: number } = {
const RuleIDs: { readonly [_ in 'ReplaceUserAgent' | 'ReplaceClientHints' | 'ProvidePayload']: number } = {
ReplaceUserAgent: 1,
ReplaceClientHints: 2,
ProvidePayload: 3,
}

enum HeaderNames {
Expand All @@ -38,6 +39,7 @@ enum HeaderNames {
CLIENT_HINT_BRAND_FULL = 'Sec-CH-UA-Full-Version-List', // https://mzl.la/3C3x5TT
CLIENT_HINT_PLATFORM = 'Sec-CH-UA-Platform', // https://mzl.la/3EbrbTj
CLIENT_HINT_MOBILE = 'Sec-CH-UA-Mobile', // https://mzl.la/3SYTA3f
SERVER_TIMING = 'server-timing', // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing
}

const allResourceTypes = Object.values(ResourceType)
Expand All @@ -48,6 +50,8 @@ const allResourceTypes = Object.values(ResourceType)
* The filter parameter is optional and can be used to apply the rules only to specific domains.
* If filter is not provided, the rules are applied to all domains.
*
* Enabling payload sending means that the JS protection is enabled.
*
* To debug the rules, you can use the following page:
* https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending
*
Expand All @@ -57,7 +61,8 @@ const allResourceTypes = Object.values(ResourceType)
*/
export async function setRequestHeaders(
ua: ReadonlyUserAgentState,
filter?: { applyToDomains?: ReadonlyArray<string>; exceptDomains?: ReadonlyArray<string> }
filter?: { applyToDomains?: ReadonlyArray<string>; exceptDomains?: ReadonlyArray<string> },
sendPayload: boolean = false
): Promise<Array<Rule>> {
const condition: chrome.declarativeNetRequest.RuleCondition = {
resourceTypes: allResourceTypes,
Expand Down Expand Up @@ -108,8 +113,6 @@ export async function setRequestHeaders(

return []
})()
.map((b) => `"${b.brand}";v="${b.version}"`)
.join(', ')

const brandsWithFull = (() => {
switch (ua.browser) {
Expand All @@ -123,13 +126,23 @@ export async function setRequestHeaders(

return []
})()
.map((b) => `"${b.brand}";v="${b.version}"`)
.join(', ')

const setPlatform = platform(ua.os)
const setIsMobile = isMobile(ua.os)

const payload: ContentScriptPayload = {
current: ua,
brands: {
major: brandsWithMajor,
full: brandsWithFull,
},
platform: setPlatform,
isMobile: setIsMobile,
}

const rules: Array<Rule> = [
{
id: RuleIDs.ReplaceUserAgent,
priority: 1,
action: {
type: RuleActionType.MODIFY_HEADERS,
requestHeaders: [
Expand All @@ -144,33 +157,32 @@ export async function setRequestHeaders(
},
{
id: RuleIDs.ReplaceClientHints,
priority: 2,
action: {
type: RuleActionType.MODIFY_HEADERS,
requestHeaders: [
brandsWithMajor
? {
operation: HeaderOperation.SET,
header: HeaderNames.CLIENT_HINT_BRAND_MAJOR,
value: brandsWithMajor,
value: brandsWithMajor.map((b) => `"${b.brand}";v="${b.version}"`).join(', '),
}
: { operation: HeaderOperation.REMOVE, header: HeaderNames.CLIENT_HINT_BRAND_MAJOR },
brandsWithFull
? {
operation: HeaderOperation.SET,
header: HeaderNames.CLIENT_HINT_BRAND_FULL,
value: brandsWithFull,
value: brandsWithFull.map((b) => `"${b.brand}";v="${b.version}"`).join(', '),
}
: { operation: HeaderOperation.REMOVE, header: HeaderNames.CLIENT_HINT_BRAND_FULL },
{
operation: HeaderOperation.SET,
header: HeaderNames.CLIENT_HINT_PLATFORM,
value: `"${platform(ua.os)}"`,
value: `"${setPlatform}"`,
},
{
operation: HeaderOperation.SET,
header: HeaderNames.CLIENT_HINT_MOBILE,
value: isMobile(ua.os) ? '?1' : '?0',
value: setIsMobile ? '?1' : '?0',
},
{ operation: HeaderOperation.REMOVE, header: HeaderNames.CLIENT_HINT_FULL_VERSION },
{ operation: HeaderOperation.REMOVE, header: HeaderNames.CLIENT_HINT_PLATFORM_VERSION },
Expand All @@ -180,6 +192,23 @@ export async function setRequestHeaders(
},
]

if (sendPayload) {
rules.push({
id: RuleIDs.ProvidePayload,
action: {
type: RuleActionType.MODIFY_HEADERS,
responseHeaders: [
{
operation: HeaderOperation.SET,
header: HeaderNames.SERVER_TIMING,
value: `${__UNIQUE_HEADER_KEY_NAME__};desc="${btoa(JSON.stringify(payload)).replace(/=/g, '_')}"`,
},
],
},
condition,
})
}

await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: Object.values(RuleIDs), // remove existing rules
addRules: rules,
Expand Down
1 change: 0 additions & 1 deletion src/entrypoints/background/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export { setRequestHeaders, unsetRequestHeaders } from './http-requests'
export { setBridgeData, unsetBridgeData } from './content-script-bridge'
export { registerContentScripts } from './scripting'
2 changes: 1 addition & 1 deletion src/entrypoints/background/hooks/scripting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export async function registerContentScripts() {
// so we need to register the content scripts without the "world" property
//
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/RegisteredContentScript#browser_compatibility
return await chrome.scripting.registerContentScripts([content, inject])
return await chrome.scripting.registerContentScripts([content])
}

throw err
Expand Down
4 changes: 1 addition & 3 deletions src/entrypoints/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { checkPermissions, detectBrowser, watchPermissionsChange } from '~/share
import { type HandlersMap, listen as listenRuntime } from '~/shared/messaging'
import { newErrorEvent, newExtensionLoadedEvent } from '~/shared/stats'
import { isApplicableForDomain, reloadRequestHeadersAndBridge, renewUserAgent, updateRemoteUserAgentList } from './api'
import { registerContentScripts, unsetBridgeData, unsetRequestHeaders } from './hooks'
import { registerContentScripts, unsetRequestHeaders } from './hooks'
import { registerHotkeys } from './hotkeys'
import { CurrentUserAgent, RemoteUserAgentList, Settings, StorageArea, UserID } from './persistent'
import { type Collector as StatsCollector, GaCollector } from './stats'
Expand Down Expand Up @@ -148,8 +148,6 @@ let stats: StatsCollector | undefined = undefined
await Promise.allSettled([
// disable headers replacement
unsetRequestHeaders(),
// disable the javascript protection
unsetBridgeData(),
// disable the user-agent renewal timer
userAgentRenewTimer.stop(),
// disable the remote user-agents list update timer
Expand Down
Loading

0 comments on commit 212d75f

Please sign in to comment.