wallet-core/src/webex/wxBackend.ts

926 lines
28 KiB
TypeScript
Raw Normal View History

2016-01-05 14:20:13 +01:00
/*
This file is part of TALER
(C) 2016 GNUnet e.V.
TALER is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
TALER is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
2016-07-07 17:59:29 +02:00
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
2016-01-05 14:20:13 +01:00
*/
/**
* Messaging for the WebExtensions wallet. Should contain
* parts that are specific for WebExtensions, but as little business
* logic as possible.
*/
2016-01-05 14:20:13 +01:00
/**
* Imports.
*/
import { BrowserHttpLib } from "../http";
import * as logging from "../logging";
2017-05-28 01:10:54 +02:00
import {
Index,
Store,
} from "../query";
import { AmountJson } from "../amounts";
2017-05-28 01:10:54 +02:00
import {
2017-11-30 04:07:36 +01:00
AcceptTipRequest,
ConfirmReserveRequest,
CreateReserveRequest,
2017-11-30 04:07:36 +01:00
GetTipPlanchetsRequest,
2017-05-28 01:10:54 +02:00
Notifier,
2017-11-30 04:07:36 +01:00
ProcessTipResponseRequest,
QueryPaymentFound,
ReturnCoinsRequest,
2017-11-30 04:07:36 +01:00
TipStatusRequest,
} from "../walletTypes";
2016-09-06 14:39:45 +02:00
import {
Wallet,
} from "../wallet";
import {
Stores,
WALLET_DB_VERSION,
} from "../dbTypes";
2017-11-30 04:07:36 +01:00
import { ChromeBadge } from "./chromeBadge";
import { MessageType } from "./messages";
2017-06-05 03:20:28 +02:00
import * as wxApi from "./wxApi";
2017-05-30 18:33:28 +02:00
import URI = require("urijs");
import Port = chrome.runtime.Port;
2017-05-28 01:10:54 +02:00
import MessageSender = chrome.runtime.MessageSender;
import { TipToken } from "../talerTypes";
2016-02-09 21:56:06 +01:00
2016-01-11 02:48:19 +01:00
2016-11-15 15:07:17 +01:00
const DB_NAME = "taler";
2017-06-05 03:20:28 +02:00
const NeedsWallet = Symbol("NeedsWallet");
function handleMessage(sender: MessageSender,
type: MessageType, detail: any): any {
function assertNotFound(t: never): never {
console.error(`Request type ${t as string} unknown`);
console.error(`Request detail was ${detail}`);
return { error: "request unknown", requestType: type } as never;
}
2017-06-05 03:20:28 +02:00
function needsWallet(): Wallet {
if (!currentWallet) {
throw NeedsWallet;
}
return currentWallet;
}
switch (type) {
2017-06-05 03:20:28 +02:00
case "balances": {
return needsWallet().getBalances();
}
case "dump-db": {
const db = needsWallet().db;
return exportDb(db);
2017-06-05 03:20:28 +02:00
}
case "import-db": {
const db = needsWallet().db;
2017-04-13 15:05:38 +02:00
return importDb(db, detail.dump);
2017-06-05 03:20:28 +02:00
}
case "ping": {
2016-10-11 20:26:37 +02:00
return Promise.resolve();
2017-06-05 03:20:28 +02:00
}
case "reset-db": {
if (currentWallet) {
const db = currentWallet.db;
2017-05-28 01:10:54 +02:00
const tx = db.transaction(Array.from(db.objectStoreNames), "readwrite");
// tslint:disable-next-line:prefer-for-of
2016-03-02 00:47:00 +01:00
for (let i = 0; i < db.objectStoreNames.length; i++) {
tx.objectStore(db.objectStoreNames[i]).clear();
}
}
deleteDb();
2016-10-12 02:55:53 +02:00
chrome.browserAction.setBadgeText({ text: "" });
console.log("reset done");
2017-06-05 03:20:28 +02:00
if (!currentWallet) {
reinitWallet();
}
return Promise.resolve({});
2017-06-05 03:20:28 +02:00
}
case "create-reserve": {
2016-02-09 21:56:06 +01:00
const d = {
amount: detail.amount,
2017-05-28 01:10:54 +02:00
exchange: detail.exchange,
senderWire: detail.senderWire,
2016-02-09 21:56:06 +01:00
};
const req = CreateReserveRequest.checked(d);
2017-06-05 03:20:28 +02:00
return needsWallet().createReserve(req);
}
2017-06-05 03:20:28 +02:00
case "confirm-reserve": {
2016-02-09 21:56:06 +01:00
const d = {
2017-05-28 00:38:50 +02:00
reservePub: detail.reservePub,
};
2016-02-09 21:56:06 +01:00
const req = ConfirmReserveRequest.checked(d);
2017-06-05 03:20:28 +02:00
return needsWallet().confirmReserve(req);
}
case "confirm-pay": {
if (typeof detail.proposalId !== "number") {
throw Error("proposalId must be number");
}
return needsWallet().confirmPay(detail.proposalId, detail.sessionId);
2017-06-05 03:20:28 +02:00
}
case "check-pay": {
if (typeof detail.proposalId !== "number") {
throw Error("proposalId must be number");
2016-04-27 06:03:04 +02:00
}
2017-06-05 03:20:28 +02:00
return needsWallet().checkPay(detail.proposalId);
}
case "query-payment": {
2016-09-28 19:37:05 +02:00
if (sender.tab && sender.tab.id) {
rateLimitCache[sender.tab.id]++;
if (rateLimitCache[sender.tab.id] > 10) {
2017-02-13 00:44:44 +01:00
console.warn("rate limit for query-payment exceeded");
2017-05-28 01:10:54 +02:00
const msg = {
2017-02-13 00:44:44 +01:00
error: "rate limit exceeded for query-payment",
2016-09-28 19:37:05 +02:00
hint: "Check for redirect loops",
2017-05-28 01:10:54 +02:00
rateLimitExceeded: true,
2016-09-28 19:37:05 +02:00
};
return Promise.resolve(msg);
}
}
return needsWallet().queryPaymentByFulfillmentUrl(detail.url);
2017-06-05 03:20:28 +02:00
}
case "exchange-info": {
2016-02-18 22:50:17 +01:00
if (!detail.baseUrl) {
2016-10-12 02:55:53 +02:00
return Promise.resolve({ error: "bad url" });
2016-02-18 22:50:17 +01:00
}
2017-06-05 03:20:28 +02:00
return needsWallet().updateExchangeFromUrl(detail.baseUrl);
}
case "currency-info": {
if (!detail.name) {
return Promise.resolve({ error: "name missing" });
}
2017-06-05 03:20:28 +02:00
return needsWallet().getCurrencyRecord(detail.name);
}
case "hash-contract": {
2016-09-28 23:41:34 +02:00
if (!detail.contract) {
2016-10-12 02:55:53 +02:00
return Promise.resolve({ error: "contract missing" });
2016-09-28 23:41:34 +02:00
}
2017-06-05 03:20:28 +02:00
return needsWallet().hashContract(detail.contract).then((hash) => {
return hash;
2016-09-28 23:41:34 +02:00
});
2017-06-05 03:20:28 +02:00
}
case "reserve-creation-info": {
2016-02-18 22:50:17 +01:00
if (!detail.baseUrl || typeof detail.baseUrl !== "string") {
2016-10-12 02:55:53 +02:00
return Promise.resolve({ error: "bad url" });
2016-02-18 22:50:17 +01:00
}
2017-05-28 01:10:54 +02:00
const amount = AmountJson.checked(detail.amount);
2017-06-05 03:20:28 +02:00
return needsWallet().getReserveCreationInfo(detail.baseUrl, amount);
}
case "get-history": {
// TODO: limit history length
2017-06-05 03:20:28 +02:00
return needsWallet().getHistory();
}
case "get-proposal": {
return needsWallet().getProposal(detail.proposalId);
}
case "get-exchanges": {
return needsWallet().getExchanges();
}
case "get-currencies": {
return needsWallet().getCurrencies();
}
case "update-currency": {
return needsWallet().updateCurrency(detail.currencyRecord);
}
case "get-reserves": {
2016-10-12 02:55:53 +02:00
if (typeof detail.exchangeBaseUrl !== "string") {
return Promise.reject(Error("exchangeBaseUrl missing"));
}
2017-06-05 03:20:28 +02:00
return needsWallet().getReserves(detail.exchangeBaseUrl);
}
case "get-payback-reserves": {
return needsWallet().getPaybackReserves();
}
case "withdraw-payback-reserve": {
if (typeof detail.reservePub !== "string") {
return Promise.reject(Error("reservePub missing"));
}
2017-06-05 03:20:28 +02:00
return needsWallet().withdrawPaybackReserve(detail.reservePub);
}
case "get-coins": {
2016-10-12 02:55:53 +02:00
if (typeof detail.exchangeBaseUrl !== "string") {
return Promise.reject(Error("exchangBaseUrl missing"));
}
2017-06-05 03:20:28 +02:00
return needsWallet().getCoins(detail.exchangeBaseUrl);
}
case "get-precoins": {
2016-10-12 02:55:53 +02:00
if (typeof detail.exchangeBaseUrl !== "string") {
return Promise.reject(Error("exchangBaseUrl missing"));
}
2017-10-15 19:28:35 +02:00
return needsWallet().getPreCoins(detail.exchangeBaseUrl);
2017-06-05 03:20:28 +02:00
}
case "get-denoms": {
if (typeof detail.exchangeBaseUrl !== "string") {
return Promise.reject(Error("exchangBaseUrl missing"));
}
2017-06-05 03:20:28 +02:00
return needsWallet().getDenoms(detail.exchangeBaseUrl);
}
case "refresh-coin": {
2016-10-13 02:36:33 +02:00
if (typeof detail.coinPub !== "string") {
return Promise.reject(Error("coinPub missing"));
}
2017-06-05 03:20:28 +02:00
return needsWallet().refresh(detail.coinPub);
}
case "payback-coin": {
if (typeof detail.coinPub !== "string") {
return Promise.reject(Error("coinPub missing"));
}
2017-06-05 03:20:28 +02:00
return needsWallet().payback(detail.coinPub);
}
case "get-sender-wire-infos": {
return needsWallet().getSenderWireInfos();
}
case "return-coins": {
const d = {
amount: detail.amount,
exchange: detail.exchange,
senderWire: detail.senderWire,
};
const req = ReturnCoinsRequest.checked(d);
return needsWallet().returnCoins(req);
}
2017-06-05 03:20:28 +02:00
case "check-upgrade": {
let dbResetRequired = false;
if (!currentWallet) {
dbResetRequired = true;
}
const resp: wxApi.UpgradeResponse = {
currentDbVersion: WALLET_DB_VERSION.toString(),
2017-10-15 19:28:35 +02:00
dbResetRequired,
2017-06-05 03:20:28 +02:00
oldDbVersion: (oldDbVersion || "unknown").toString(),
2017-10-15 19:28:35 +02:00
};
2017-06-05 03:20:28 +02:00
return resp;
}
case "log-and-display-error":
logging.storeReport(detail).then((reportUid) => {
2017-08-27 03:56:19 +02:00
const url = chrome.extension.getURL(`/src/webex/pages/error.html?reportUid=${reportUid}`);
if (detail.sameTab && sender && sender.tab && sender.tab.id) {
chrome.tabs.update(detail.tabId, { url });
} else {
chrome.tabs.create({ url });
}
});
return;
case "get-report":
return logging.getReport(detail.reportUid);
2017-10-15 19:28:35 +02:00
case "get-purchase": {
2017-08-27 03:56:19 +02:00
const contractTermsHash = detail.contractTermsHash;
if (!contractTermsHash) {
throw Error("contractTermsHash missing");
}
return needsWallet().getPurchase(contractTermsHash);
2017-10-15 19:28:35 +02:00
}
case "get-full-refund-fees":
return needsWallet().getFullRefundFees(detail.refundPermissions);
2017-11-30 04:07:36 +01:00
case "get-tip-status": {
const req = TipStatusRequest.checked(detail);
return needsWallet().getTipStatus(req.merchantDomain, req.tipId);
}
case "accept-tip": {
const req = AcceptTipRequest.checked(detail);
return needsWallet().acceptTip(req.merchantDomain, req.tipId);
}
case "process-tip-response": {
const req = ProcessTipResponseRequest.checked(detail);
return needsWallet().processTipResponse(req.merchantDomain, req.tipId, req.tipResponse);
}
case "get-tip-planchets": {
const req = GetTipPlanchetsRequest.checked(detail);
return needsWallet().getTipPlanchets(req.merchantDomain,
req.tipId,
req.amount,
req.deadline,
req.exchangeUrl,
req.nextUrl);
2017-11-30 04:07:36 +01:00
}
case "clear-notification": {
return needsWallet().clearNotification();
}
case "download-proposal": {
return needsWallet().downloadProposal(detail.url);
}
case "taler-pay": {
const senderUrl = sender.url;
if (!senderUrl) {
console.log("can't trigger payment, no sender URL");
return;
}
const tab = sender.tab;
if (!tab) {
console.log("can't trigger payment, no sender tab");
return;
}
const tabId = tab.id;
if (typeof tabId !== "string") {
console.log("can't trigger payment, no sender tab id");
return;
}
talerPay(detail, senderUrl, tabId);
return;
}
default:
// Exhaustiveness check.
// See https://www.typescriptlang.org/docs/handbook/advanced-types.html
return assertNotFound(type);
2016-11-20 08:58:04 +01:00
}
}
2017-06-05 03:20:28 +02:00
async function dispatch(req: any, sender: any, sendResponse: any): Promise<void> {
2016-11-20 08:58:04 +01:00
try {
2017-06-05 03:20:28 +02:00
const p = handleMessage(sender, req.type, req.detail);
2017-05-28 01:10:54 +02:00
const r = await p;
2016-11-20 08:58:04 +01:00
try {
sendResponse(r);
} catch (e) {
// might fail if tab disconnected
}
} catch (e) {
console.log(`exception during wallet handler for '${req.type}'`);
console.log("request", req);
console.error(e);
2017-05-28 01:10:54 +02:00
let stack;
try {
stack = e.stack.toString();
} catch (e) {
// might fail
}
2016-11-20 08:58:04 +01:00
try {
sendResponse({
error: "exception",
2017-08-27 06:47:13 +02:00
message: e.message,
2017-05-28 01:10:54 +02:00
stack,
2016-11-20 08:58:04 +01:00
});
} catch (e) {
console.log(e);
2016-11-20 08:58:04 +01:00
// might fail if tab disconnected
}
}
}
2016-02-18 23:41:29 +01:00
class ChromeNotifier implements Notifier {
private ports: Port[] = [];
2016-02-18 23:41:29 +01:00
constructor() {
chrome.runtime.onConnect.addListener((port) => {
console.log("got connect!");
this.ports.push(port);
port.onDisconnect.addListener(() => {
2017-05-28 01:10:54 +02:00
const i = this.ports.indexOf(port);
2016-02-18 23:41:29 +01:00
if (i >= 0) {
this.ports.splice(i, 1);
} else {
console.error("port already removed");
}
});
});
}
notify() {
2017-05-28 01:10:54 +02:00
for (const p of this.ports) {
2016-10-12 02:55:53 +02:00
p.postMessage({ notify: true });
2016-02-18 23:41:29 +01:00
}
}
}
2016-09-06 13:31:30 +02:00
async function talerPay(fields: any, url: string, tabId: number): Promise<string | undefined> {
if (!currentWallet) {
console.log("can't handle payment, no wallet");
return undefined;
}
const w = currentWallet;
const goToPayment = (p: QueryPaymentFound): string => {
const nextUrl = new URI(p.contractTerms.fulfillment_url);
nextUrl.addSearch("order_id", p.contractTerms.order_id);
if (p.lastSessionSig) {
nextUrl.addSearch("session_sig", p.lastSessionSig);
}
return url;
};
if (fields.resource_url) {
const p = await w.queryPaymentByFulfillmentUrl(fields.resource_url);
if (p.found) {
return goToPayment(p);
}
}
if (fields.contract_hash) {
const p = await w.queryPaymentByContractTermsHash(fields.contract_hash);
if (p.found) {
goToPayment(p);
return goToPayment(p);
}
}
if (fields.contract_url) {
const proposalId = await w.downloadProposal(fields.contract_url);
const uri = new URI(chrome.extension.getURL("/src/webex/pages/confirm-contract.html"));
if (fields.session_id) {
uri.addSearch("sessionId", fields.session_id);
}
uri.addSearch("proposalId", proposalId);
const redirectUrl = uri.href();
return redirectUrl;
}
if (fields.offer_url) {
return fields.offer_url;
}
if (fields.refund_url) {
console.log("processing refund");
const hc = await w.acceptRefund(fields.refund_url);
return chrome.extension.getURL(`/src/webex/pages/refund.html?contractTermsHash=${hc}`);
}
if (fields.tip) {
const tipToken = TipToken.checked(fields.tip);
w.processTip(tipToken);
// Go to tip dialog page, where the user can confirm the tip or
// decline if they are not happy with the exchange.
const merchantDomain = new URI(url).origin();
const uri = new URI(chrome.extension.getURL("/src/webex/pages/tip.html"));
const params = { tip_id: tipToken.tip_id, merchant_domain: merchantDomain };
const redirectUrl = uri.query(params).href();
return redirectUrl;
}
return undefined;
}
2016-09-08 17:26:31 +02:00
/**
* Handle a HTTP response that has the "402 Payment Required" status.
* In this callback we don't have access to the body, and must communicate via
* shared state with the content script that will later be run later
* in this tab.
*/
2017-02-13 00:44:44 +01:00
function handleHttpPayment(headerList: chrome.webRequest.HttpHeader[], url: string, tabId: number): any {
if (!currentWallet) {
console.log("can't handle payment, no wallet");
return;
}
2016-10-12 02:55:53 +02:00
const headers: { [s: string]: string } = {};
2017-05-28 01:10:54 +02:00
for (const kv of headerList) {
2016-09-12 17:41:12 +02:00
if (kv.value) {
headers[kv.name.toLowerCase()] = kv.value;
}
2016-09-06 13:31:30 +02:00
}
2017-05-28 01:10:54 +02:00
const fields = {
contract_hash: headers["x-taler-contract-hash"],
2017-05-28 01:10:54 +02:00
contract_url: headers["x-taler-contract-url"],
2017-02-13 00:44:44 +01:00
offer_url: headers["x-taler-offer-url"],
2017-08-27 03:56:19 +02:00
refund_url: headers["x-taler-refund-url"],
resource_url: headers["x-taler-resource-url"],
session_id: headers["x-taler-session-id"],
2017-11-30 04:07:36 +01:00
tip: headers["x-taler-tip"],
2017-05-28 01:10:54 +02:00
};
2016-09-06 13:31:30 +02:00
2017-05-28 01:10:54 +02:00
const talerHeaderFound = Object.keys(fields).filter((x: any) => (fields as any)[x]).length !== 0;
2016-09-06 13:31:30 +02:00
if (!talerHeaderFound) {
2017-02-13 00:44:44 +01:00
// looks like it's not a taler request, it might be
// for a different payment system (or the shop is buggy)
console.log("ignoring non-taler 402 response");
return;
2017-02-13 00:44:44 +01:00
}
console.log("got pay detail", fields);
2017-02-13 00:44:44 +01:00
// Fast path for existing payment
if (fields.resource_url) {
const nextUrl = currentWallet.getNextUrlFromResourceUrl(fields.resource_url);
if (nextUrl) {
return { redirectUrl: nextUrl };
}
}
// Fast path for new contract
if (!fields.contract_hash && fields.contract_url) {
const uri = new URI(chrome.extension.getURL("/src/webex/pages/confirm-contract.html"));
uri.addSearch("contractUrl", fields.contract_url);
if (fields.session_id) {
uri.addSearch("sessionId", fields.session_id);
}
return { redirectUrl: uri.href() };
}
2017-02-13 00:44:44 +01:00
// We need to do some asynchronous operation, we can't directly redirect
talerPay(fields, url, tabId).then((nextUrl) => {
if (nextUrl) {
chrome.tabs.update(tabId, { url: nextUrl });
}
});
return;
2016-09-06 13:31:30 +02:00
}
2016-11-17 21:21:05 +01:00
function handleBankRequest(wallet: Wallet, headerList: chrome.webRequest.HttpHeader[],
2017-05-28 01:10:54 +02:00
url: string, tabId: number): any {
2016-11-17 21:21:05 +01:00
const headers: { [s: string]: string } = {};
2017-05-28 01:10:54 +02:00
for (const kv of headerList) {
2016-11-17 21:21:05 +01:00
if (kv.value) {
headers[kv.name.toLowerCase()] = kv.value;
}
}
const operation = headers["x-taler-operation"];
if (!operation) {
// Not a taler related request.
return;
}
2017-10-15 19:28:35 +02:00
if (operation === "confirm-reserve") {
const reservePub = headers["x-taler-reserve-pub"];
if (reservePub !== undefined) {
console.log(`confirming reserve ${reservePub} via 201`);
wallet.confirmReserve({reservePub});
2017-12-12 17:37:06 +01:00
} else {
console.warn("got 'X-Taler-Operation: confirm-reserve' without 'X-Taler-Reserve-Pub'");
}
2016-11-17 21:21:05 +01:00
return;
}
2017-10-15 19:28:35 +02:00
if (operation === "create-reserve") {
const amount = headers["x-taler-amount"];
if (!amount) {
console.log("202 not understood (X-Taler-Amount missing)");
return;
}
2017-05-28 01:10:54 +02:00
const callbackUrl = headers["x-taler-callback-url"];
2016-11-17 21:21:05 +01:00
if (!callbackUrl) {
2016-11-18 17:15:12 +01:00
console.log("202 not understood (X-Taler-Callback-Url missing)");
2016-11-17 21:21:05 +01:00
return;
}
2016-11-19 17:37:39 +01:00
try {
JSON.parse(amount);
2016-11-19 17:37:39 +01:00
} catch (e) {
2017-10-15 19:28:35 +02:00
const errUri = new URI(chrome.extension.getURL("/src/webex/pages/error.html"));
2017-05-28 01:10:54 +02:00
const p = {
2016-11-19 17:37:39 +01:00
message: `Can't parse amount ("${amount}"): ${e.message}`,
};
2017-10-15 19:28:35 +02:00
const errRedirectUrl = errUri.query(p).href();
2017-04-24 17:50:13 +02:00
// FIXME: use direct redirect when https://bugzilla.mozilla.org/show_bug.cgi?id=707624 is fixed
2017-10-15 19:28:35 +02:00
chrome.tabs.update(tabId, {url: errRedirectUrl});
2017-04-24 17:50:13 +02:00
return;
2016-11-19 17:37:39 +01:00
}
2017-05-28 01:10:54 +02:00
const wtTypes = headers["x-taler-wt-types"];
2016-11-17 21:21:05 +01:00
if (!wtTypes) {
2016-11-18 17:15:12 +01:00
console.log("202 not understood (X-Taler-Wt-Types missing)");
2016-11-17 21:21:05 +01:00
return;
}
2017-05-28 01:10:54 +02:00
const params = {
amount,
2016-11-17 21:21:05 +01:00
bank_url: url,
2017-05-28 01:10:54 +02:00
callback_url: new URI(callbackUrl) .absoluteTo(url),
2017-10-15 19:28:35 +02:00
sender_wire: headers["x-taler-sender-wire"],
suggested_exchange_url: headers["x-taler-suggested-exchange"],
2017-05-28 01:10:54 +02:00
wt_types: wtTypes,
2016-11-17 21:21:05 +01:00
};
const uri = new URI(chrome.extension.getURL("/src/webex/pages/confirm-create-reserve.html"));
2017-05-28 01:10:54 +02:00
const redirectUrl = uri.query(params).href();
2017-04-24 17:50:13 +02:00
console.log("redirecting to", redirectUrl);
// FIXME: use direct redirect when https://bugzilla.mozilla.org/show_bug.cgi?id=707624 is fixed
chrome.tabs.update(tabId, { url: redirectUrl });
2017-04-24 17:50:13 +02:00
return;
2016-11-17 21:21:05 +01:00
}
console.log("Ignoring unknown X-Taler-Operation:", operation);
2016-11-17 21:21:05 +01:00
}
2016-09-28 19:37:05 +02:00
// Rate limit cache for executePayment operations, to break redirect loops
2016-10-12 02:55:53 +02:00
let rateLimitCache: { [n: number]: number } = {};
2016-09-28 19:37:05 +02:00
function clearRateLimitCache() {
rateLimitCache = {};
}
2017-06-05 02:00:03 +02:00
/**
* Currently active wallet instance. Might be unloaded and
* re-instantiated when the database is reset.
*/
let currentWallet: Wallet|undefined;
2017-06-05 03:20:28 +02:00
/**
* Last version if an outdated DB, if applicable.
*/
let oldDbVersion: number|undefined;
2017-06-05 02:00:03 +02:00
async function reinitWallet() {
if (currentWallet) {
currentWallet.stop();
currentWallet = undefined;
}
chrome.browserAction.setBadgeText({ text: "" });
const badge = new ChromeBadge();
let db: IDBDatabase;
try {
db = await openTalerDb();
} catch (e) {
console.error("could not open database", e);
return;
}
const http = new BrowserHttpLib();
const notifier = new ChromeNotifier();
console.log("setting wallet");
const wallet = new Wallet(db, http, badge, notifier);
// Useful for debugging in the background page.
(window as any).talerWallet = wallet;
currentWallet = wallet;
}
/**
* Inject a script into a tab. Gracefully logs errors
* and works around a bug where the tab's URL does not match the internal URL,
* making the injection fail in a confusing way.
*/
function injectScript(tabId: number, details: chrome.tabs.InjectDetails, actualUrl: string): void {
chrome.tabs.executeScript(tabId, details, () => {
// Required to squelch chrome's "unchecked lastError" warning.
// Sometimes chrome reports the URL of a tab as http/https but
// injection fails. This can happen when a page is unloaded or
// shows a "no internet" page etc.
if (chrome.runtime.lastError) {
console.warn("injection failed on page", actualUrl, chrome.runtime.lastError.message);
}
});
}
/**
* Main function to run for the WebExtension backend.
*
* Sets up all event handlers and other machinery.
*/
2016-11-20 08:58:04 +01:00
export async function wxMain() {
2017-05-31 22:55:03 +02:00
// Explicitly unload the extension page as soon as an update is available,
// so the update gets installed as soon as possible.
chrome.runtime.onUpdateAvailable.addListener((details) => {
console.log("update available:", details);
chrome.runtime.reload();
2017-10-15 19:28:35 +02:00
});
2017-05-31 22:55:03 +02:00
2016-11-18 04:09:04 +01:00
window.onerror = (m, source, lineno, colno, error) => {
2016-11-19 16:33:29 +01:00
logging.record("error", m + error, undefined, source || "(unknown)", lineno || 0, colno || 0);
2017-05-28 01:10:54 +02:00
};
2016-11-18 04:09:04 +01:00
2017-05-28 01:10:54 +02:00
chrome.tabs.query({}, (tabs) => {
2017-08-30 15:35:34 +02:00
console.log("got tabs", tabs);
2017-05-28 01:10:54 +02:00
for (const tab of tabs) {
2016-09-12 17:41:12 +02:00
if (!tab.url || !tab.id) {
2017-08-30 15:35:34 +02:00
continue;
2016-03-02 15:33:23 +01:00
}
2017-05-28 01:10:54 +02:00
const uri = new URI(tab.url);
if (uri.protocol() !== "http" && uri.protocol() !== "https") {
2017-08-30 15:35:34 +02:00
continue;
2016-03-02 15:33:23 +01:00
}
console.log("injecting into existing tab", tab.id, "with url", uri.href(), "protocol", uri.protocol());
2017-08-30 15:35:34 +02:00
injectScript(tab.id, { file: "/dist/contentScript-bundle.js", runAt: "document_start" }, uri.href());
const code = `
if (("taler" in window) || document.documentElement.getAttribute("data-taler-nojs")) {
document.dispatchEvent(new Event("taler-probe-result"));
}
`;
2017-08-30 15:35:34 +02:00
injectScript(tab.id, { code, runAt: "document_start" }, uri.href());
2016-03-02 15:33:23 +01:00
}
});
const tabTimers: {[n: number]: number[]} = {};
chrome.tabs.onRemoved.addListener((tabId, changeInfo) => {
2017-05-28 01:10:54 +02:00
const tt = tabTimers[tabId] || [];
for (const t of tt) {
chrome.extension.getBackgroundPage().clearTimeout(t);
}
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
2017-05-28 01:10:54 +02:00
if (changeInfo.status !== "complete") {
return;
}
const timers: number[] = [];
const addRun = (dt: number) => {
const id = chrome.extension.getBackgroundPage().setTimeout(run, dt);
timers.push(id);
2017-05-28 01:10:54 +02:00
};
const run = () => {
timers.shift();
chrome.tabs.get(tabId, (tab) => {
if (chrome.runtime.lastError) {
return;
}
if (!tab.url || !tab.id) {
return;
}
2017-05-28 01:10:54 +02:00
const uri = new URI(tab.url);
2017-05-28 00:38:50 +02:00
if (!(uri.protocol() === "http" || uri.protocol() === "https")) {
return;
}
2017-05-28 01:10:54 +02:00
const code = `
if (("taler" in window) || document.documentElement.getAttribute("data-taler-nojs")) {
document.dispatchEvent(new Event("taler-probe-result"));
}
`;
injectScript(tab.id!, { code, runAt: "document_start" }, uri.href());
});
};
addRun(0);
addRun(50);
addRun(300);
addRun(1000);
addRun(2000);
addRun(4000);
addRun(8000);
addRun(16000);
tabTimers[tabId] = timers;
});
2016-09-28 19:37:05 +02:00
chrome.extension.getBackgroundPage().setInterval(clearRateLimitCache, 5000);
2017-06-05 02:00:03 +02:00
reinitWallet();
2016-11-20 08:58:04 +01:00
// Handlers for messages coming directly from the content
// script on the page
chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
2017-06-05 03:20:28 +02:00
dispatch(req, sender, sendResponse);
2016-11-20 08:58:04 +01:00
return true;
});
2016-10-12 02:55:53 +02:00
2017-06-05 02:00:03 +02:00
// Clear notifications both when the popop opens,
// as well when it closes.
chrome.runtime.onConnect.addListener((port) => {
if (port.name === "popup") {
if (currentWallet) {
currentWallet.clearNotification();
}
port.onDisconnect.addListener(() => {
if (currentWallet) {
currentWallet.clearNotification();
}
});
}
});
2016-11-20 08:58:04 +01:00
// Handlers for catching HTTP requests
chrome.webRequest.onHeadersReceived.addListener((details) => {
2017-06-05 02:00:03 +02:00
const wallet = currentWallet;
if (!wallet) {
console.warn("wallet not available while handling header");
}
2017-05-28 00:38:50 +02:00
if (details.statusCode === 402) {
2016-11-20 08:58:04 +01:00
console.log(`got 402 from ${details.url}`);
return handleHttpPayment(details.responseHeaders || [],
details.url,
details.tabId);
2017-05-28 00:38:50 +02:00
} else if (details.statusCode === 202) {
2016-11-20 08:58:04 +01:00
return handleBankRequest(wallet!, details.responseHeaders || [],
details.url,
details.tabId);
}
}, { urls: ["<all_urls>"] }, ["responseHeaders", "blocking"]);
2016-10-11 20:26:37 +02:00
}
2016-11-15 15:07:17 +01:00
/**
* Return a promise that resolves
* to the taler wallet db.
*/
function openTalerDb(): Promise<IDBDatabase> {
return new Promise<IDBDatabase>((resolve, reject) => {
const req = indexedDB.open(DB_NAME, WALLET_DB_VERSION);
2016-11-15 15:07:17 +01:00
req.onerror = (e) => {
2017-06-05 02:00:03 +02:00
console.log("taler database error", e);
2016-11-15 15:07:17 +01:00
reject(e);
};
req.onsuccess = (e) => {
2017-06-05 02:00:03 +02:00
req.result.onversionchange = (evt: IDBVersionChangeEvent) => {
console.log(`handling live db version change from ${evt.oldVersion} to ${evt.newVersion}`);
req.result.close();
reinitWallet();
};
2016-11-15 15:07:17 +01:00
resolve(req.result);
};
req.onupgradeneeded = (e) => {
const db = req.result;
2017-06-05 00:52:22 +02:00
console.log(`DB: upgrade needed: oldVersion=${e.oldVersion}, newVersion=${e.newVersion}`);
2016-11-15 15:07:17 +01:00
switch (e.oldVersion) {
case 0: // DB does not exist yet
2017-05-28 01:10:54 +02:00
for (const n in Stores) {
2016-11-15 15:07:17 +01:00
if ((Stores as any)[n] instanceof Store) {
2017-05-28 01:10:54 +02:00
const si: Store<any> = (Stores as any)[n];
2016-11-15 15:07:17 +01:00
const s = db.createObjectStore(si.name, si.storeParams);
2017-05-28 01:10:54 +02:00
for (const indexName in (si as any)) {
2016-11-15 15:07:17 +01:00
if ((si as any)[indexName] instanceof Index) {
2017-05-28 01:10:54 +02:00
const ii: Index<any, any> = (si as any)[indexName];
2017-11-30 04:07:36 +01:00
s.createIndex(ii.indexName, ii.keyPath, ii.options);
2016-11-15 15:07:17 +01:00
}
}
}
}
break;
default:
if (e.oldVersion !== WALLET_DB_VERSION) {
2017-06-05 03:20:28 +02:00
oldDbVersion = e.oldVersion;
chrome.tabs.create({
url: chrome.extension.getURL("/src/webex/pages/reset-required.html"),
});
2016-11-15 15:07:17 +01:00
chrome.browserAction.setBadgeText({text: "err"});
chrome.browserAction.setBadgeBackgroundColor({color: "#F00"});
throw Error("incompatible DB");
}
break;
}
};
});
}
function exportDb(db: IDBDatabase): Promise<any> {
2017-05-28 01:10:54 +02:00
const dump = {
2016-11-15 15:07:17 +01:00
name: db.name,
stores: {} as {[s: string]: any},
2017-05-28 01:10:54 +02:00
version: db.version,
2016-11-15 15:07:17 +01:00
};
return new Promise((resolve, reject) => {
2017-05-28 01:10:54 +02:00
const tx = db.transaction(Array.from(db.objectStoreNames));
2016-11-15 15:07:17 +01:00
tx.addEventListener("complete", () => {
resolve(dump);
});
2017-05-28 01:10:54 +02:00
// tslint:disable-next-line:prefer-for-of
2016-11-15 15:07:17 +01:00
for (let i = 0; i < db.objectStoreNames.length; i++) {
2017-05-28 01:10:54 +02:00
const name = db.objectStoreNames[i];
const storeDump = {} as {[s: string]: any};
2016-11-15 15:07:17 +01:00
dump.stores[name] = storeDump;
2017-05-28 01:10:54 +02:00
tx.objectStore(name)
.openCursor()
.addEventListener("success", (e: Event) => {
const cursor = (e.target as any).result;
if (cursor) {
storeDump[cursor.key] = cursor.value;
cursor.continue();
}
});
2016-11-15 15:07:17 +01:00
}
});
}
2017-04-13 15:05:38 +02:00
function importDb(db: IDBDatabase, dump: any): Promise<void> {
console.log("importing db", dump);
return new Promise<void>((resolve, reject) => {
2017-05-28 01:10:54 +02:00
const tx = db.transaction(Array.from(db.objectStoreNames), "readwrite");
if (dump.stores) {
for (const storeName in dump.stores) {
const objects = [];
const dumpStore = dump.stores[storeName];
for (const key in dumpStore) {
objects.push(dumpStore[key]);
}
console.log(`importing ${objects.length} records into ${storeName}`);
const store = tx.objectStore(storeName);
for (const obj of objects) {
store.put(obj);
}
2017-04-13 15:05:38 +02:00
}
}
tx.addEventListener("complete", () => {
resolve();
});
});
}
2016-11-15 15:07:17 +01:00
function deleteDb() {
indexedDB.deleteDatabase(DB_NAME);
}