Why are all sites blocked when I use declarativeNetRequest.updateDynamicRules - google-chrome-extension

I need to block some http requests with new manifest v3. I try to use declarativeNetRequest.updateDynamicRules, but any rule blocks all requests, and I can't open any site. For example https://developer.chrome.com.
Code example:
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [232],
addRules: [{
id: 232,
"condition": { "urlFilter": "analytics", "resourceTypes": ["main_frame"] },
action: {
"type": "block",
},
}]
});
Can somebody help me?)

Related

Why does a rule added and immediately removed with declarativeNetRequest.updateDynamicRules not get removed even after the extension is reloaded?

I am trying to write an extension in Manifest Version 3, where I want to modify cookie headers for certain requests. Since the rule will only be applied to specific requests that meets my conditions,
I thought of adding a dynamic rule temporarily for that request, modify the cookie header, and immediately remove it. Here's the function for that rule.
if (condition) {
function makeNewRule(url) {
chrome.declarativeNetRequest.updateDynamicRules(
{
addRules:
[
{
"id": 1000,
"priority": 100,
"action": {
"type": "modifyHeaders",
"requestHeaders": [
{
"header": "cookie",
"operation": "set",
"value": "Modified cookie value 1"
}
]
},
"condition": {
"urlFilter" : url,
"resourceTypes":
["csp_report", "font", "image",
"main_frame", "media", "object",
"other", "ping", "script",
"stylesheet", "sub_frame",
"webbundle", "websocket",
"webtransport"]
}
}
],
removeRuleIds: [1000],
});
}
}
While this works for all requests that meet my condition, and the cookies are being modified observed in the chrome developers tool network window, the rule persists for a later session, even if I reload/update the unpacked extension. If I change the value of the cookie header to ""Modified cookie value 2", the developers tools still shows the previous "Modified cookie value 1". Therefore, I am assuming that the rule that I added is not being removed, and it is persisting across browser sessions. I tried cleaning the cache and reloading the browser. Additionally,
chrome.declarativeNetRequest.getDynamicRules(
e => console.log(e)
);
The snippet above shows the existence of the rule even when removed. How do I remove the rule that I added dynamically within that session?
I update my dynamic rules by removing and then adding them, I'll share my code with you, I hope it helps.
To update rules
function UpdateIntercept(token: string) {
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: GetInterceptRules(token).map((rule) => rule.id), // remove existing rules
addRules: GetInterceptRules(token)
});
chrome.declarativeNetRequest.getDynamicRules(
e => console.log(e)
);
}
then when I intercept the url
function GetInterceptRules(token: string) {
const allResourceTypes =
Object.values(chrome.declarativeNetRequest.ResourceType);
return [
{
id: 1,
priority: 1,
action: {
type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
requestHeaders: [
{
operation: chrome.declarativeNetRequest.HeaderOperation.SET,
header: 'Authorization',
value: 'Bearer ' + token,
},
]
},
condition: {
urlFilter: liveApiUrl,
initiatorDomains: ["mail.google.com"],
resourceTypes: allResourceTypes,
}
},
{
id: 2,
priority: 1,
action: {
type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
requestHeaders: [
{
operation: chrome.declarativeNetRequest.HeaderOperation.SET,
header: 'Authorization',
value: 'Bearer ' + token,
},
]
},
condition: {
urlFilter: testApiUrl,
initiatorDomains: ["mail.google.com"],
resourceTypes: allResourceTypes,
}
}
];
}
To intercept the url you want
function interceptURL(requestDetails: chrome.webRequest.WebRequestBodyDetails) {
console.log('intercepted: ' + requestDetails.url);
if (requestDetails.url.includes(liveApiUrl) || requestDetails.url.includes(testApiUrl)) { //maybe the inclue
chrome.runtime.sendMessage({ "message": "refresh_token" }, (token: string) => {
console.log('refreshed token: ' + token)
if (token == undefined) {
chrome.runtime.sendMessage({ "message": "get_token" });
}
});
}
}
I use onBeforeRequest
chrome.webRequest.onBeforeRequest.addListener(
interceptURL,
{ urls: [liveApiUrl, testApiUrl] }
)
In my case, I need to pass a refresh token everytime I intercept that url
still have a couple of things to work on, but hopefully it gives you some direction.

declarativeNetRequest Regex rules for redirecting YT shorts work when the url is typed out or opened in a new tab but not when clicked from YT itself

I'm making a Chrome extension from redirecting youtube.com/shorts/... to youtube.com/watch?v=...
Everything works fine when I open those shorts links in new tabs or when I type them out but when I click from the homepage itself, they don't get redirected.
Here is my rules.json file:
[
{
"id": 1,
"priority": 1,
"action": { "type": "redirect", "redirect": { "regexSubstitution":"https://youtube.com/watch?v=\\1" } },
"condition": { "regexFilter": "^.*youtube\\.com/shorts/(.*)", "resourceTypes": ["main_frame"] }
}
]
Here is my manifest.json file:
{
"manifest_version": 3,
"name": "No Shorts",
"version": "0.5",
"description": "Play YT shorts as regular videos instead of in a separate player",
"action": {
"default_icon": "images/no-shorts-ico.png"
},
"declarative_net_request": {
"rule_resources": [{
"id": "ruleset_1",
"enabled": true,
"path": "rules.json"
}]
},
"icons":{
"16": "images/16.png",
"48": "images/48.png",
"128": "images/128.png"
},
"permissions":[ "declarativeNetRequest"],
"host_permissions":["*://*.youtube.com/*"]
}
I clicked on a short video from the homepage and it did not get redirected. However, when I refreshed it, it did get redirected. It also got redirected when I clicked open in new tab or typed out the url myself.
If I had to guess, I think it is happening because of something that is similar to client-side navigation but I really can't say for sure. Is there a fix for this?
There is no network request to intercept in such inner navigation as it uses the history API in JS.
You can run a script on the entire youtube domain and intercept the click event:
// page.js:
addEventListener('click', e => {
const thumb = e.target.closest('ytd-thumbnail');
const cmd = thumb?.__data.data.navigationEndpoint.commandMetadata.webCommandMetadata;
if (cmd?.webPageType !== 'WEB_PAGE_TYPE_SHORTS') return;
cmd.webPageType = 'WEB_PAGE_TYPE_WATCH';
cmd.url = cmd.url.replace('/shorts/', '/watch?v=');
for (const a of thumb.querySelectorAll('a'))
a.href = a.href.replace('/shorts/', '/watch?v=');
}, true);
// manifest.json:
"background": { "service_worker": "bg.js" },
"permissions": ["scripting"],
"host_permissions": ["*://www.youtube.com/"],
// bg.js
chrome.runtime.onInstalled.addListener(async () => {
const scripts = [{
id: 'page',
world: 'MAIN',
matches: ['*://www.youtube.com/*'],
runAt: 'document_start',
js: ['page.js'],
}];
await chrome.scripting.unregisterContentScripts({ids: scripts.map(s => s.id)})
.catch(() => {});
await chrome.scripting.registerContentScripts(scripts);
for (const script of scripts) {
const execCfg = {
target: {},
files: script.js,
injectImmediately: true,
world: script.world,
};
for (const tab of await chrome.tabs.query({url: script.matches})) {
execCfg.target.tabId = tab.id;
chrome.scripting.executeScript(execCfg);
}
}
});

Microsoft Teams task module with URL not working for external url

trigger a task module that will display a web page. All I was able to get is an empty Task Module with the title, while the specified height and width do not showing URL displayed.
i want to redirect the url from the api.,but api is giving a url but not redirecting
let requestUrl = await getRedirectUrlForSubmitAction(tokenResponse) ===> api call to get the url
const response: MessagingExtensionActionResponse = <MessagingExtensionActionResponse>{
task: {
type: "continue",
value: {
title: "Send recognition",
url: `${request.data.value}`, //url from api call
height: "large"
}
}
};
return Promise.resolve(response);
please check this below code for external url redirecting
<html>
<head>
<title>Redirecting</title>
<script src='https://statics.teams.cdn.office.net/sdk/v1.6.0/js/MicrosoftTeams.min.js'></script>
</head>
<body>
<div id='app'>
<header style="display: flex; justify-content: center;align-items: center; font-size: 1rem;">
<h1>Redirecting <em>....</em></h1>
</header>
</div>
<script type="text/javascript">
function login() {
microsoftTeams.initialize();
if (window.location.href.includes("redirectUrl.action")) {
let token = localStorage.getItem("appToken");
let urlStr = window.location.href.split('?url=')[1]
fetch(`${urlStr}`, {
method: 'GET',
headers: new Headers({
"content-type": "application/json",
"originated": "teams",
"post-type": "ajax",
"outlookauth": `${token}`
}),
})
.then(res => res.json())
.then(
(result) => {
console.log("result", result);
location.href = result.url
//return result.url
},
(error) => {
console.log("Error", error);
}
)
} else {
//balance
const host = window.location.href.split('&host=')[1].split('&')[0]
const appcode = window.location.href.split('&appCode=')[1]
const token = localStorage.getItem("appToken");
const urlType = window.location.href.split('?url=')[1]
const urlStr = `https://${host}/${appcode}/mobileapp/teams/teamsShopRedirectUrl.action?${urlType}`
fetch(`${urlStr}`, {
method: 'GET',
headers: new Headers({
"content-type": "application/json",
"originated": "teams",
"post-type": "ajax",
"outlookauth": `${token}`
}),
})
.then(res => res.json())
.then(
(result) => {
window.location.href = result.url
},
(error) => {
console.log("Error", error);
}
)
}
}
window.onload = login();
</script>
</body>
</html>
manifest file
{
"$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.8/MicrosoftTeams.schema.json",
"manifestVersion": "1.8",
"id": "{{APPLICATION_ID}}",
"version": "{{VERSION}}",
"packageName": "{{PACKAGE_NAME}}",
"developer": {
"name": "name",
"websiteUrl": "https://{{HOSTNAME}}/now",
"privacyUrl": "https://{{HOSTNAME}}/now/privacy.html",
"termsOfUseUrl": "https://{{HOSTNAME}}/now/tou.html"
},
"name": {
"short": "Now",
"full": "Now"
},
"description": {
"short": "for Teams",
"full": "."
},
"icons": {
"outline": "icon-outline.png",
"color": "icon-color.png"
},
"accentColor": "#FFFFFF",
"configurableTabs": [],
"staticTabs": [],
"bots": [
{
"botId": "{{MICROSOFT_APP_ID}}",
"needsChannelSelector": true,
"isNotificationOnly": false,
"scopes": [
"team",
"personal",
"groupchat"
],
"commandLists": [
{
"scopes": [
"team",
"personal"
],
"commands": [
{
"title": "test1",
"description": "test1"
},
{
"title": "test2",
"description": "test2 "
}
]
}
],
"supportsFiles": true,
"supportsCalling": true,
"supportsVideo": true
}
],
"connectors": [],
"composeExtensions": [
{
"botId": "{{MICROSOFT_APP_ID}}",
"canUpdateConfiguration": true,
"messageHandlers": [
{
"type": "link",
"value": {
"domains": [
"{{HOSTNAME}}",
"avidanpprd.performnet.com",
"youtube.com"
]
}
}
],
"commands": [
{
"id": "MessageExtension",
"title": "title",
"description": "Add a clever description here",
"initialRun": true,
"type": "action",
"context": [
"compose"
],
"fetchTask": true
}
]
}
],
"permissions": [
"identity",
"messageTeamMembers"
],
"validDomains": [
"{{HOSTNAME}}",
"avidanpprd.performnet.com",
"youtube.com"
],
"showLoadingIndicator": true,
"isFullScreen": false
}
This is probably a combination of things:
You need to make sure that the website you're showing is listed as a 'safe' domain in your manifest for your Teams app. I think you need something in both the messageHandlers > value > domain section as well as the validDomains section in the root level of the manifest.
However, depending on what you're trying to embed, it might not work because the external site has to have some basic Teams integration. See this heading, where it says:
For your page to display in Teams, you must include the Microsoft Teams JavaScript client SDK and include a call to microsoftTeams.initialize() after your page loads.
As a result, if this is an external site you don't control, you might need to have your own page that you host in the task module, which simpyly iframes in the external website.
This issue might come if the URL doesn't support iframe embedding.
To help you here you can refer the sample and try to bind the URL in iframe like below in your page.
<iframe width="700" height="700" src="https://www.example.com/embed/QPSaLnaU" allow="autoplay; encrypted-media"></iframe>
I have been recently working on something similar.
I have a message extension (build using Adaptive cards) and on one of the button clicks, I want to trigger Upload Document functionality. Unfortunately, an adaptive card doesn't provide.
So, I build an separate angular web-page, which will act as an upload application.
Note: The domain of the webpage should be added correctly under validDomains in the manifest file.
"validDomains": [
"*.example.com",
],
On button click in message extension (NodeJS):
...
return {
task: {
type: 'continue',
value: {
height: 400,
width: 400,
title: 'Task module WebView',
url: `https://show.example.com`
}
}
};
For more info visit:
Upload attachment from messages extension in MS Teams

declarativeNetRequest path to dynamically added rules in Chrome Extension

How can I specify in the manifest json file the dynamic rules?
Currently I have:
"declarative_net_request": {
"rule_resources": [{
"id": "ruleset_1",
"enabled": true,
"path": "rules.json"
}] }
And in my background.js file I have
const blockUrls = ['qwe.com', '123.com'];
blockUrls.forEach((domain, index) => {
let id = index + 1;
chrome.declarativeNetRequest.updateDynamicRules({
addRules: [
{
id: id,
priority: 1,
action: { type: 'block' },
condition: { urlFilter: domain, resourceTypes: ['main_frame'] },
},
],
removeRuleIds: [id],
});
});
What should I write in the path field?

Not able to query for nested relations using dgraph-orm

I am using dgraph-orm for fetching nested relational values but it works for single level but not multiple level.
I am getting the page details but unable to fetch the avatar of the page.
Here is my snippet:
let posts = await PagePost.has('page_id', {
filter: {
page_id: {
uid_in: [page_id]
}
},
include: {
page_id: {
as: 'page',
include: {
avatar: {
as: 'avatar'
}
}
},
owner_id: {
as: 'postedBy'
}
},
order: [], // accepts order like the above example
first: perPage, // accepts first
offset: offset, // accepts offset
});
I am not getting avatar for the attribute page_id:
{
"uid": "0x75b4",
"title": "",
"content": "haha",
"created_at": "2019-09-23T08:50:52.957Z",
"status": true,
"page": [
{
"uid": "0x75ac",
"name": "Saregamaapaaaa...",
"description": "This a is place where you can listen ti thrilling music.",
"created_at": "2019-09-23T06:46:50.756Z",
"status": true
}
],
"postedBy": [
{
"uid": "0x3",
"first_name": "Mohit",
"last_name": "Talwar",
"created_at": "2019-07-11T11:37:33.853Z",
"status": true
}
]
}
Is there a support for multilevel field querying in the orm??
There was some issue with ORM itself it was not able to recognize the correct model name for multilevel includes and generating the wrong queries.
Fixed the same in version 1.2.4, please run npm update dgraph-orm --save to update your DgraphORM.
Thanks for the issue.

Resources