summaryrefslogtreecommitdiff
path: root/taler-wallet-lib.ts
blob: 21371e86c4019266f047b9555994deb986573191 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/*
  @source https://www.git.taler.net/?p=web-common.git;a=blob_plain;f=taler-wallet-lib.ts;hb=HEAD
  @license magnet:?xt=urn:btih:5de60da917303dbfad4f93fb1b985ced5a89eac2&dn=lgpl-2.1.txt LGPL v21

  @licstart  The following is the entire license notice for the
  JavaScript code in this page.

  Copyright (C) 2015, 2016 INRIA

  The JavaScript code in this page is free software: you can
  redistribute it and/or modify it under the terms of the GNU
  Lesser General Public License (GNU LGPL) as published by the Free Software
  Foundation, either version 2.1 of the License, or (at your option)
  any later version.  The code is distributed WITHOUT ANY WARRANTY;
  without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.  See the GNU LGPL for more details.

  As additional permission under GNU LGPL version 2.1 section 7, you
  may distribute non-source (e.g., minimized or compacted) forms of
  that code without the copy of the GNU LGPL normally required by
  section 4, provided you include this license notice and a URL
  through which recipients can access the Corresponding Source.

  @licend  The above is the entire license notice
  for the JavaScript code in this page.

  @author Marcello Stanisci
  @author Florian Dold
*/

namespace taler {
  "use strict";

  const presentHandlers: any[] = [];
  const absentHandlers: any[] = [];

  let callSeqId = 1;

  let installed = false;
  let probeExecuted = false;
  let pageLoaded = false;

  let errorHandler: any = undefined;

  let sheet: CSSStyleSheet;

  export function onError(handler: any) {
    if (errorHandler) {
      console.warn("Overriding error handler");
    }
    errorHandler = handler;
  }


  /**
   * Error handler for things that go wrong in the merchant
   * frontend browser code.
   */
  function raise_error(reason: string, detail: any) {
    if (errorHandler) {
      errorHandler(reason, detail);
      return;
    }
    alert(`Failure: ${reason}.  No error handler installed.  Open the developer console for more information.`);
    console.error(reason, detail);
    console.warn("No custom error handler set.");
  }


  function callWallet(funcName: string, args: any, onResult?: any): void {
    const detail = JSON.parse(JSON.stringify(args || {}));
    const callId = callSeqId++;
    detail.callId = callId;
    let onTimeout = () => {
      console.warn("timeout for invocation of " + funcName);
    }
    const timeoutHandle: number = setTimeout(onTimeout, 1000);
    let handler = (evt: CustomEvent) => {
      if (evt.detail.callId !== callId) {
        return;
      }
      if (onResult) {
        onResult(evt.detail);
      }
      clearTimeout(timeoutHandle);
      document.removeEventListener(funcName + "-result", handler);
    };
    document.addEventListener(funcName + "-result", handler);
    const evt = new CustomEvent(funcName, {detail});
    document.dispatchEvent(evt)
  }


  /**
   * Confirm that a reserve was created.
   *
   * Used by tightly integrated bank portals.
   */
  export function confirmReserve(reservePub: string) {
    if (!installed) {
      console.log("delaying confirmReserve");
      taler.onPresent(() => {
        confirmReserve(reservePub);
      });
      return;
    }
    callWallet("taler-confirm-reserve", {reserve_pub: reservePub});
  }


  export function createReserve(callbackUrl: string, amount: any, wtTypes: string[]) {
    if (!installed) {
      console.log("delaying createReserve");
      taler.onPresent(() => {
        createReserve(callbackUrl, amount, wtTypes);
      });
      return;
    }
    let args = {
      callback_url: callbackUrl,
      amount: amount,
      wt_types: wtTypes,
    };
    callWallet("taler-create-reserve", args);
  }


  export function executePayment(contractHash: string, payUrl: string, offeringUrl: string, onError?: any) {
    if (!installed) {
      console.log("delaying executePayment");
      taler.onPresent(() => {
        executePayment(contractHash, payUrl, offeringUrl);
      });
      return;
    }
    internalExecutePayment(contractHash, payUrl, offeringUrl);
  }


  export function internalExecutePayment(contractHash: string, payUrl: string, offeringUrl: string, onError?: any) {
    if (!contractHash) {
      raise_error("protocol-violation", {hint: "contract hash not given"});
    }

    function subst(url: string, contractHash: string) {
      url = url.replace("${H_contract}", contractHash);
      url = url.replace("${$}", "$");
      return url;
    }

    /**
     * Handle a failed payment.
     *
     * Try to notify the wallet first, before we show a potentially
     * synchronous error message (such as an alert) or leave the page.
     */
    function handleFailedPayment(r: XMLHttpRequest) {
      let timeoutHandle: number|null = null;
      function err() {
        raise_error("pay-failed", {status: r.status, response: r.responseText});
      }
      function onResp() {
        if (timeoutHandle != null) {
          clearTimeout(timeoutHandle);
          timeoutHandle = null;
        }
        err();
      }
      function onTimeout() {
        timeoutHandle = null
        err();
      }
      callWallet("taler-payment-failed", {}, onResp);
      timeoutHandle = setTimeout(onTimeout, 200);
    }


    function handleResponse(resp: any) {
      console.log("handling taler-notify-payment");
      // Payment timeout in ms.
      let timeout_ms = 1000;
      // Current request.
      let r: XMLHttpRequest|null;
      let timeoutHandle: number|null = null;
      function sendPay() {
        r = new XMLHttpRequest();
        r.open("post", payUrl);
        r.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        r.send(JSON.stringify(resp.payment));
        r.onload = function() {
          if (!r) {
            return;
          }
          switch (r.status) {
            case 200:
              callWallet("taler-payment-succeeded", {}, () => {
                window.location.href = subst(resp.contract.fulfillment_url,
                                             resp.H_contract);
                window.location.reload(true);
              });
              break;
            default:
              handleFailedPayment(r);
              break;
          }
          r = null;
          if (timeoutHandle != null) {
            clearTimeout(timeoutHandle!);
            timeoutHandle = null;
          }
        };
        function retry() {
          if (r) {
            r.abort();
            r = null;
          }
          timeout_ms = Math.min(timeout_ms * 2, 10 * 1000);
          console.log("sendPay timed out, retrying in ", timeout_ms, "ms");
          sendPay();
        }
        timeoutHandle = setTimeout(retry, timeout_ms);
      }
      sendPay();
    }

    let args = {
      H_contract: contractHash,
      offering_url: offeringUrl
    };

    callWallet("taler-get-payment", args, handleResponse);
  }


  export function onPresent(f: any) {
    presentHandlers.push(f);
  }

  export function onAbsent(f: any) {
    absentHandlers.push(f);
  }

  export function offerContractFrom(url: string) {
    if (!installed) {
      console.log("delaying offerContractFrom until GNU Taler wallet is present");
      taler.onPresent(() => {
        offerContractFrom(url);
      });
      return;
    }
    internalOfferContractFrom(url);
  }

  /**
   * Offer a contract to the wallet after
   * downloading it from the given URL.
   */
  export function internalOfferContractFrom(url: string) {
    function handle_contract(contract_wrapper: any) {
      let args = {
          contract_wrapper: contract_wrapper,
          replace_navigation: true
      }
      callWallet("taler-confirm-contract", args);
    };

    var contract_request = new XMLHttpRequest();
    console.log("downloading contract from '" + url + "'")
    contract_request.open("GET", url, true);
    contract_request.onload = function (e) {
      if (contract_request.readyState == 4) {
        if (contract_request.status == 200) {
          console.log("response text:",
                      contract_request.responseText);
          var contract_wrapper = JSON.parse(contract_request.responseText);
          if (!contract_wrapper) {
            console.error("response text was invalid json");
            let detail = {hint: "invalid json", status: contract_request.status, body: contract_request.responseText};
            raise_error("contract-failed", detail);
            return;
          }
          handle_contract(contract_wrapper);
        } else {
          let detail = {hint: "contract download failed", status: contract_request.status, body: contract_request.responseText};
          raise_error("contract-failed", detail);
          return;
        }
      }
    };
    contract_request.onerror = function (e) {
      let detail = {hint: "contract download failed", status: contract_request.status, body: contract_request.responseText};
      raise_error("contract-failed", detail);
      return;
    };
    contract_request.send();
  }


  function initTaler() {

    function handleProbe() {
      probeExecuted = true;
      if (!installed) {
        console.log("taler install detected");
        installed = true;
        announce();
      }
    }

    function probeTaler() {
      probeExecuted = false;
      var eve = new Event("taler-probe");
      document.dispatchEvent(eve);
    }

    let firstTimeoutCalled = false;

    function onProbeTimeout() {
      if (!probeExecuted) {
        if (installed || !firstTimeoutCalled) {
          installed = false;
          firstTimeoutCalled = true;
          console.log("taler uninstall detected");
          announce();
        }
      }
      // try again, maybe it'll be installed ...
      probeTaler();
    }

    /**
     * Announce presence/absence and update stylesheets.
     *
     * Only called after document.readyState is at least "interactive".
     */
    function announce() {
      if (!pageLoaded) {
        return;
      }
      while (sheet.rules.length > 0) {
        sheet.deleteRule(0);
      }
      if (installed) {
        sheet.insertRule(".taler-installed-hide { display: none; }", 0);
        sheet.insertRule(".taler-probed-hide { display: none; }", 0);
        for (var i = 0; i < presentHandlers.length; i++) {
          presentHandlers[i]();
        }
      } else {
        sheet.insertRule(".taler-installed-show { display: none; }", 0);
      }

      if (firstTimeoutCalled) {
        if (!installed) {
          // This rule would be already added when we're installed
          sheet.insertRule(".taler-probed-hide { display: none; }", 0);
          for (var i = 0; i < presentHandlers.length; i++) {
            absentHandlers[i]();
          }
        }
      }

      // if not installed and first timeout not called,
      // we're still doing the detection ...
    }

    function initStyle() {
      const name = "taler-presence-stylesheet";
      const content = "/* Taler stylesheet controlled by JS */";
      let style = document.getElementById(name) as HTMLStyleElement|null; 
      if (!style) {
        style = document.createElement("style");
        // Needed by WebKit
        style.appendChild(document.createTextNode(content));
        style.id = name;
        document.head.appendChild(style);
      } else {
        // We've taken over the stylesheet now,
        // make it clear by clearing all the rules in it
        // and making it obvious in the DOM.
        style.innerText = content;
      }
      sheet = style.sheet as CSSStyleSheet;
    }

    function onPageLoad() {
      pageLoaded = true;
      initStyle();

      // We only start the timeout after the page is interactive.
      window.setInterval(onProbeTimeout, 300);

      announce();
    }

    probeTaler();
    document.addEventListener("taler-probe-result", handleProbe, false);
    // Handle the case where the JavaScript is loaded after the page
    // has been loaded for the first time.
    if (document.readyState == "loading") {
      document.addEventListener("DOMContentLoaded", onPageLoad, false);
    } else {
      onPageLoad();
    }
  }

  // Only init taler if we're not running inside an extension.
  let chrome: any;
  if (!(chrome && chrome.runtime && chrome.runtime.id)) {
    initTaler();
  }
}
// @license-end