Skip to content

Commit

Permalink
Stop using chrome.webRequest.onSendHeaders
Browse files Browse the repository at this point in the history
  • Loading branch information
atuchin-m committed Aug 15, 2024
1 parent d44890e commit 0ce9e93
Show file tree
Hide file tree
Showing 7 changed files with 145 additions and 69 deletions.
48 changes: 48 additions & 0 deletions scripts/brave_rewards/publisher/common/XHREvents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export class Headers {[name: string] : string}

export function makeEvent<T>(eventName: string, args: T) {
return new CustomEvent<T>(
eventName,
{detail: args}
)
}

export function subscribe<T>(eventName: string, callback: (args: T) => void) {
addEventListener(eventName, (e: CustomEvent<T>) => callback(e?.detail))
}


export class HeadersHandlerMessageEvent {
static eventName = 'header-handler-message'
url?: string;
headers: Headers;

static makeEvent(args: HeadersHandlerMessageEvent) {
return new CustomEvent<HeadersHandlerMessageEvent>(
this.eventName,
{detail: args}
)
}

static subscribe(callback: (args: HeadersHandlerMessageEvent) => void) {
addEventListener(this.eventName,
(e: CustomEvent<HeadersHandlerMessageEvent>) => callback(e?.detail))
}
}

export class RegisterHeadersHandlerEvent{
urlPattern?: string;
static eventName = 'register-header-handler'

static makeEvent(args: RegisterHeadersHandlerEvent) {
return new CustomEvent<RegisterHeadersHandlerEvent>(
this.eventName,
{detail: args}
)
}

static subscribe<T>(callback: (args: RegisterHeadersHandlerEvent) => void) {
addEventListener(this.eventName,
(e: CustomEvent<RegisterHeadersHandlerEvent>) => callback(e?.detail))
}
}
53 changes: 53 additions & 0 deletions scripts/brave_rewards/publisher/common/XHRInterceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at https://mozilla.org/MPL/2.0/. */

import {HeadersHandlerMessageEvent, RegisterHeadersHandlerEvent} from '../common/XHREvents'

let headerProcessUrlPattern: RegExp | undefined;
class CustomXMLHttpRequest extends XMLHttpRequest {
headers: {[header: string]: string} = {}
url: string | undefined;

override open(method: string, url: string | URL): void;
override open(
method: string, url: string | URL, isAsync: boolean,
username?: any): void;
override open(
method: string, url: string | URL, isAsync?: boolean,
username?: any,
password?: any): void {

this.url = url instanceof URL ? url.toString() : url
const realAsync = isAsync ? isAsync : true;
super.open(method, url, realAsync, username, password);
}

override setRequestHeader(name: string, value: string): void {
this.headers[name] = value
super.setRequestHeader(name, value)
}

override send(body?: any): void {
if (!headerProcessUrlPattern || !this.url || this.url.search(headerProcessUrlPattern) >= 0) {
window.dispatchEvent(HeadersHandlerMessageEvent.makeEvent(
{url: this.url, headers: this.headers}))
}
super.send(body)
}
}

const initHeadersHandler = (urlPattern?: string) => {
XMLHttpRequest = CustomXMLHttpRequest
headerProcessUrlPattern = urlPattern ? new RegExp(urlPattern) : undefined
}


export const initScript = () => {
RegisterHeadersHandlerEvent.subscribe((e) => {
const urlPattern = e.urlPattern
initHeadersHandler(urlPattern)
})
}

initScript()
45 changes: 8 additions & 37 deletions scripts/brave_rewards/publisher/common/webRequestHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
* You can obtain one at http://mozilla.org/MPL/2.0/. */

import { getPort } from '../common/messaging'
import {HeadersHandlerMessageEvent, RegisterHeadersHandlerEvent} from '../common/XHREvents'

let registeredOnCompletedWebRequestHandler = false
let registeredOnSendHeadersWebRequest = false

export const registerOnCompletedWebRequestHandler = (
mediaType: string,
Expand Down Expand Up @@ -41,41 +41,12 @@ export const registerOnCompletedWebRequestHandler = (
})
}

export const registerOnSendHeadersWebRequest = (
mediaType: string,
urlPatterns: string[],
extra: string[],
callback: (mediaType: string, details: any) => void
) => {
if (!mediaType || registeredOnSendHeadersWebRequest) {
return
}

registeredOnSendHeadersWebRequest = true

const port = getPort()
if (!port) {
return
}

port.postMessage({
type: 'RegisterOnSendHeadersWebRequest',
mediaType,
data: {
urlPatterns,
extra
}
})

port.onMessage.addListener(function (msg: any) {
if (!msg.data) {
return
}
switch (msg.type) {
case 'OnSendHeadersWebRequest': {
callback(msg.mediaType, msg.data.details)
break
}
}
})
export const registerHeadersHandler = (
urlPattern: string | undefined,
callback: (headers: any) => void
) => {
HeadersHandlerMessageEvent.subscribe((e) => callback(e.headers))
console.log('send RegisterHeadersHandlerEvent')
dispatchEvent(RegisterHeadersHandlerEvent.makeEvent({urlPattern}))
}
41 changes: 23 additions & 18 deletions scripts/brave_rewards/publisher/twitter/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,18 @@ const authTokenCookieRegex = /[; ]_twitter_sess=([^\s;]*)/

let lastSessionId: SessionId = null

let authHeaders: any = {}
class AuthHeaders {
[header: string]: string;
}

let authHeaders: AuthHeaders = {}

const readSessionCookie = (cookiesString: string): SessionId => {
if (!cookiesString) {
const readSessionCookie = (): SessionId => {
if (!document.cookie) {
return null
}

const match = cookiesString.match(authTokenCookieRegex)
const match = document.cookie.match(authTokenCookieRegex)
if (!match) {
return null
}
Expand All @@ -41,26 +45,27 @@ export const hasRequiredAuthHeaders = () => {
(authHeaders['x-csrf-token'] && authHeaders['x-guest-token']))
}

export const processRequestHeaders = (requestHeaders: any[]) => {
export const processRequestHeaders = (requestHeaders: {[header: string]: string}) => {
if (!requestHeaders) {
return false
}

let headers = {}
let headers = new AuthHeaders()

for (const header of requestHeaders) {
const currentSessionId = readSessionCookie()
const hasAuthChanged = (currentSessionId !== lastSessionId)
if (hasAuthChanged) {
// Clear cached auth data when session changes
lastSessionId = currentSessionId
// TODO: why it was headers = {}?
authHeaders = {}
}
for (const name in requestHeaders) {
const value = requestHeaders[name]
// Parse cookies for session id
if (header.name === 'Cookie') {
const currentSessionId = readSessionCookie(header.value as string)
const hasAuthChanged = (currentSessionId !== lastSessionId)
if (hasAuthChanged) {
// Clear cached auth data when session changes
lastSessionId = currentSessionId
headers = {}
}
} else if (authHeaderNames.includes(header.name) ||
header.name.startsWith('x-twitter-')) {
headers[header.name] = header.value
if (authHeaderNames.includes(name) ||
name.startsWith('x-twitter-')) {
headers[name] = value
}
}

Expand Down
23 changes: 11 additions & 12 deletions scripts/brave_rewards/publisher/twitter/twitterBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,9 @@ import * as types from './types'
import * as utils from '../common/utils'
import * as webRequestHandlers from '../common/webRequestHandlers'

const handleOnSendHeadersWebRequest = (mediaType: string, details: any) => {
if (mediaType !== types.mediaType || !details || !details.requestHeaders) {
return
}

if (auth.processRequestHeaders(details.requestHeaders)) {
const handleHeaders = (headers: any) => {
console.log('handleHeaders', headers)
if (auth.processRequestHeaders(headers)) {
publisherInfo.send()
}
}
Expand Down Expand Up @@ -59,12 +56,14 @@ const initScript = () => {
}
})

webRequestHandlers.registerOnSendHeadersWebRequest(
types.mediaType,
types.sendHeadersUrls,
types.sendHeadersExtra,
handleOnSendHeadersWebRequest)
tabHandlers.registerOnUpdatedTab(types.mediaType, handleOnUpdatedTab)
// TODO: remove the timeout when XHRInterceptor is injected automatically.
setTimeout( () => {
webRequestHandlers.registerHeadersHandler(
types.sendHeadersUrl,
handleHeaders)

tabHandlers.registerOnUpdatedTab(types.mediaType, handleOnUpdatedTab)
}, 5000);
})

console.info('Greaselion script loaded: twitterBase.ts')
Expand Down
3 changes: 1 addition & 2 deletions scripts/brave_rewards/publisher/twitter/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,4 @@ export const mediaType = 'twitter'
export const mediaDomain = 'twitter.com'

export const baseApiUrl = 'https://api.' + location.hostname
export const sendHeadersUrls = [baseApiUrl + '/1.1/*']
export const sendHeadersExtra = ['requestHeaders', 'extraHeaders']
export const sendHeadersUrl = baseApiUrl + '/1.1/*'
1 change: 1 addition & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const rewardsDir = 'scripts/brave_rewards'
const togetherDir = 'scripts/brave_talk'

const allEntries = [
`${rewardsDir}/publisher/common/XHRInterceptor`,
`${rewardsDir}/publisher/github/githubBase`,
`${rewardsDir}/publisher/github/githubAutoContribution`,
`${rewardsDir}/publisher/reddit/redditBase`,
Expand Down

0 comments on commit 0ce9e93

Please sign in to comment.