Chrome Extension - chrome.webRequest - Unknown error in requestBody - google-chrome-extension

I'm trying to logout file information that is being uploaded through the browser with a chrome extension. In V3.
Minimal steps to reproduce:
background.js
chrome.webRequest.onBeforeRequest.addListener(
(details) => {
if (details.method.toUpperCase() !== "POST") return;
if (!details.requestBody) return;
if (details.url.includes("put_block")) {
console.log(details);
}
},
{ urls: ["<all_urls>"] },
["requestBody"]
);
console.log:
{
...
requestBody: { error: 'Unknown error.' },
...
}
I'm testing my extension by uploading images to dropbox
When looking at the network tab I can see a post-request with this payload to:
https://dl-web.dropbox.com/put_block_returning_token?...
requestBody: { error: 'Unknown error.' },
how come I can't get anything meaningful in the service worker?

Related

Why would a server deny a request?

I am working on a chrome extension that creates an Anki card and adds it to my desk.
Right now am I trying to get the request to work using the Anki API.
For some reason the server is denying my request.
Here is my code (JavaScript) to create a card and send it as a request to the localhost:
async function createCard() {
// Set the Anki API endpoint URL
const baseURL = 'http://localhost:8765';
// Set the Anki API action, version and params
const card = {
"action": "addNote",
"version": 6,
"params": {
"note": {
"deckName": "Default",
"modelName": "Basic",
"fields": {
"Front": "front content",
"Back": "back content"
},
"options": {
"allowDuplicate": false,
"duplicateScope": "deck",
"duplicateScopeOptions": {
"deckName": "Default",
"checkChildren": false,
"checkAllModels": false
}
}
}
}
};
// Send the request to the Anki API
try {
const response = await fetch(baseURL, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(card)
});
// Check the status code of the response
if (response.ok) {
console.log('Card created successfully');
} else {
console.error(`Error creating card: ${response.statusText}`);
}
} catch (error) {
console.error(`Error creating card: ${error}`);
}
}
(The card by now is hardcoded.)
When I execute this code I get 2 errors thrown by chrome:
POST http://localhost:8765/ net::ERR_ABORTED 403 (Forbidden)
Error creating card:
The first error happens on the fetch function
and the second error at "console.error('Error creating card: ${response.statusText}');"
I suggest that the second error appears due to the first one.
Since I am new to computer science, all I tried so far is checking the logs of ANKI to find information about the error, but I couldn't find something. I tried different syntax to create the card since I pass this into the fetch function where the error occurs.
The localhost is running while I am working on this, so the server is accessible.
My solution is setting the webCorsOriginList config of AnkiConnect as "*"
"webCorsOriginList": ["*"]
It will allow CORS for all domains.

Missing credentials while calling YouTube insert API

I want to use API key instead of OAuth token to call insert API from YouTube v3 lib. Code snippet is like below:
await google
.youtube("v3")
.videos.insert({
key: "my-youtube-api-key",
part: "id,snippet,status",
notifySubscribers: false,
requestBody: {
snippet: {
title: "Test video title",
description: "Test video description",
},
status: {
privacyStatus: "public",
},
},
media: {
body: fs.createReadStream(filePath),
},
})
.catch((err) => {
console.log("Upload to YouTube failed", err);
return null;
});
However, I am hitting error code 401, message is:
code: 401,
errors: [
{
message: 'Login Required.',
domain: 'global',
reason: 'required',
location: 'Authorization',
debugInfo: 'Authentication error: missing credentials.',
locationType: 'header'
}
]
How can I fix this issue? Isn't API key not supported? Thanks!
As per the docs, it's insufficient to use an API key on Videos.insert endpoint; you'll have to be properly authorized to call this endpoint:
Authorization
This request requires authorization with at least one of the following scopes (read more about authentication and authorization).
Scope
https://www.googleapis.com/auth/youtube.upload
https://www.googleapis.com/auth/youtube
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube.force-ssl

Firebase Cloud Functions: Requests from referer <empty> are blocked. - PERMISSION_DENIED

I am not sure why the following code is throwing google api key permission denied.
I have the api or service enabled both in firebase console and google console.
export async function createJobDynamicLink(job){
if(job.jobStatus !== 'approved' || (job.dynamicLink).length > 2){
console.log('Dynamic link already exist!');
return false;
}
console.log(dynamic_links);
console.log(dynamic_links_key);
// Firebase web api key logs just fine
const options = {
method: 'POST',
uri: `https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=${dynamic_links_key}`,
body: {
"longDynamicLink": makeDynamicLongLink(job)
},
json: true
};
return await requestpromise(options)
.then(function (parsedBody) {
console.log(parsedBody);
return parsedBody.shortLink;
})
.then((shortLink) => {
//post.shareUrl = shortLink;
console.log('short link: ' + shortLink);
//return event.data.ref.set(post);
return shortLink;
})
}
export async function makeDynamicLongLink(job) {
return buildUrl(`${dynamic_links}`, {
queryParams: {
link: `https://app.com/jobs/${slugify(job.jobTitle)}-${job.id}`,
apn: "com.app.appe",
ibi: "com.app.app",
dfl: "https://app.com",
st: job.jobTitle,
}
});
}
Is something wrong with the way I am doing the request using request-promise?
StatusCodeError: 403 - {
"error": {
"code": 403,
"message": "Requests from referer <empty> are blocked.",
"status": "PERMISSION_DENIED",
"details": [{
"#type": "type.googleapis.com/google.rpc.Help",
"links": [{
"description":"Google developer console API key",
"url": "https://console.developers.google.com/project/904573jjwj/apiui/credential"
}]
}]
}
}
Go to the Google API Credentials https://console.developers.google.com/apis/credentials and see if there is any restriction on your API Key you're using.
If it is restricted by HTTP referrers, then add your website domain to it and add the Referrer header like the above answer.
Although in your use case, None or IP address restriction is a better choice.
Because you are invoking your function from a node.js environment, the HTTP Header Referer isn't being set. When you create requests through a browser, the browser will automatically fill this field for you.
You can get a suitable referrer value using:
"https://" + process.env.GCLOUD_PROJECT + ".cloudfunctions.net/createJobDynamicLink"
// becomes "https://your-project-id.cloudfunctions.net/createJobDynamicLink"
This generated URL isn't callable, because it doesn't start with a region, but it means you now have a URL that can be used to identify that the call is coming from a Cloud Function.
To use it, add it to your request-promise options object.
const options = {
method: 'POST',
uri: `https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=${dynamic_links_key}`,
body: {
"longDynamicLink": makeDynamicLongLink(job)
},
headers: {
"Referer": "https://" + process.env.GCLOUD_PROJECT + ".cloudfunctions.net/createJobDynamicLink"
},
json: true
};
Note: I'd use request-promise-native instead of request-promise - same API but skips loading Bluebird.
In my case i had
<meta name="referrer" content="no-referrer">
in the head so the referer was not being sent

Domains are not being added, Whitelist domains facebook messenger extension

I've been trying to whitelist my domains following the instruction that is given by facebook but nothing is working.
I first tried with curl, the response is {result:"success"} but when I try to list the domains that are whitelisted I am getting {data:[]}
Then I tried using node request module as follow:
request.post("https://graph.facebook.com/v2.6/me/messenger_profile?access_token=sfdlksdfu79r9429049824982342348sjdfsf", {
"setting_type": "domain_whitelisting",
"whitelisted_domains": ["https://mydomainw.com", "https://mydomainw.com/profile", "https://sfujyx.com/ofr", "mydomain1.com", "mydomain.com"],
"domain_action_type": "add"}, function (err, res, body) {
console.log("Whitelisting domain");
if (!err) {
console.log(body);
console.log("Showing the list of whitelisted:");
request.get("https://graph.facebook.com/v2.6/me/messenger_profile?fields=whitelisted_domains&access_token=sfdlksdfu79r9429049824982342348sjdfsf", function (err, res, body) {
if (!err) {
console.log(body);
} else {
console.log(err);
}
});
} else {
console.log(err);
}
});
Still it bring the same result as curl :
And when I use Facebook Graph Api Explorer tool, here is the error I am getting:
I am really stuck, I don't know what should I do or how people exactly whitelist domain for messenger extension.
What I am doing wrong? why isn't the domains being added?
My project is on Google App Engine.
The problem is I was using the App Access Token instead of the Page Access Token, I didn't know the difference.
your domain: "https://mydomainw..com" is an invalid domain.
The request should return:
{
"error": {
"message": "(#100) whitelisted_domains[0] should represent a valid URL",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "Aq3AVaNVJU9"
}
}
Actually, I didn't use "setting_type" before. This is how I register domains:
var request = require("request");
var options = { method: 'POST',
url: 'https://graph.facebook.com/v2.6/me/messenger_profile',
qs: { access_token: 'my_page_token' },
headers: { 'content-type': 'application/json' },
body:
{ whitelisted_domains:
[
'https://mydomainw.com',
'https://ijuugwivbc.localtunnel.me' ] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

couchdb session and IE8

I am writing a couchapp, which uses the couch.jquery.js library.
When I login to the site with ie8, i get a successful login (it returns ok, and a login id), but when I query the session, I get a userCtx.name of null (just like if the login didn't happen).
It would seem that explorer will not keep the cookie from the login. Does anyone have any info on this?
I have tried J Chris's couchLogin.js library and written my own login scripts with the same problem.
The session code is:
$.couch.session({
success: function(data) {
console.log(JSON.stringify(data));
}
});
Response from IE:
{"ok":true,"userCtx":{"name":null,"roles":[]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"]}}
Response from Firefox / Chrome:
{"ok":true,"userCtx":{"name":"user1","roles":[]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"],"authenticated":"cookie"}}
I have solved this by editing jquery.couch.js, and adding cache:false to ajax call in the session function.
session: function(options) {
options = options || {};
$.ajax({
cache: false, //disable caching for IE
type: "GET", url: this.urlPrefix + "/_session",
beforeSend: function(xhr) {
xhr.setRequestHeader('Accept', 'application/json');
},
complete: function(req) {
var resp = $.parseJSON(req.responseText);
if (req.status == 200) {
if (options.success) options.success(resp);
} else if (options.error) {
options.error(req.status, resp.error, resp.reason);
} else {
throw "An error occurred getting session info: " + resp.reason;
}
}
});
}

Resources