Skip to content

Commit

Permalink
fix: session rules should be used instead of dynamic rules
Browse files Browse the repository at this point in the history
session rules are less persistent than dynamic rules, and the
intention of RequestBuilder is to only have rules active for the
lifetime of specific requests.
  • Loading branch information
praschke committed Oct 29, 2023
1 parent 0adf9ce commit ba8eec9
Showing 1 changed file with 46 additions and 4 deletions.
50 changes: 46 additions & 4 deletions ext/js/background/request-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class RequestBuilder {
async prepare() {
try {
await this._clearDynamicRules();
await this._clearSessionRules();
} catch (e) {
// NOP
}
Expand Down Expand Up @@ -260,6 +261,21 @@ class RequestBuilder {
}
}

async _clearSessionRules() {
if (!isObject(chrome.declarativeNetRequest)) { return; }

const rules = await this._getSessionRules();

if (rules.length === 0) { return; }

const removeRuleIds = [];
for (const {id} of rules) {
removeRuleIds.push(id);
}

await this._updateSessionRules({removeRuleIds});
}

async _clearDynamicRules() {
if (!isObject(chrome.declarativeNetRequest)) { return; }

Expand Down Expand Up @@ -311,17 +327,43 @@ class RequestBuilder {
}
}];

await this._updateDynamicRules({addRules});
await this._updateSessionRules({addRules});
try {
return await fetch(url, init);
} finally {
await this._tryUpdateDynamicRules({removeRuleIds: [id]});
await this._tryUpdateSessionRules({removeRuleIds: [id]});
}
} finally {
this._ruleIds.delete(id);
}
}

_getSessionRules() {
return new Promise((resolve, reject) => {
chrome.declarativeNetRequest.getSessionRules((result) => {
const e = chrome.runtime.lastError;
if (e) {
reject(new Error(e.message));
} else {
resolve(result);
}
});
});
}

_updateSessionRules(options) {
return new Promise((resolve, reject) => {
chrome.declarativeNetRequest.updateSessionRules(options, () => {
const e = chrome.runtime.lastError;
if (e) {
reject(new Error(e.message));
} else {
resolve();
}
});
});
}

_getDynamicRules() {
return new Promise((resolve, reject) => {
chrome.declarativeNetRequest.getDynamicRules((result) => {
Expand All @@ -348,9 +390,9 @@ class RequestBuilder {
});
}

async _tryUpdateDynamicRules(options) {
async _tryUpdateSessionRules(options) {
try {
await this._updateDynamicRules(options);
await this._updateSessionRules(options);
return true;
} catch (e) {
return false;
Expand Down

0 comments on commit ba8eec9

Please sign in to comment.