1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 * @fileoverview Does common handling for requests coming from web pages and
7 * routes them to the provided handler.
11 * Gets the scheme + origin from a web url.
12 * @param {string} url Input url
13 * @return {?string} Scheme and origin part if url parses
15 function getOriginFromUrl(url) {
16 var re = new RegExp('^(https?://)[^/]*/?');
17 var originarray = re.exec(url);
18 if (originarray == null) return originarray;
19 var origin = originarray[0];
20 while (origin.charAt(origin.length - 1) == '/') {
21 origin = origin.substring(0, origin.length - 1);
23 if (origin == 'http:' || origin == 'https:')
29 * Returns whether the registered key appears to be valid.
30 * @param {Object} registeredKey The registered key object.
31 * @param {boolean} appIdRequired Whether the appId property is required on
33 * @return {boolean} Whether the object appears valid.
35 function isValidRegisteredKey(registeredKey, appIdRequired) {
36 if (appIdRequired && !registeredKey.hasOwnProperty('appId')) {
39 if (!registeredKey.hasOwnProperty('keyHandle'))
41 if (registeredKey['version']) {
42 if (registeredKey['version'] != 'U2F_V1' &&
43 registeredKey['version'] != 'U2F_V2') {
51 * Returns whether the array of registered keys appears to be valid.
52 * @param {Array<Object>} registeredKeys The array of registered keys.
53 * @param {boolean} appIdRequired Whether the appId property is required on
55 * @return {boolean} Whether the array appears valid.
57 function isValidRegisteredKeyArray(registeredKeys, appIdRequired) {
58 return registeredKeys.every(function(key) {
59 return isValidRegisteredKey(key, appIdRequired);
64 * Returns whether the array of SignChallenges appears to be valid.
65 * @param {Array<SignChallenge>} signChallenges The array of sign challenges.
66 * @param {boolean} challengeValueRequired Whether each challenge object
67 * requires a challenge value.
68 * @param {boolean} appIdRequired Whether the appId property is required on
70 * @return {boolean} Whether the array appears valid.
72 function isValidSignChallengeArray(signChallenges, challengeValueRequired,
74 for (var i = 0; i < signChallenges.length; i++) {
75 var incomingChallenge = signChallenges[i];
76 if (challengeValueRequired &&
77 !incomingChallenge.hasOwnProperty('challenge'))
79 if (!isValidRegisteredKey(incomingChallenge, appIdRequired)) {
86 /** Posts the log message to the log url.
87 * @param {string} logMsg the log message to post.
88 * @param {string=} opt_logMsgUrl the url to post log messages to.
90 function logMessage(logMsg, opt_logMsgUrl) {
91 console.log(UTIL_fmt('logMessage("' + logMsg + '")'));
96 // Image fetching is not allowed per packaged app CSP.
97 // But video and audio is.
98 var audio = new Audio();
99 audio.src = opt_logMsgUrl + logMsg;
103 * @param {Object} request Request object
104 * @param {MessageSender} sender Sender frame
105 * @param {Function} sendResponse Response callback
106 * @return {?Closeable} Optional handler object that should be closed when port
109 function handleWebPageRequest(request, sender, sendResponse) {
110 switch (request.type) {
111 case GnubbyMsgTypes.ENROLL_WEB_REQUEST:
112 return handleWebEnrollRequest(sender, request, sendResponse);
114 case GnubbyMsgTypes.SIGN_WEB_REQUEST:
115 return handleWebSignRequest(sender, request, sendResponse);
117 case MessageTypes.U2F_REGISTER_REQUEST:
118 return handleU2fEnrollRequest(sender, request, sendResponse);
120 case MessageTypes.U2F_SIGN_REQUEST:
121 return handleU2fSignRequest(sender, request, sendResponse);
125 makeU2fErrorResponse(request, ErrorCodes.BAD_REQUEST, undefined,
126 MessageTypes.U2F_REGISTER_RESPONSE));
132 * Set-up listeners for webpage connect.
133 * @param {Object} port connection is on.
134 * @param {Object} request that got received on port.
136 function handleWebPageConnect(port, request) {
139 var onMessage = function(request) {
140 console.log(UTIL_fmt('request'));
141 console.log(request);
142 closeable = handleWebPageRequest(request, port.sender,
144 response['requestId'] = request['requestId'];
145 port.postMessage(response);
149 var onDisconnect = function() {
150 port.onMessage.removeListener(onMessage);
151 port.onDisconnect.removeListener(onDisconnect);
152 if (closeable) closeable.close();
155 port.onMessage.addListener(onMessage);
156 port.onDisconnect.addListener(onDisconnect);
158 // Start work on initial message.
163 * Makes a response to a request.
164 * @param {Object} request The request to make a response to.
165 * @param {string} responseSuffix How to name the response's type.
166 * @param {string=} opt_defaultType The default response type, if none is
167 * present in the request.
168 * @return {Object} The response object.
170 function makeResponseForRequest(request, responseSuffix, opt_defaultType) {
172 if (request && request.type) {
173 type = request.type.replace(/_request$/, responseSuffix);
175 type = opt_defaultType;
177 var reply = { 'type': type };
178 if (request && request.requestId) {
179 reply.requestId = request.requestId;
185 * Makes a response to a U2F request with an error code.
186 * @param {Object} request The request to make a response to.
187 * @param {ErrorCodes} code The error code to return.
188 * @param {string=} opt_detail An error detail string.
189 * @param {string=} opt_defaultType The default response type, if none is
190 * present in the request.
191 * @return {Object} The U2F error.
193 function makeU2fErrorResponse(request, code, opt_detail, opt_defaultType) {
194 var reply = makeResponseForRequest(request, '_response', opt_defaultType);
195 var error = {'errorCode': code};
197 error['errorMessage'] = opt_detail;
199 reply['responseData'] = error;
204 * Makes a success response to a web request with a responseData object.
205 * @param {Object} request The request to make a response to.
206 * @param {Object} responseData The response data.
207 * @return {Object} The web error.
209 function makeU2fSuccessResponse(request, responseData) {
210 var reply = makeResponseForRequest(request, '_response');
211 reply['responseData'] = responseData;
216 * Makes a response to a web request with an error code.
217 * @param {Object} request The request to make a response to.
218 * @param {GnubbyCodeTypes} code The error code to return.
219 * @param {string=} opt_defaultType The default response type, if none is
220 * present in the request.
221 * @return {Object} The web error.
223 function makeWebErrorResponse(request, code, opt_defaultType) {
224 var reply = makeResponseForRequest(request, '_reply', opt_defaultType);
225 reply['code'] = code;
230 * Makes a success response to a web request with a responseData object.
231 * @param {Object} request The request to make a response to.
232 * @param {Object} responseData The response data.
233 * @return {Object} The web error.
235 function makeWebSuccessResponse(request, responseData) {
236 var reply = makeResponseForRequest(request, '_reply');
237 reply['code'] = GnubbyCodeTypes.OK;
238 reply['responseData'] = responseData;
243 * Maps an error code from the ErrorCodes namespace to the GnubbyCodeTypes
245 * @param {ErrorCodes} errorCode Error in the ErrorCodes namespace.
246 * @param {boolean} forSign Whether the error is for a sign request.
247 * @return {GnubbyCodeTypes} Error code in the GnubbyCodeTypes namespace.
249 function mapErrorCodeToGnubbyCodeType(errorCode, forSign) {
252 case ErrorCodes.BAD_REQUEST:
253 return GnubbyCodeTypes.BAD_REQUEST;
255 case ErrorCodes.DEVICE_INELIGIBLE:
256 return forSign ? GnubbyCodeTypes.NONE_PLUGGED_ENROLLED :
257 GnubbyCodeTypes.ALREADY_ENROLLED;
259 case ErrorCodes.TIMEOUT:
260 return GnubbyCodeTypes.WAIT_TOUCH;
262 return GnubbyCodeTypes.UNKNOWN_ERROR;
266 * Maps a helper's error code from the DeviceStatusCodes namespace to a
268 * @param {number} code Error code from DeviceStatusCodes namespace.
269 * @return {U2fError} An error.
271 function mapDeviceStatusCodeToU2fError(code) {
273 case DeviceStatusCodes.WRONG_DATA_STATUS:
274 return {errorCode: ErrorCodes.DEVICE_INELIGIBLE};
276 case DeviceStatusCodes.TIMEOUT_STATUS:
277 case DeviceStatusCodes.WAIT_TOUCH_STATUS:
278 return {errorCode: ErrorCodes.TIMEOUT};
281 var reportedError = {
282 errorCode: ErrorCodes.OTHER_ERROR,
283 errorMessage: 'device status code: ' + code.toString(16)
285 return reportedError;
290 * Sends a response, using the given sentinel to ensure at most one response is
291 * sent. Also closes the closeable, if it's given.
292 * @param {boolean} sentResponse Whether a response has already been sent.
293 * @param {?Closeable} closeable A thing to close.
294 * @param {*} response The response to send.
295 * @param {Function} sendResponse A function to send the response.
297 function sendResponseOnce(sentResponse, closeable, response, sendResponse) {
304 // If the page has gone away or the connection has otherwise gone,
305 // sendResponse fails.
306 sendResponse(response);
307 } catch (exception) {
308 console.warn('sendResponse failed: ' + exception);
311 console.warn(UTIL_fmt('Tried to reply more than once! Juan, FIX ME'));
316 * @param {!string} string Input string
317 * @return {Array<number>} SHA256 hash value of string.
319 function sha256HashOfString(string) {
320 var s = new SHA256();
321 s.update(UTIL_StringToBytes(string));
326 * Normalizes the TLS channel ID value:
327 * 1. Converts semantically empty values (undefined, null, 0) to the empty
329 * 2. Converts valid JSON strings to a JS object.
330 * 3. Otherwise, returns the input value unmodified.
331 * @param {Object|string|undefined} opt_tlsChannelId TLS Channel id
332 * @return {Object|string} The normalized TLS channel ID value.
334 function tlsChannelIdValue(opt_tlsChannelId) {
335 if (!opt_tlsChannelId) {
336 // Case 1: Always set some value for TLS channel ID, even if it's the empty
337 // string: this browser definitely supports them.
340 if (typeof opt_tlsChannelId === 'string') {
342 var obj = JSON.parse(opt_tlsChannelId);
344 // Case 1: The string value 'null' parses as the Javascript object null,
345 // so return an empty string: the browser definitely supports TLS
349 // Case 2: return the value as a JS object.
350 return /** @type {Object} */ (obj);
352 console.warn('Unparseable TLS channel ID value ' + opt_tlsChannelId);
353 // Case 3: return the value unmodified.
356 return opt_tlsChannelId;
360 * Creates a browser data object with the given values.
361 * @param {!string} type A string representing the "type" of this browser data
363 * @param {!string} serverChallenge The server's challenge, as a base64-
365 * @param {!string} origin The server's origin, as seen by the browser.
366 * @param {Object|string|undefined} opt_tlsChannelId TLS Channel Id
367 * @return {string} A string representation of the browser data object.
369 function makeBrowserData(type, serverChallenge, origin, opt_tlsChannelId) {
372 'challenge' : serverChallenge,
375 if (BROWSER_SUPPORTS_TLS_CHANNEL_ID) {
376 browserData['cid_pubkey'] = tlsChannelIdValue(opt_tlsChannelId);
378 return JSON.stringify(browserData);
382 * Creates a browser data object for an enroll request with the given values.
383 * @param {!string} serverChallenge The server's challenge, as a base64-
385 * @param {!string} origin The server's origin, as seen by the browser.
386 * @param {Object|string|undefined} opt_tlsChannelId TLS Channel Id
387 * @return {string} A string representation of the browser data object.
389 function makeEnrollBrowserData(serverChallenge, origin, opt_tlsChannelId) {
390 return makeBrowserData(
391 'navigator.id.finishEnrollment', serverChallenge, origin,
396 * Creates a browser data object for a sign request with the given values.
397 * @param {!string} serverChallenge The server's challenge, as a base64-
399 * @param {!string} origin The server's origin, as seen by the browser.
400 * @param {Object|string|undefined} opt_tlsChannelId TLS Channel Id
401 * @return {string} A string representation of the browser data object.
403 function makeSignBrowserData(serverChallenge, origin, opt_tlsChannelId) {
404 return makeBrowserData(
405 'navigator.id.getAssertion', serverChallenge, origin, opt_tlsChannelId);
409 * Encodes the sign data as an array of sign helper challenges.
410 * @param {Array<SignChallenge>} signChallenges The sign challenges to encode.
411 * @param {string|undefined} opt_defaultChallenge A default sign challenge
412 * value, if a request does not provide one.
413 * @param {string=} opt_defaultAppId The app id to use for each challenge, if
414 * the challenge contains none.
415 * @param {function(string, string): string=} opt_challengeHashFunction
416 * A function that produces, from a key handle and a raw challenge, a hash
417 * of the raw challenge. If none is provided, a default hash function is
419 * @return {!Array<SignHelperChallenge>} The sign challenges, encoded.
421 function encodeSignChallenges(signChallenges, opt_defaultChallenge,
422 opt_defaultAppId, opt_challengeHashFunction) {
423 function encodedSha256(keyHandle, challenge) {
424 return B64_encode(sha256HashOfString(challenge));
426 var challengeHashFn = opt_challengeHashFunction || encodedSha256;
427 var encodedSignChallenges = [];
428 if (signChallenges) {
429 for (var i = 0; i < signChallenges.length; i++) {
430 var challenge = signChallenges[i];
431 var keyHandle = challenge['keyHandle'];
433 if (challenge.hasOwnProperty('challenge')) {
434 challengeValue = challenge['challenge'];
436 challengeValue = opt_defaultChallenge;
438 var challengeHash = challengeHashFn(keyHandle, challengeValue);
440 if (challenge.hasOwnProperty('appId')) {
441 appId = challenge['appId'];
443 appId = opt_defaultAppId;
445 var encodedChallenge = {
446 'challengeHash': challengeHash,
447 'appIdHash': B64_encode(sha256HashOfString(appId)),
448 'keyHandle': keyHandle,
449 'version': (challenge['version'] || 'U2F_V1')
451 encodedSignChallenges.push(encodedChallenge);
454 return encodedSignChallenges;
458 * Makes a sign helper request from an array of challenges.
459 * @param {Array<SignHelperChallenge>} challenges The sign challenges.
460 * @param {number=} opt_timeoutSeconds Timeout value.
461 * @param {string=} opt_logMsgUrl URL to log to.
462 * @return {SignHelperRequest} The sign helper request.
464 function makeSignHelperRequest(challenges, opt_timeoutSeconds, opt_logMsgUrl) {
466 'type': 'sign_helper_request',
467 'signData': challenges,
468 'timeout': opt_timeoutSeconds || 0,
469 'timeoutSeconds': opt_timeoutSeconds || 0
471 if (opt_logMsgUrl !== undefined) {
472 request.logMsgUrl = opt_logMsgUrl;