1//Copyright 2014-2015 Google Inc. All rights reserved.
3//Use of this source code is governed by a BSD-style
4//license that can be found in the LICENSE file or at
5//https://developers.google.com/open-source/licenses/bsd
8 * @fileoverview The U2F api.
14 * Namespace for the U2F api.
20 * FIDO U2F Javascript API Version
26 * The U2F extension id
29// The Chrome packaged app extension ID.
30// Uncomment this if you want to deploy a server instance that uses
31// the package Chrome app and does not require installing the U2F Chrome extension.
32 u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd';
33 // The U2F Chrome extension ID.
34 // Uncomment this if you want to deploy a server instance that uses
35 // the U2F Chrome extension to authenticate.
36 // u2f.EXTENSION_ID = 'pfboblefjcgdjicmnffhdgionmgcdmne';
40 * Message types for messsages to/from the extension
45 'U2F_REGISTER_REQUEST': 'u2f_register_request',
46 'U2F_REGISTER_RESPONSE': 'u2f_register_response',
47 'U2F_SIGN_REQUEST': 'u2f_sign_request',
48 'U2F_SIGN_RESPONSE': 'u2f_sign_response',
49 'U2F_GET_API_VERSION_REQUEST': 'u2f_get_api_version_request',
50 'U2F_GET_API_VERSION_RESPONSE': 'u2f_get_api_version_response'
55 * Response status codes
63 'CONFIGURATION_UNSUPPORTED': 3,
64 'DEVICE_INELIGIBLE': 4,
70 * A message for registration requests
72 * type: u2f.MessageTypes,
74 * timeoutSeconds: ?number,
82 * A message for registration responses
84 * type: u2f.MessageTypes,
85 * responseData: (u2f.Error | u2f.RegisterResponse | u2f.SignResponse),
93 * An error object for responses
95 * errorCode: u2f.ErrorCodes,
96 * errorMessage: ?string
102 * Data object for a single sign request.
103 * @typedef {enum {BLUETOOTH_RADIO, BLUETOOTH_LOW_ENERGY, USB, NFC}}
109 * Data object for a single sign request.
110 * @typedef {Array<u2f.Transport>}
115 * Data object for a single sign request.
127 * Data object for a sign response.
130 * signatureData: string,
138 * Data object for a registration request.
148 * Data object for a registration response.
152 * transports: Transports,
160 * Data object for a registered key.
164 * transports: ?Transports,
172 * Data object for a get API register response.
174 * js_api_version: number
177u2f.GetJsApiVersionResponse;
180 //Low level MessagePort API support
183 * Sets up a MessagePort to the U2F extension using the
184 * available mechanisms.
185 * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback
187u2f.getMessagePort = function (callback) {
188 if (typeof chrome != 'undefined' && chrome.runtime) {
189 // The actual message here does not matter, but we need to get a reply
190 // for the callback to run. Thus, send an empty signature request
191 // in order to get a failure response.
193 type: u2f.MessageTypes.U2F_SIGN_REQUEST,
196 chrome.runtime.sendMessage(u2f.EXTENSION_ID, msg, function () {
197 if (!chrome.runtime.lastError) {
198 // We are on a whitelisted origin and can talk directly
199 // with the extension.
200 u2f.getChromeRuntimePort_(callback);
202 // chrome.runtime was available, but we couldn't message
203 // the extension directly, use iframe
204 u2f.getIframePort_(callback);
207 } else if (u2f.isAndroidChrome_()) {
208 u2f.getAuthenticatorPort_(callback);
209 } else if (u2f.isIosChrome_()) {
210 u2f.getIosPort_(callback);
212 // chrome.runtime was not available at all, which is normal
213 // when this origin doesn't have access to any extensions.
214 u2f.getIframePort_(callback);
219 * Detect chrome running on android based on the browser's useragent.
222u2f.isAndroidChrome_ = function () {
223 var userAgent = navigator.userAgent;
224 return userAgent.indexOf('Chrome') != -1 &&
225 userAgent.indexOf('Android') != -1;
229 * Detect chrome running on iOS based on the browser's platform.
232u2f.isIosChrome_ = function () {
233 var r = ["iPhone", "iPad", "iPod"];
234 for (var i in r) { if (navigator.platform == r[i]) { return true; } }
236 //return $.inArray(navigator.platform, ["iPhone", "iPad", "iPod"]) > -1;
240 * Connects directly to the extension via chrome.runtime.connect.
241 * @param {function(u2f.WrappedChromeRuntimePort_)} callback
244u2f.getChromeRuntimePort_ = function (callback) {
245 var port = chrome.runtime.connect(u2f.EXTENSION_ID,
246 { 'includeTlsChannelId': true });
247 setTimeout(function () {
248 callback(new u2f.WrappedChromeRuntimePort_(port));
253 * Return a 'port' abstraction to the Authenticator app.
254 * @param {function(u2f.WrappedAuthenticatorPort_)} callback
257u2f.getAuthenticatorPort_ = function (callback) {
258 setTimeout(function () {
259 callback(new u2f.WrappedAuthenticatorPort_());
264 * Return a 'port' abstraction to the iOS client app.
265 * @param {function(u2f.WrappedIosPort_)} callback
268u2f.getIosPort_ = function (callback) {
269 setTimeout(function () {
270 callback(new u2f.WrappedIosPort_());
275 * A wrapper for chrome.runtime.Port that is compatible with MessagePort.
280u2f.WrappedChromeRuntimePort_ = function (port) {
285 * Format and return a sign request compliant with the JS API version supported by the extension.
286 * @param {Array<u2f.SignRequest>} signRequests
287 * @param {number} timeoutSeconds
288 * @param {number} reqId
291u2f.formatSignRequest_ =
292 function (appId, challenge, registeredKeys, timeoutSeconds, reqId) {
293 if (js_api_version === undefined || js_api_version < 1.1) {
294 // Adapt request to the 1.0 JS API
295 var signRequests = [];
296 for (var i = 0; i < registeredKeys.length; i++) {
298 version: registeredKeys[i].version,
299 challenge: challenge,
300 keyHandle: registeredKeys[i].keyHandle,
305 type: u2f.MessageTypes.U2F_SIGN_REQUEST,
306 signRequests: signRequests,
307 timeoutSeconds: timeoutSeconds,
313 type: u2f.MessageTypes.U2F_SIGN_REQUEST,
315 challenge: challenge,
316 registeredKeys: registeredKeys,
317 timeoutSeconds: timeoutSeconds,
323 * Format and return a register request compliant with the JS API version supported by the extension..
324 * @param {Array<u2f.SignRequest>} signRequests
325 * @param {Array<u2f.RegisterRequest>} signRequests
326 * @param {number} timeoutSeconds
327 * @param {number} reqId
330u2f.formatRegisterRequest_ =
331 function (appId, registeredKeys, registerRequests, timeoutSeconds, reqId) {
332 if (js_api_version === undefined || js_api_version < 1.1) {
333 // Adapt request to the 1.0 JS API
334 for (var i = 0; i < registerRequests.length; i++) {
335 registerRequests[i].appId = appId;
337 var signRequests = [];
338 for (var i = 0; i < registeredKeys.length; i++) {
340 version: registeredKeys[i].version,
341 challenge: registerRequests[0],
342 keyHandle: registeredKeys[i].keyHandle,
347 type: u2f.MessageTypes.U2F_REGISTER_REQUEST,
348 signRequests: signRequests,
349 registerRequests: registerRequests,
350 timeoutSeconds: timeoutSeconds,
356 type: u2f.MessageTypes.U2F_REGISTER_REQUEST,
358 registerRequests: registerRequests,
359 registeredKeys: registeredKeys,
360 timeoutSeconds: timeoutSeconds,
367 * Posts a message on the underlying channel.
368 * @param {Object} message
370u2f.WrappedChromeRuntimePort_.prototype.postMessage = function (message) {
371 this.port_.postMessage(message);
376 * Emulates the HTML 5 addEventListener interface. Works only for the
377 * onmessage event, which is hooked up to the chrome.runtime.Port.onMessage.
378 * @param {string} eventName
379 * @param {function({data: Object})} handler
381u2f.WrappedChromeRuntimePort_.prototype.addEventListener =
382 function (eventName, handler) {
383 var name = eventName.toLowerCase();
384 if (name == 'message' || name == 'onmessage') {
385 this.port_.onMessage.addListener(function (message) {
386 // Emulate a minimal MessageEvent object
387 handler({ 'data': message });
390 console.error('WrappedChromeRuntimePort only supports onMessage');
395 * Wrap the Authenticator app with a MessagePort interface.
399u2f.WrappedAuthenticatorPort_ = function () {
400 this.requestId_ = -1;
401 this.requestObject_ = null;
405 * Launch the Authenticator intent.
406 * @param {Object} message
408u2f.WrappedAuthenticatorPort_.prototype.postMessage = function (message) {
410 u2f.WrappedAuthenticatorPort_.INTENT_URL_BASE_ +
411 ';S.request=' + encodeURIComponent(JSON.stringify(message)) +
413 document.location = intentUrl;
417 * Tells what type of port this is.
418 * @return {String} port type
420u2f.WrappedAuthenticatorPort_.prototype.getPortType = function () {
421 return "WrappedAuthenticatorPort_";
426 * Emulates the HTML 5 addEventListener interface.
427 * @param {string} eventName
428 * @param {function({data: Object})} handler
430u2f.WrappedAuthenticatorPort_.prototype.addEventListener = function (eventName, handler) {
431 var name = eventName.toLowerCase();
432 if (name == 'message') {
434 /* Register a callback to that executes when
435 * chrome injects the response. */
436 window.addEventListener(
437 'message', self.onRequestUpdate_.bind(self, handler), false);
439 console.error('WrappedAuthenticatorPort only supports message');
444 * Callback invoked when a response is received from the Authenticator.
445 * @param function({data: Object}) callback
446 * @param {Object} message message Object
448u2f.WrappedAuthenticatorPort_.prototype.onRequestUpdate_ =
449 function (callback, message) {
450 var messageObject = JSON.parse(message.data);
451 var intentUrl = messageObject['intentURL'];
453 var errorCode = messageObject['errorCode'];
454 var responseObject = null;
455 if (messageObject.hasOwnProperty('data')) {
456 responseObject = /** @type {Object} */ (
457 JSON.parse(messageObject['data']));
460 callback({ 'data': responseObject });
464 * Base URL for intents to Authenticator.
468u2f.WrappedAuthenticatorPort_.INTENT_URL_BASE_ =
469 'intent:#Intent;action=com.google.android.apps.authenticator.AUTHENTICATE';
472 * Wrap the iOS client app with a MessagePort interface.
476u2f.WrappedIosPort_ = function () { };
479 * Launch the iOS client app request
480 * @param {Object} message
482u2f.WrappedIosPort_.prototype.postMessage = function (message) {
483 var str = JSON.stringify(message);
484 var url = "u2f://auth?" + encodeURI(str);
485 location.replace(url);
489 * Tells what type of port this is.
490 * @return {String} port type
492u2f.WrappedIosPort_.prototype.getPortType = function () {
493 return "WrappedIosPort_";
497 * Emulates the HTML 5 addEventListener interface.
498 * @param {string} eventName
499 * @param {function({data: Object})} handler
501u2f.WrappedIosPort_.prototype.addEventListener = function (eventName, handler) {
502 var name = eventName.toLowerCase();
503 if (name !== 'message') {
504 console.error('WrappedIosPort only supports message');
509 * Sets up an embedded trampoline iframe, sourced from the extension.
510 * @param {function(MessagePort)} callback
513u2f.getIframePort_ = function (callback) {
515 var iframeOrigin = 'chrome-extension://' + u2f.EXTENSION_ID;
516 var iframe = document.createElement('iframe');
517 iframe.src = iframeOrigin + '/u2f-comms.html';
518 iframe.setAttribute('style', 'display:none');
519 document.body.appendChild(iframe);
521 var channel = new MessageChannel();
522 var ready = function (message) {
523 if (message.data == 'ready') {
524 channel.port1.removeEventListener('message', ready);
525 callback(channel.port1);
527 console.error('First event on iframe port was not "ready"');
530 channel.port1.addEventListener('message', ready);
531 channel.port1.start();
533 iframe.addEventListener('load', function () {
534 // Deliver the port to the iframe and initialize
535 iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]);
543 * Default extension response timeout in seconds.
546u2f.EXTENSION_TIMEOUT_SEC = 30;
549 * A singleton instance for a MessagePort to the extension.
550 * @type {MessagePort|u2f.WrappedChromeRuntimePort_}
556 * Callbacks waiting for a port
557 * @type {Array<function((MessagePort|u2f.WrappedChromeRuntimePort_))>}
560u2f.waitingForPort_ = [];
563 * A counter for requestIds.
570 * A map from requestIds to client callbacks
571 * @type {Object.<number,(function((u2f.Error|u2f.RegisterResponse))
572 * |function((u2f.Error|u2f.SignResponse)))>}
575u2f.callbackMap_ = {};
578 * Creates or retrieves the MessagePort singleton to use.
579 * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback
582u2f.getPortSingleton_ = function (callback) {
586 if (u2f.waitingForPort_.length == 0) {
587 u2f.getMessagePort(function (port) {
589 u2f.port_.addEventListener('message',
590 /** @type {function(Event)} */ (u2f.responseHandler_));
592 // Careful, here be async callbacks. Maybe.
593 while (u2f.waitingForPort_.length)
594 u2f.waitingForPort_.shift()(u2f.port_);
597 u2f.waitingForPort_.push(callback);
602 * Handles response messages from the extension.
603 * @param {MessageEvent.<u2f.Response>} message
606u2f.responseHandler_ = function (message) {
607 var response = message.data;
608 var reqId = response['requestId'];
609 if (!reqId || !u2f.callbackMap_[reqId]) {
610 console.error('Unknown or missing requestId in response.');
613 var cb = u2f.callbackMap_[reqId];
614 delete u2f.callbackMap_[reqId];
615 cb(response['responseData']);
619 * Dispatches an array of sign requests to available U2F tokens.
620 * If the JS API version supported by the extension is unknown, it first sends a
621 * message to the extension to find out the supported API version and then it sends
623 * @param {string=} appId
624 * @param {string=} challenge
625 * @param {Array<u2f.RegisteredKey>} registeredKeys
626 * @param {function((u2f.Error|u2f.SignResponse))} callback
627 * @param {number=} opt_timeoutSeconds
629u2f.sign = function (appId, challenge, registeredKeys, callback, opt_timeoutSeconds) {
630 if (js_api_version === undefined) {
631 // Send a message to get the extension to JS API version, then send the actual sign request.
633 function (response) {
634 js_api_version = response['js_api_version'] === undefined ? 0 : response['js_api_version'];
635 //console.log("Extension JS API Version: ", js_api_version);
636 u2f.sendSignRequest(appId, challenge, registeredKeys, callback, opt_timeoutSeconds);
639 // We know the JS API version. Send the actual sign request in the supported API version.
640 u2f.sendSignRequest(appId, challenge, registeredKeys, callback, opt_timeoutSeconds);
645 * Dispatches an array of sign requests to available U2F tokens.
646 * @param {string=} appId
647 * @param {string=} challenge
648 * @param {Array<u2f.RegisteredKey>} registeredKeys
649 * @param {function((u2f.Error|u2f.SignResponse))} callback
650 * @param {number=} opt_timeoutSeconds
652u2f.sendSignRequest = function (appId, challenge, registeredKeys, callback, opt_timeoutSeconds) {
653 u2f.getPortSingleton_(function (port) {
654 var reqId = ++u2f.reqCounter_;
655 u2f.callbackMap_[reqId] = callback;
656 var timeoutSeconds = (typeof opt_timeoutSeconds !== 'undefined' ?
657 opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC);
658 var req = u2f.formatSignRequest_(appId, challenge, registeredKeys, timeoutSeconds, reqId);
659 port.postMessage(req);
664 * Dispatches register requests to available U2F tokens. An array of sign
665 * requests identifies already registered tokens.
666 * If the JS API version supported by the extension is unknown, it first sends a
667 * message to the extension to find out the supported API version and then it sends
668 * the register request.
669 * @param {string=} appId
670 * @param {Array<u2f.RegisterRequest>} registerRequests
671 * @param {Array<u2f.RegisteredKey>} registeredKeys
672 * @param {function((u2f.Error|u2f.RegisterResponse))} callback
673 * @param {number=} opt_timeoutSeconds
675u2f.register = function (appId, registerRequests, registeredKeys, callback, opt_timeoutSeconds) {
676 if (js_api_version === undefined) {
677 // Send a message to get the extension to JS API version, then send the actual register request.
679 function (response) {
680 js_api_version = response['js_api_version'] === undefined ? 0: response['js_api_version'];
681 //console.log("Extension JS API Version: ", js_api_version);
682 u2f.sendRegisterRequest(appId, registerRequests, registeredKeys,
683 callback, opt_timeoutSeconds);
686 // We know the JS API version. Send the actual register request in the supported API version.
687 u2f.sendRegisterRequest(appId, registerRequests, registeredKeys,
688 callback, opt_timeoutSeconds);
693 * Dispatches register requests to available U2F tokens. An array of sign
694 * requests identifies already registered tokens.
695 * @param {string=} appId
696 * @param {Array<u2f.RegisterRequest>} registerRequests
697 * @param {Array<u2f.RegisteredKey>} registeredKeys
698 * @param {function((u2f.Error|u2f.RegisterResponse))} callback
699 * @param {number=} opt_timeoutSeconds
701u2f.sendRegisterRequest = function (appId, registerRequests, registeredKeys, callback, opt_timeoutSeconds) {
702 u2f.getPortSingleton_(function (port) {
703 var reqId = ++u2f.reqCounter_;
704 u2f.callbackMap_[reqId] = callback;
705 var timeoutSeconds = (typeof opt_timeoutSeconds !== 'undefined' ?
706 opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC);
707 var req = u2f.formatRegisterRequest_(
708 appId, registeredKeys, registerRequests, timeoutSeconds, reqId);
709 port.postMessage(req);
715 * Dispatches a message to the extension to find out the supported
717 * If the user is on a mobile phone and is thus using Google Authenticator instead
718 * of the Chrome extension, don't send the request and simply return 0.
719 * @param {function((u2f.Error|u2f.GetJsApiVersionResponse))} callback
720 * @param {number=} opt_timeoutSeconds
722u2f.getApiVersion = function (callback, opt_timeoutSeconds) {
723 u2f.getPortSingleton_(function (port) {
724 // If we are using Android Google Authenticator or iOS client app,
725 // do not fire an intent to ask which JS API version to use.
726 if (port.getPortType) {
728 switch (port.getPortType()) {
729 case 'WrappedIosPort_':
730 case 'WrappedAuthenticatorPort_':
738 callback({ 'js_api_version': apiVersion });
741 var reqId = ++u2f.reqCounter_;
742 u2f.callbackMap_[reqId] = callback;
744 type: u2f.MessageTypes.U2F_GET_API_VERSION_REQUEST,
745 timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ?
746 opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC),
749 port.postMessage(req);