summaryrefslogtreecommitdiffstats
path: root/chrome/renderer/resources/extensions/platform_keys_custom_bindings.js
blob: 924e60eab81cda87f44cb3e51b549b7999832ed7 (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
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Custom binding for the platformKeys API.

var binding = require('binding').Binding.create('platformKeys');
var SubtleCrypto = require('platformKeys.SubtleCrypto').SubtleCrypto;
var getPublicKey = require('platformKeys.getPublicKey').getPublicKey;
var internalAPI = require('platformKeys.internalAPI');

var keyModule = require('platformKeys.Key');
var Key = keyModule.Key;
var KeyType = keyModule.KeyType;
var KeyUsage = keyModule.KeyUsage;

function createPublicKey(publicKeySpki, algorithm) {
  return new Key(KeyType.public, publicKeySpki, algorithm, [KeyUsage.verify],
                 true /* extractable */);
}

function createPrivateKey(publicKeySpki, algorithm) {
  return new Key(KeyType.private, publicKeySpki, algorithm, [KeyUsage.sign],
                 false /* not extractable */);
}

binding.registerCustomHook(function(api) {
  var apiFunctions = api.apiFunctions;
  var subtleCrypto = new SubtleCrypto('' /* tokenId */);

  apiFunctions.setHandleRequest(
      'selectClientCertificates', function(details, callback) {
        internalAPI.selectClientCertificates(details, function(matches) {
          if (chrome.runtime.lastError) {
            callback([]);
            return;
          }
          callback($Array.map(matches, function(match) {
            // internalAPI.selectClientCertificates returns publicExponent as
            // ArrayBuffer, but it should be a Uint8Array.
            if (match.keyAlgorithm.publicExponent) {
              match.keyAlgorithm.publicExponent =
                  new Uint8Array(match.keyAlgorithm.publicExponent);
            }
            return match;
          }));
        });
      });

  apiFunctions.setHandleRequest(
      'subtleCrypto', function() { return subtleCrypto });

  apiFunctions.setHandleRequest(
      'getKeyPair', function(cert, params, callback) {
        getPublicKey(cert, params, function(publicKey, algorithm) {
          if (chrome.runtime.lastError) {
            callback();
            return;
          }
          callback(createPublicKey(publicKey, algorithm),
                   createPrivateKey(publicKey, algorithm));
        });
      });
});

exports.binding = binding.generate();