I am trying to develop a chrome tool to spoof HTTP request and response headers. Request spoofing works fine. This code changes UA in request header but in response header I can't change anything. e.g. I am trying to change "Set-Cookie" but it won't work. I have used two codes for response. Here's my code:
Request
var requestFilter = {
urls: [ "<all_urls>" ]
},
extraInfoSpec = ['requestHeaders','blocking'],
handler = function( details ) {
var headers = details.requestHeaders,
blockingResponse = {};
for( var i = 0, l = headers.length; i < l; ++i ) {
if( headers[i].name == 'User-Agent' ) {
headers[i].value = 's';
break;
}
}
blockingResponse.requestHeaders = headers;
return blockingResponse;
};
chrome.webRequest.onBeforeSendHeaders.addListener( handler, requestFilter, extraInfoSpec );
Response
chrome.webRequest.onHeadersReceived.addListener(function(details){
details.responseHeaders[details.responseHeaders.length] = {name: 'Set-Cookie', value: 'some random value'};
return {responseHeaders: details.responseHeaders};
},{urls:["<all_urls>"],types:["xmlhttprequest","sub_frame"]},
["responseHeaders","blocking"]);
Response 2
var responseListener = function(details){
var rule = {
"name": "Set-Cookie",
"value": "Some Random Value"
};
details.responseHeaders.push(rule);
return {responseHeaders: details.responseHeaders};
};
chrome.webRequest.onHeadersReceived.addListener(responseListener,
{urls: [ "*://*/*" ] },
["blocking", "responseHeaders"]);
Related
An API request like this: const response = await this.publicGetMarkets (params); is giving me a response that contains a list of markets in the following format:
{
"markets": {
"LINK-USD": {
"market": "LINK-USD",
"status": "ONLINE"
},
...
}
As in the example here, my problem is that LINK-USD is changing for every market.
How do I fix my code so that I can variables such as market, status in my code.
I have written the following code snippet:
const market = this.safeValue (response, 'markets');
const result = [];
for (let i = 0; i < markets.length; i++) {
const markets = this.safeString (markets, {}, {});
const market = this.safeString (markets, 'market');
const status = this.safeString (markets, 'status');
result.push({
'market': market,
'status': status,
});
}
return result;
You can get an array of all the inner objects using Object.values(data.markets).
If you need to filter out unwanted properties that is a fairly simple mapping addition to this also
const data = {
"markets": {
"LINK-USD": {
"market": "LINK-USD",
"status": "ONLINE"
},
"LINK-EURO": {
"market": "LINK-EURO",
"status": "TBD"
}
}
}
const res = Object.values(data.markets)
console.log(res)
const responses = this.safeValue (response, 'markets');
const result = [];
for (let response of responses) {
const market = responses.markets["LINK-USD"].market,
status = responses.markets["LINK-USD"].status;
result.push({market, status});
}
return result;
I hope this is what you asked for.
I am trying to integrate with a service (paysera https://developers.paysera.com/) that uses HMAC Authentication. I've manage to integrate every GET endpoint. Nevertheless, when it comes to the POST request it seems the code is not working.
createHMACAuth(data) {
let bodyHash = crypto.createHash('sha256').update(JSON.stringify(data)).digest('base64');
let method = 'POST';
let path = `/rest/v1/transfers`;
let ts = moment().unix();
let nonce = GUID(32);
let port = 443;
let macString = `${ts}\n${nonce}\n${method}\n${path}\n${host}\n${port}\n${bodyHash || ''}\n`;
let my_mac_key = 'my_mac_key';
let my_mac_id = 'my_mac_id';
let mac = crypto.createHmac('sha256', my_mac_key).update(macString).digest('base64');
let headerString = `MAC id="${my_mac_id}", ts="${ts}", nonce="${nonce}", mac="${mac}", ext="body_hash=${bodyHash}"`;
return headerString;
}
let data = {
key: 'value',
otherkey: 'othervalue'
};
let headers = {
Host: 'wallet.paysera.com',
'User-Agent': `Paysera node.js library`,
mac_id: 'my_mac_id',
Authorization: createHMACAuth(data);
};
POST_REQUEST(`${headers.host}/rest/v1/transfers`, data, headers, (err, res) => console.log(res))
The response I get is:
{
error: 'unauthorized',
error_description: 'Given MAC content body hash does not match actual hash of content'
}
Any help will be much appreciated!
I had an error when generating the body_hash
Fix
createHMACAuth(method, path, data) {
let bodyHash, ext;
if (method === 'POST') {
ext = `body_hash=${encodeURIComponent(this.createHash(JSON.stringify(data)))}`;
}
this.method = method;
this.path = `/${path}`;
let nonce = `${U.GUID(32)}`;
let port = 443;
let macString = `${this.ts}\n${nonce}\n${this.method}\n${this.path}\n${this.host}\n${port}\n${ext || ''}\n`;
let mac = this.createHMACHash(macString);
let headerString = `MAC id="${this.mac_id}", ts="${this.ts}", nonce="${nonce}", mac="${mac}"`;
if (method === 'POST') headerString += `, ext="${ext}"`
return headerString;
}
Your answer helped me make it work. Full code for other people that might need this.
import crypto from 'crypto'
import fetch from 'node-fetch'
function createHash(data) {
return crypto.createHash('sha256').update(data).digest('base64');
}
function createHMACHash (macKey, macString) {
return crypto.createHmac('sha256', macKey).update(macString).digest('base64');
}
async function createHMACAuth() {
const macId = 'your-mac-id';
const macKey = 'your-mac-key';
const ts = new Date().getTime();
const nonce = 'nQnNaSNyubfPErjRO55yaaEYo9YZfKYU';
const method = 'POST';
const uri = '/rest/v1/transaction'
const host = 'wallet.paysera.com'
const port = 443;
const data = {
"payments": [
{
"description": "Payment for order No. 1234",
"price": 1299,
"currency": "EUR",
"parameters": {
"orderid": 1234
}
}
],
"redirect_uri": "http://www.example.com/somePage"
}
let ext;
if (method === 'POST') {
ext = `body_hash=${encodeURIComponent(createHash(JSON.stringify(data)))}`;
}
let macString = `${ts}\n${nonce}\n${method}\n${uri}\n${host}\n${port}\n${ext || ''}\n`;
let mac = createHMACHash(macKey, macString);
let headerString = `MAC id="${macId}", ts="${ts}", nonce="${nonce}", mac="${mac}"`;
if (method === 'POST') headerString += `, ext="${ext}"`
const response = await fetch(`https://${host}${uri}`,{
method:method,
headers:{
Authorization: headerString,
'Content-Type':'application/json'
},
body: JSON.stringify(data)
})
return headerString;
}
await createHMACAuth()
I am trying to add all the people I follow to a new Twitter list(named personal, I created) but I am getting error 404 with my code (I created a developer Twitter account and passed the credentials, which is working fine):
Here is the script (resetting on 80, as I read I can't add directly more than 80 people, though here I am just passing two Twitter handles only):
[Also, is this going as a get request, does it need to go as a post, if so, how do I send a post request in this]
//Include the node module
var Twitter = require( 'twitter-node-client' ).Twitter;
//Get this data from your twitter apps dashboard
var config = {
//demo values
"consumerKey": "zKuw",
"consumerSecret": "isdfsd",
"accessToken": "852",
"accessTokenSecret": "81c",
"callBackUrl": "http://localhost:3000/" // Do I need to change it?
};
//Init the Twitter API client with the API key
var twitter = new Twitter( config );
//Callback functions
var error = function ( err, response, body ) {
console.log( err );
};
var success = function ( data ) {
console.log( data );
};
// List to add, adding two handles initially
var myList = "bchesky, sama";
console.log( myList );
var myStrings = myList.split( "," );
console.log( myStrings );
let i = 0;
let j = 0;
var myText = "";
while ( ( i + j ) < myStrings.length ) {
myText += myStrings[ i + j ];
i++;
if ( i == 80 || i + j >= myStrings.length ) {
j = j + i;
i = 0;
//Add members
twitter.listAddMembers( {
owner_screen_name: "abhishek_123",
slug: "personal",
list_id: 133851,
screen_name: myText
}, error, success );
console.log( myText );
myText = "";
}
else {
myText += ", ";
}
}
And the error/output I am getting is :
Abhisheks-MacBook-Air:upload-twitter-list-master abhishek$ node server.js
bchesky, sama
[ 'bchesky', ' sama' ]
bchesky, sama
URL [https://api.twitter.com/1.1/lists/members/create_all.json]
{
statusCode: 404,
data: '{"errors":[{"code":34,"message":"Sorry, that page does not exist."}]}'
}
Thanks in advance, every help is highly appreciated.
I want to add header AppVersion to my chrome os app
here what I did
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
const newHeader = {name:"appVersion", value:"chrome|2.1"};
const responseHeaders = details.responseHeaders.concat(newHeader);
return { responseHeaders };
},
// filters
{
urls: ["https://website.link/*"],
},
// extraInfoSpec
["blocking","responseHeaders", "extraHeaders"]
);
but it is not working
I have a question regarding parse cloud code. The following cloud code was working before migration written in cloud code but after migration its not returning desired output.
var streamClass = Parse.Object.extend("Streams");
streamObj = new streamClass({
objectId: "dummy",
streamerId: usersArr[i]
});
streamObj.dirty = function() {return false;};
There are two entities i.e. streams and users. Every user has streams. So there is users pointer(streamerId) in stream table. If user do not have any stream created then i am creating a stream dummy object and setting user(streamerId) as a pointer in stream object. When this code was called as a API, it was returning stream dummy object with user(streamerId) information before parse server migration. After migration the above code gives the following output.
{
"result": [
{
"__type": "Pointer",
"className": "Streams",
"objectId": "dummy"
}
]
}
It can noticed that there is no user(streamerId) information in the output. Can anyone please help me in this regard.
I am not saving this streamObj. I am returning this streamObj to IOS app. I also tested it through postman in google chrome. The following is a complete function which takes array of users object and array of streams objects and return one object contains user and its related streams.
function getUsersAndRecentStreams(usersArr, streamsArr) {
var responseObj = [];
var moment = require('moment');
var now = moment();
var currentDate = new Date();
for( var i=0; i<usersArr.length; i++ ) {
var streamObj = null;
for( j=0; j<streamsArr.length; j++ ) {
var streamerObj = streamsArr[j].get('streamerId');
if( streamerObj.id === usersArr[i].id ) {
if( moment(streamsArr[j].get('showTimeStart')) <= now && moment(streamsArr[j].get('showTimeEnd')) >= now ) {
streamObj = streamsArr[j];
break;
}
if( streamObj == null) {
streamObj = streamsArr[j];
}
else {
if( moment(streamsArr[j].get('showTimeStart')) <= now ) {
streamObj = streamsArr[j];
}
}
}
}
if( streamObj == null ) {
var streamClass = Parse.Object.extend("Streams");
streamObj = new streamClass({
objectId: "dummy",
streamerId: usersArr[i]
});
streamObj.dirty = function() {return false;};
var streamObj = new streamObj();
}
responseObj.push(streamObj);
}
return responseObj;
}
There are two cases.
1) When streamObj is not null. In this case the output is correct.
2) The second case when streamObj is null. In this case the following output is return which is not desired.
{
"result": [
{
"__type": "Pointer",
"className": "Streams",
"objectId": "dummy"
}
]
}
When streamObj is null, The following desired output should return this function.
{
"result": [
{
"__type": "Pointer",
"className": "Streams",
"objectId": "dummy",
"StreamerId": userObject
}
]
}