Chrome Extension - not sending cookies in the request - google-chrome-extension

I've read tons of questions on SO, tried multiple things but to no luck. My question would be similar, but I'm posting because I've tried everything but still not succeeded.
I want to check whether there's a user session maintained at my server. I've a webservice which returns a boolean value, based on the cookies received.
It's the responsibility of the browser to send cookies (if any) while requesting the server. So, when I request via the chrome-extension, theoretically the browser should send along the cookies too. However, it does not.
Here's my code:-
content.js
fetch('https://zoffers.in/apis/shops/get_aff_url/', {
credentials: 'include',
mode: 'cors',
async: false,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})
.then(function(data) {
})
.catch(function(error) {
})
Manifest.json
{
"manifest_version": 2,
"version": "0.1",
"content_scripts": [{
"matches": [
"https://*/*/"
],
"js": ["js/content.js"],
"run_at": "document_start"
}],
"browser_action": {
// "default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Click here!"
},
"permissions": [
"identity",
"identity.email",
"tabs",
"notifications",
"cookies",
"https://zoffers.in/"
]
}
What wrong am I doing? Can anyone please help me through it.
UPDATED
content.js
message = {
'event_type': 'Event1',
}
chrome.runtime.sendMessage(message);
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
if(request.event_type === 'Event1'){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
fetch('https://zoffers.in/apis/shops/get_aff_url/', {
credentials: 'include',
mode: 'cors',
async: false,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})
.then(function(data) {
})
.catch(function(error) {
})
}
}
}
);
Have added background.js to manifest.json file. But still not working.

You can use standard Cookies api and access cookies for any URL that is available.

You might need to set the SameSite attribute of the cookies to None.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
You may also have to set your browser to accept third-party cookies.

Related

Problem with CORS in Nest.js app after deployment on Vercel

POST request in my Nest.js app not working after deployment on Vercel and I receive CORS error, but cors in my app is enable and when I send GET request all working. When I test my request in postman all working. I am not sure but maybe this error can happen through that I use React Query or problem with vercel and I not right deployment my app.
I receive such error:
Access to XMLHttpRequest at 'https://server-store.vercel.app/api/auth/login' from origin 'https://next-store-liard-three.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And I enabled CORS such method:
app.enableCors({
origin: ['http://localhost:3000', 'https://next-store-liard-three.vercel.app'],
allowedHeaders: ['Accept', 'Content-Type'],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
});
This is my file vercel.json:
{
"version": 2,
"name": "next-store-server",
"buildCommand": "npm start",
"installCommand": "npm install",
"builds": [
{
"src": "dist/main.js",
"use": "#vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "dist/main.js",
"methods": ["GET", "POST", "PATCH", "PUT", "DELETE"]
}
]
}
Also I try enable CORS other way, but it is not help me.
I try enable CORS, such method:
const app = await NestFactory.create(AppModule, { cors: true });
On client I using Next.js, reactQuery and axios for sending request
import axios from "axios";
import { FAuth, IUser } from "./Auth.types";
const AuthService = {
async registration(dto: IUser) {
const { data } = await axios.post<FAuth>(
`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/registration`,
dto,
);
return data;
},
async login(dto: IUser) {
const { data } = await axios.post<FAuth>(`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/login`, dto);
return data;
},
};
This my custom useMutation hooks
export const useRegistration = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.registration(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
export const useLogin = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.login(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
Try to add "OPTIONS" into methods, this worked for me
vercel.json:
{
"version": 2,
"builds": [{ "src": "src/main.ts", "use": "#vercel/node" }],
"routes": [
{
"src": "/(.*)",
"dest": "src/main.ts",
"methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
}
]
}

How to inject remote CSS file onto current tab? [Chrome Extension Manifest V3]

Does anyone know how to inject a remote CSS file onto current tab without downloading it and adding to my extension package?
Here's the code I'm running:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
{
var activeTab = tabs[0];
chrome.scripting.insertCSS
({
target: { tabId: activeTab.id },
files: ['https://fonts.googleapis.com/css2?family=Acme']
});
chrome.scripting.insertCSS
({
target: { tabId: activeTab.id },
css: 'body{font-family:Acme !important;}'
});
});
I get the following error:
Uncaught (in promise) Error: Could not load file: 'https://fonts.googleapis.com/css2?family=Acme'.
Here's sections of the manifest I've added without luck:
"host_permissions":
[
"https://fonts.googleapis.com",
"https://fonts.gstatic.com"
],
"web_accessible_resources":
[
{
"resources": [ "css2?family=Acme" ],
"matches": [ "https://fonts.googleapis.com/*" ]
},
{
"resources": [ "MwQ5bhbm2POE2V9BPQ.woff2" ],
"matches": [ "https://fonts.gstatic.com/*" ]
}
]
Here's one workaround for my problem that actually gives me the result I'm looking for by storing the content of the remote CSS file into a string first. It's a bit hacky and relies on jQuery. Would still like to find a better way.
$.ajax
({
type:'GET',
url:'https://fonts.googleapis.com/css2?family=Acme',
success: function(fontCss)
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
{
var activeTab = tabs[0];
var customCss = 'body{font-family:Acme !important;}';
var fullCss = fontCss + customCss;
chrome.scripting.insertCSS
({
target: { tabId: activeTab.id },
css: fullCss
});
});
}
});

Why is the library I injected into my background script missing it's prototype methods?

I'm injecting a custom library into my background script in my chrome extension. There are methods on the prototype of the object but when I test my extension it says the method I am calling is undefined. I pop open the debugger to find that all of my libraries prototype methods are missing. Here is my manifest:
{
"name": "Travelers Learning",
"version": "1.0",
"description": "Chrome extension to enable xAPI",
"background": {
"scripts": ["tx.js", "main.js"],
"persistent": true
},
"permissions": [
"activeTab",
"tabs"
],
"content_scripts": [
{
"run_at": "document_end",
"matches": ["http://*/*", "https://*/*"],
"js": [ "ramda.js", "tincan.js", "interactionProfile.js", "tx.js", "all.js"]
},
{
"run_at": "document_end",
"matches": ["*://*.youtube.com/*"],
"js": ["interactionProfile.js", "tx.js", "youtube.js"]
}
],
"browser_action": {
"default_popup": "main.html"
},
"manifest_version": 2
}
//all.js
chrome.runtime.sendMessage({contentScriptQuery: ''}, (tx) => {
// This callback catches a newly created instance of my tx library, it has some variables on it but the prototype methods are missing. The prototype methods are missing from any sub objects too.
tx.registerProfile('launched', interactionProfile);
tx.sendStatement('launched', {
verbLabel: 'experienced',
userEmail: tx.getUserId(),
UUID: tx.getUUID(),
objectID: 'Page Title',
objectDisplayName: 'Page Title',
iriRoot: 'http://adlnet.gov/expapi/verbs/'
});
});
//main.js
chrome.tabs.onActivated.addListener(function (tabInfo){
chrome.tabs.get(tabInfo.tabId, function(tab) {
console.log(tab);
});
});
chrome.runtime.onMessage.addListener(
(request, sender, sendResponse) => {
tx.TX.create({
endpoint: '*****',
username: '*****',
password: '*****',
allowfail: false,
env: "sandbox",
xapiEndpoint: '*****'
})
.then((tx) => {
// Prototype methods are still present here.
return sendResponse(tx)
});
return true;
});

How to log cookies from a cookie jar?

How can I log cookies that are stored in a cookie jar using the request-promise npm module.
I have tried printing the cookie jar variable but as expected that does not work.
How I am creating the jar,
var request = require('request-promise');
var sess = request.jar()
The code sending the request,
request({url: myurl, jar: sess}, function () {
request(
{
url: 'myurl',
method: 'POST',
headers: [
{
"Accept": "application/json",
}
],
postData: {
"xqr":"1"
}
}
)
I expect all the cookies used to send my request to be printed out using console.log()
request uses tough-cookie internally. So you can easily access to tough-cookie store which is an abstract class and use its prototype function getAllCookies.
function logCookies(jar){
jar._jar.store.getAllCookies(function(err, cookieArray) {
if(err) throw new Error("Failed to get cookies");
console.log(JSON.stringify(cookieArray, null, 4));
});
}
And this will log all cookies and its properties.
[
{
"key": "1P_JAR",
"value": "1P_JAR_VALUE",
"expires": "2019-01-23T20:09:38.000Z",
"domain": "google.com",
"path": "/",
"hostOnly": false,
"creation": "2018-12-24T20:09:37.800Z",
"lastAccessed": "2018-12-24T20:09:38.097Z"
},
{
"key": "NID",
"value": "NID_VALUE",
"expires": "2019-06-25T20:09:38.000Z",
"domain": "google.com",
"path": "/",
"httpOnly": true,
"hostOnly": false,
"creation": "2018-12-24T20:09:37.802Z",
"lastAccessed": "2018-12-24T20:09:38.098Z"
}
]
If you only want to get raw cookie string you can just simply use
console.log(cookieArray.map(cookie => cookie.toString()))
And it will give you
[
'1P_JAR=1P_JAR_VALUE; Expires=Wed, 23 Jan 2019 20:15:02 GMT; Domain=google.com; Path=/',
'NID=NID_VALUE; Expires=Tue, 25 Jun 2019 20:15:02 GMT; Domain=google.com; Path=/; HttpOnly'
]

"RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request: reason: invalid patch for uri urlList.json: invalid path: /test/

I have a marklogic database with the following JSON document named urlList.json
{
"test": {
"ip": "10.10.10.10",
"fqdn": "www.test.test"
}
}
I am trying to add to the test object with the marklogic rest API using patch. I am using Node with the request-promise module here is the code
var options = {
method: 'PATCH',
url: 'https://test:8000/v1/documents',
qs: { database: databaseName, uri: 'urlList.json' },
headers:
{
'Content-Type': 'application/json',
Accept: 'application/json'
},
strictSSL: false,
auth: {
user: userName,
pass: password,
sendImmediately: false
},
body: JSON.stringify({
"patch": [
{
"insert": {
"context": "/test/",
"position": "last-child",
"content": { "test": "test"}
}
}
]
})
};
request(options)
.then(results => {
return resolve(results);
})
.catch(err => {
return reject(err);
})
The desired outcome when it runs is
{
"test": {
"ip": "10.10.10.10",
"fqdn": "www.test.test",
"test": "test"
}
}
I get the following error every time I run it
"400 - "{\"errorResponse\":{\"statusCode\":400, \"status\":\"Bad
Request\", \"messageCode\":\"RESTAPI-INVALIDREQ\",
\"message\":\"RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request:
reason: invalid patch for uri urlList.json: invalid path: /test/\"}}""
Here is the body that is sent
"{"patch":[{"insert":{"context":"/test/","position":"last-
child","content":{"test":"test"}}}]}"
A path must select a node. For that reason, a path can't end with a separator. That's what the message attempts to convey.
Does it work with a path of /test?
By the way, MarkLogic provides a Node.js API with support for promises. That might be easier to work with.
Hoping that helps,

Resources