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 { ...@@ -24,7 +24,6 @@ export class TokenManager {
anonymous_tokens_enabled: "use_anonymous_tokens", anonymous_tokens_enabled: "use_anonymous_tokens",
key: "key", key: "key",
key_charge: "anonymous_tokens_key_charge", key_charge: "anonymous_tokens_key_charge",
key_charge_check: "anonymous_tokens_key_charge_check",
tokens: "anonymous_tokens", tokens: "anonymous_tokens",
stored_tokens: "stored_tokens", stored_tokens: "stored_tokens",
tokens_recent_costs: "anonymous_tokens_recent_costs", tokens_recent_costs: "anonymous_tokens_recent_costs",
...@@ -38,7 +37,7 @@ export class TokenManager { ...@@ -38,7 +37,7 @@ export class TokenManager {
_anonymous_tokens_enabled = false; _anonymous_tokens_enabled = false;
_key = null; _key = null;
_key_charge = 0; _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_attach = false; // Attach tokens to result page
_tokens = []; // Stored anonymous Tokens _tokens = []; // Stored anonymous Tokens
_stored_tokens = []; // Stored Anonymous Tokens that are about to be consumed by the browser _stored_tokens = []; // Stored Anonymous Tokens that are about to be consumed by the browser
...@@ -96,7 +95,6 @@ export class TokenManager { ...@@ -96,7 +95,6 @@ export class TokenManager {
settings[this._storage_keys.stored_tokens] = []; settings[this._storage_keys.stored_tokens] = [];
settings[this._storage_keys.tokens_recent_costs] = [1]; settings[this._storage_keys.tokens_recent_costs] = [1];
settings[this._storage_keys.key_charge] = 0; settings[this._storage_keys.key_charge] = 0;
settings[this._storage_keys.key_charge_check] = 0;
return browser.storage.local.get(settings); return browser.storage.local.get(settings);
}) })
.then(async (storage) => { .then(async (storage) => {
...@@ -104,7 +102,6 @@ export class TokenManager { ...@@ -104,7 +102,6 @@ export class TokenManager {
this._stored_tokens = storage[this._storage_keys.stored_tokens]; this._stored_tokens = storage[this._storage_keys.stored_tokens];
this._recent_costs = storage[this._storage_keys.tokens_recent_costs]; this._recent_costs = storage[this._storage_keys.tokens_recent_costs];
this._key_charge = storage[this._storage_keys.key_charge]; this._key_charge = storage[this._storage_keys.key_charge];
this._key_charge_check = storage[this._storage_keys.key_charge_check];
return this.refill(); return this.refill();
}).then(() => this._updateNetRequestRules()); }).then(() => this._updateNetRequestRules());
return this._initialized; return this._initialized;
...@@ -140,9 +137,6 @@ export class TokenManager { ...@@ -140,9 +137,6 @@ export class TokenManager {
this._key_charge = changes[this._storage_keys.key_charge].newValue; this._key_charge = changes[this._storage_keys.key_charge].newValue;
rulesChange = true; 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) { if (rulesChange) {
return this._updateNetRequestRules(); return this._updateNetRequestRules();
} }
...@@ -150,6 +144,12 @@ export class TokenManager { ...@@ -150,6 +144,12 @@ export class TokenManager {
async handleRequestHeaders(details) { async handleRequestHeaders(details) {
await this.init(); 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) { async handleResponseHeaders(details) {
...@@ -182,7 +182,6 @@ export class TokenManager { ...@@ -182,7 +182,6 @@ export class TokenManager {
} }
this._stored_tokens = []; this._stored_tokens = [];
await this._store_tokens(); await this._store_tokens();
await this.remove_token_header();
} else if (parsed_cookie.key == "key") { } else if (parsed_cookie.key == "key") {
if (parsed_cookie.expired) { if (parsed_cookie.expired) {
await this.store_key(null); await this.store_key(null);
...@@ -212,6 +211,7 @@ export class TokenManager { ...@@ -212,6 +211,7 @@ export class TokenManager {
* Returns the current key charge * Returns the current key charge
*/ */
async getKeyCharge() { async getKeyCharge() {
await this.init();
return this._fetch_key_charge(); return this._fetch_key_charge();
} }
...@@ -250,14 +250,16 @@ export class TokenManager { ...@@ -250,14 +250,16 @@ export class TokenManager {
throw new Error("Couldn't fetch key status"); throw new Error("Couldn't fetch key status");
} }
}).then(async response => { }).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 }); }).catch(error => { console.error(error); return 0 });
} }
async _updateNetRequestRules() { async _updateNetRequestRules() {
if (!browser.hasOwnProperty("declarativeNetRequest")) return; if (!browser.hasOwnProperty("declarativeNetRequest")) return;
let rules = []; 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) { if (this._key) {
// Some paths require a key to be submitted (settings page; key management) // Some paths require a key to be submitted (settings page; key management)
rules.push({ rules.push({
...@@ -293,7 +295,6 @@ export class TokenManager { ...@@ -293,7 +295,6 @@ export class TokenManager {
} }
}); });
} }
// `tokenauthorization=${token_authorization}; tokensource=webextension`;
rules.push({ rules.push({
id: 4, id: 4,
...@@ -315,6 +316,23 @@ export class TokenManager { ...@@ -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) { } else if (this._key) {
rules.push({ rules.push({
id: 2, id: 2,
...@@ -342,11 +360,7 @@ export class TokenManager { ...@@ -342,11 +360,7 @@ export class TokenManager {
if (key) { if (key) {
let settings = {}; let settings = {};
settings[this._storage_keys.key] = key; settings[this._storage_keys.key] = key;
return browser.storage.sync.set(settings).then(async () => { return browser.storage.sync.set(settings).then(async () => this._fetch_key_charge());
settings = {};
settings[this._storage_keys.key_charge] = await this._fetch_key_charge();
return browser.storage.local.set(settings);
});
} else { } else {
return browser.storage.sync.remove(this._storage_keys.key).then(() => browser.storage.local.remove(this._storage_keys.key_charge)); 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 { ...@@ -356,17 +370,38 @@ export class TokenManager {
* Adds an entry to the array of recent * Adds an entry to the array of recent
* costs of the latest search requests * costs of the latest search requests
* *
* @param {int} cost * @param {string} payment_id
*/ */
async prepare_token_auth(cost) { async _token_auth(payment_id) {
if (isNaN(cost)) return; let baseURL = new URL(this._api_base);
this._recent_costs.unshift(cost); baseURL = new URL(baseURL.origin);
while (this._recent_costs.length > 50) { let cost = 0;
this._recent_costs.pop(); return fetch(`${baseURL}anonymous-token/cost?anonymous_token_payment_id=${payment_id}`).then(response => {
} if (response.ok) {
let new_setting = {}; return response.json();
new_setting[this._storage_keys.tokens_recent_costs] = this._recent_costs; } else {
return browser.storage.local.set(new_setting) 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(() => this.refill())
.then(async () => { .then(async () => {
let missing_tokens = Math.max(cost - this._stored_tokens.length, 0); let missing_tokens = Math.max(cost - this._stored_tokens.length, 0);
...@@ -376,9 +411,9 @@ export class TokenManager { ...@@ -376,9 +411,9 @@ export class TokenManager {
} }
return this._store_tokens().then(() => this.create_token_header()); return this._store_tokens().then(() => this.create_token_header());
} else { } else {
return this.remove_token_header().then(() => this._updateNetRequestRules()); return this._updateNetRequestRules();
} }
}); });*/
} }
/** /**
...@@ -428,38 +463,6 @@ export class TokenManager { ...@@ -428,38 +463,6 @@ export class TokenManager {
return token_authorization; 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 * Enable/Disable Tokenmanager when permissions
* are revoked or granted * are revoked or granted
...@@ -482,7 +485,6 @@ export class TokenManager { ...@@ -482,7 +485,6 @@ export class TokenManager {
let new_storage = {}; let new_storage = {};
if (key_charge != null) { if (key_charge != null) {
new_storage[this._storage_keys.key_charge] = key_charge; 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.tokens] = this._tokens;
new_storage[this._storage_keys.stored_tokens] = this._stored_tokens; new_storage[this._storage_keys.stored_tokens] = this._stored_tokens;
...@@ -493,25 +495,9 @@ export class TokenManager { ...@@ -493,25 +495,9 @@ export class TokenManager {
* Refills locally stored tokens * Refills locally stored tokens
*/ */
async refill() { 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 max_cost = 1;
let required_token_count = 0; let required_token_count = 0;
if (this._key_charge <= 0) return;
for (let [index, cost] of this._recent_costs.entries()) { for (let [index, cost] of this._recent_costs.entries()) {
if (cost > max_cost) max_cost = cost; if (cost > max_cost) max_cost = cost;
......
...@@ -19,16 +19,27 @@ browser.runtime.getManifest().host_permissions.forEach((value, index) => { ...@@ -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 * Execute things when a new browser profile is created
*/ */
browser.runtime.onStartup.addListener(async () => { browser.runtime.onStartup.addListener(async () => {
// Initialize our settings managers // Initialize our settings managers
let init_promises = [settingsManager.init(), tokenManager.init()]; 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; if (BROWSER != "CHROME") return;
/** Chrome currently does not apply NetRequestRules to startpages. But they will be applied after a reload */ /** 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 = []; let reloads = [];
tabs.forEach(tab => reloads.push(browser.tabs.reload(tab.id))); tabs.forEach(tab => reloads.push(browser.tabs.reload(tab.id)));
return Promise.all(reloads); return Promise.all(reloads);
...@@ -73,15 +84,6 @@ browser.runtime.onMessage.addListener((request, sender, sendResponse) => { ...@@ -73,15 +84,6 @@ browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
} }
return true; 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.type == "key") {
if (request.hasOwnProperty("action") && request.action == "getcharge") { if (request.hasOwnProperty("action") && request.action == "getcharge") {
tokenManager.getKeyCharge().then(charge => { tokenManager.getKeyCharge().then(charge => {
......
...@@ -40,7 +40,8 @@ ...@@ -40,7 +40,8 @@
"storage", "storage",
"cookies", "cookies",
"webRequest", "webRequest",
"declarativeNetRequestWithHostAccess" "declarativeNetRequestWithHostAccess",
"alarms"
], ],
"content_scripts": [ "content_scripts": [
{ {
......
...@@ -21,12 +21,7 @@ if (typeof browser == "undefined") { ...@@ -21,12 +21,7 @@ if (typeof browser == "undefined") {
hosts.push(url.host); hosts.push(url.host);
origins.push(url.origin); origins.push(url.origin);
}); });
let permissions = [ let permissions = browser.runtime.getManifest().permissions;
"storage",
"cookies",
"webRequest",
"declarativeNetRequestWithHostAccess"
];
await initializeSettingsState(); await initializeSettingsState();
......
...@@ -6,12 +6,7 @@ let urls = []; ...@@ -6,12 +6,7 @@ let urls = [];
let origins = []; let origins = [];
let hosts = []; let hosts = [];
let permissions = [ let permissions = browser.runtime.getManifest().permissions;
"storage",
"cookies",
"webRequest",
"declarativeNetRequestWithHostAccess"
];
if (typeof browser == "undefined") { if (typeof browser == "undefined") {
var browser = chrome; var browser = chrome;
......