Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • weblate/metager-webextension
  • open-source/metager-webextension
2 results
Show changes
Commits on Source (5)
......@@ -24,7 +24,6 @@ export class TokenManager {
anonymous_tokens_enabled: "use_anonymous_tokens",
key: "key",
key_charge: "anonymous_tokens_key_charge",
key_charge_check: "anonymous_tokens_key_charge_check",
tokens: "anonymous_tokens",
stored_tokens: "stored_tokens",
tokens_recent_costs: "anonymous_tokens_recent_costs",
......@@ -38,7 +37,7 @@ export class TokenManager {
_anonymous_tokens_enabled = false;
_key = null;
_key_charge = 0;
_key_charge_check = 0; // When the key charge was last checked
_payment_id = null;
_tokens_attach = false; // Attach tokens to result page
_tokens = []; // Stored anonymous Tokens
_stored_tokens = []; // Stored Anonymous Tokens that are about to be consumed by the browser
......@@ -96,7 +95,6 @@ export class TokenManager {
settings[this._storage_keys.stored_tokens] = [];
settings[this._storage_keys.tokens_recent_costs] = [1];
settings[this._storage_keys.key_charge] = 0;
settings[this._storage_keys.key_charge_check] = 0;
return browser.storage.local.get(settings);
})
.then(async (storage) => {
......@@ -104,7 +102,6 @@ export class TokenManager {
this._stored_tokens = storage[this._storage_keys.stored_tokens];
this._recent_costs = storage[this._storage_keys.tokens_recent_costs];
this._key_charge = storage[this._storage_keys.key_charge];
this._key_charge_check = storage[this._storage_keys.key_charge_check];
return this.refill();
}).then(() => this._updateNetRequestRules());
return this._initialized;
......@@ -140,9 +137,6 @@ export class TokenManager {
this._key_charge = changes[this._storage_keys.key_charge].newValue;
rulesChange = true;
}
if (changes.hasOwnProperty(this._storage_keys.key_charge_check)) {
this._key_charge_check = changes[this._storage_keys.key_charge_check].newValue;
}
if (rulesChange) {
return this._updateNetRequestRules();
}
......@@ -150,6 +144,12 @@ export class TokenManager {
async handleRequestHeaders(details) {
await this.init();
if (details.url.match(/\/meta\/meta.ger3\?/) && this._payment_id != null) {
let payment_id = this._payment_id;
this._payment_id = null;
return this._updateNetRequestRules().then(() => this._token_auth(payment_id));
}
}
async handleResponseHeaders(details) {
......@@ -182,7 +182,6 @@ export class TokenManager {
}
this._stored_tokens = [];
await this._store_tokens();
await this.remove_token_header();
} else if (parsed_cookie.key == "key") {
if (parsed_cookie.expired) {
await this.store_key(null);
......@@ -212,6 +211,7 @@ export class TokenManager {
* Returns the current key charge
*/
async getKeyCharge() {
await this.init();
return this._fetch_key_charge();
}
......@@ -250,14 +250,16 @@ export class TokenManager {
throw new Error("Couldn't fetch key status");
}
}).then(async response => {
return response.charge;
let settings = {};
settings[this._storage_keys.key_charge] = response.charge;
return browser.storage.local.set(settings).then(() => response.charge);
}).catch(error => { console.error(error); return 0 });
}
async _updateNetRequestRules() {
if (!browser.hasOwnProperty("declarativeNetRequest")) return;
let rules = [];
if ((this._key && this._anonymous_tokens_enabled) || Math.min(...this._recent_costs) <= (this._tokens.length + this._stored_tokens.length)) {
if ((this._key && this._anonymous_tokens_enabled && this._key_charge > 0) || Math.min(...this._recent_costs) <= (this._tokens.length + this._stored_tokens.length)) {
if (this._key) {
// Some paths require a key to be submitted (settings page; key management)
rules.push({
......@@ -293,7 +295,6 @@ export class TokenManager {
}
});
}
// `tokenauthorization=${token_authorization}; tokensource=webextension`;
rules.push({
id: 4,
......@@ -315,6 +316,23 @@ export class TokenManager {
}]
}
});
this._payment_id = crypto.randomUUID();
rules.push({
id: 5,
condition: {
requestDomains: this._hosts,
urlFilter: "/meta/meta.ger3?*",
resourceTypes: ["main_frame", "sub_frame", "xmlhttprequest"]
},
action: {
type: "modifyHeaders",
requestHeaders: [{
header: "anonymous-token-payment-id",
operation: "set",
value: this._payment_id
}]
}
});
} else if (this._key) {
rules.push({
id: 2,
......@@ -342,11 +360,7 @@ export class TokenManager {
if (key) {
let settings = {};
settings[this._storage_keys.key] = key;
return browser.storage.sync.set(settings).then(async () => {
settings = {};
settings[this._storage_keys.key_charge] = await this._fetch_key_charge();
return browser.storage.local.set(settings);
});
return browser.storage.sync.set(settings).then(async () => this._fetch_key_charge());
} else {
return browser.storage.sync.remove(this._storage_keys.key).then(() => browser.storage.local.remove(this._storage_keys.key_charge));
}
......@@ -356,17 +370,38 @@ export class TokenManager {
* Adds an entry to the array of recent
* costs of the latest search requests
*
* @param {int} cost
* @param {string} payment_id
*/
async prepare_token_auth(cost) {
if (isNaN(cost)) return;
this._recent_costs.unshift(cost);
while (this._recent_costs.length > 50) {
this._recent_costs.pop();
}
let new_setting = {};
new_setting[this._storage_keys.tokens_recent_costs] = this._recent_costs;
return browser.storage.local.set(new_setting)
async _token_auth(payment_id) {
let baseURL = new URL(this._api_base);
baseURL = new URL(baseURL.origin);
let cost = 0;
return fetch(`${baseURL}anonymous-token/cost?anonymous_token_payment_id=${payment_id}`).then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Did not receive a valid response");
}
}).then(response => {
cost = response.cost;
this._recent_costs.unshift(cost);
while (this._recent_costs.length > 50) {
this._recent_costs.pop();
}
let new_setting = {};
new_setting[this._storage_keys.tokens_recent_costs] = this._recent_costs;
return browser.storage.local.set(new_setting)
debugger;
}).then(() => this.refill())
.then(() => {
// ToDo complete payment process
});
debugger;
/*
.then(() => this.refill())
.then(async () => {
let missing_tokens = Math.max(cost - this._stored_tokens.length, 0);
......@@ -376,9 +411,9 @@ export class TokenManager {
}
return this._store_tokens().then(() => this.create_token_header());
} else {
return this.remove_token_header().then(() => this._updateNetRequestRules());
return this._updateNetRequestRules();
}
});
});*/
}
/**
......@@ -428,38 +463,6 @@ export class TokenManager {
return token_authorization;
}
async remove_token_header() {
return browser.declarativeNetRequest.updateDynamicRules({
addRules: [],
removeRuleIds: [6]
});
}
async create_token_header() {
return browser.declarativeNetRequest.updateDynamicRules({
addRules: [{
id: 6,
condition: {
requestDomains: [
"metager.de",
"metager.org"
],
urlFilter: "/meta/meta.ger3?*",
resourceTypes: ["main_frame", "sub_frame", "xmlhttprequest"]
},
action: {
type: "modifyHeaders",
requestHeaders: [{
header: "tokens",
operation: "set",
value: JSON.stringify(this._stored_tokens)
}]
}
}],
removeRuleIds: [6]
});
}
/**
* Enable/Disable Tokenmanager when permissions
* are revoked or granted
......@@ -482,7 +485,6 @@ export class TokenManager {
let new_storage = {};
if (key_charge != null) {
new_storage[this._storage_keys.key_charge] = key_charge;
new_storage[this._storage_keys.key_charge_check] = (new Date()).getTime();
}
new_storage[this._storage_keys.tokens] = this._tokens;
new_storage[this._storage_keys.stored_tokens] = this._stored_tokens;
......@@ -493,25 +495,9 @@ export class TokenManager {
* Refills locally stored tokens
*/
async refill() {
if (this._key_charge == 0) {
// If the key is empty there is no need to try to generate signed tokens on each request
// Instead we will regulary check if the key was charged
if ((this._key_charge_check + 1 * 60 * 1000) < (new Date()).getTime()) {
// Check key charge
return this._fetch_key_charge().then(async charge => {
let settings = {};
settings[this._storage_keys.key_charge] = charge;
settings[this._storage_keys.key_charge_check] = (new Date()).getTime();
return browser.storage.local.set(settings);
});
} else {
return;
}
}
let max_cost = 1;
let required_token_count = 0;
if (this._key_charge <= 0) return;
for (let [index, cost] of this._recent_costs.entries()) {
if (cost > max_cost) max_cost = cost;
......
......@@ -19,16 +19,27 @@ browser.runtime.getManifest().host_permissions.forEach((value, index) => {
});
/**
* Create alarm for updating token status every 15 minutes
*/
browser.alarms.create("token_status_updater", { periodInMinutes: 15 });
browser.alarms.onAlarm.addListener(async alarm => {
if (alarm.name == "token_status_updater") {
return tokenManager.getKeyCharge().then(() => tokenManager.refill());
}
})
/**
* Execute things when a new browser profile is created
*/
browser.runtime.onStartup.addListener(async () => {
// Initialize our settings managers
let init_promises = [settingsManager.init(), tokenManager.init()];
return Promise.all(init_promises).then(() => {
return Promise.all(init_promises).then(async () => {
await tokenManager.getKeyCharge().then(() => tokenManager.refill()); // Update Key Charge on startup
if (BROWSER != "CHROME") return;
/** Chrome currently does not apply NetRequestRules to startpages. But they will be applied after a reload */
browser.tabs.query({}).then(tabs => {
return browser.tabs.query({}).then(tabs => {
let reloads = [];
tabs.forEach(tab => reloads.push(browser.tabs.reload(tab.id)));
return Promise.all(reloads);
......@@ -73,15 +84,6 @@ browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
}
return true;
}
if (request.type == "tokenauthorization") {
tokenManager.prepare_token_auth(request.cost).then(() => {
sendResponse({ status: "ok" });
}).catch(error => {
console.trace(error);
sendResponse({ status: "error" });
});
return true;
}
if (request.type == "key") {
if (request.hasOwnProperty("action") && request.action == "getcharge") {
tokenManager.getKeyCharge().then(charge => {
......
......@@ -40,7 +40,8 @@
"storage",
"cookies",
"webRequest",
"declarativeNetRequestWithHostAccess"
"declarativeNetRequestWithHostAccess",
"alarms"
],
"content_scripts": [
{
......
......@@ -21,12 +21,7 @@ if (typeof browser == "undefined") {
hosts.push(url.host);
origins.push(url.origin);
});
let permissions = [
"storage",
"cookies",
"webRequest",
"declarativeNetRequestWithHostAccess"
];
let permissions = browser.runtime.getManifest().permissions;
await initializeSettingsState();
......
......@@ -6,12 +6,7 @@ let urls = [];
let origins = [];
let hosts = [];
let permissions = [
"storage",
"cookies",
"webRequest",
"declarativeNetRequestWithHostAccess"
];
let permissions = browser.runtime.getManifest().permissions;
if (typeof browser == "undefined") {
var browser = chrome;
......