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.
5 #import "ios/web/web_state/js/crw_js_window_id_manager.h"
7 #import "base/mac/scoped_nsobject.h"
8 #include "base/strings/string_number_conversions.h"
9 #include "base/strings/sys_string_conversions.h"
10 #include "crypto/random.h"
13 // Number of random bytes in unique key for window ID. The length of the
14 // window ID will be twice this number, as it is hexadecimal encoded.
15 const NSInteger kUniqueKeyLength = 16;
18 @interface CRWJSWindowIdManager () {
19 base::scoped_nsobject<NSString> _windowId;
22 // Returns a string of randomized ASCII characters.
23 - (NSString*)generateUniqueKey;
27 @implementation CRWJSWindowIdManager
29 - (id)initWithReceiver:(CRWJSInjectionReceiver*)receiver {
30 self = [super initWithReceiver:receiver];
32 _windowId.reset([[self generateUniqueKey] retain]);
37 - (NSString*)windowId {
41 - (void)setWindowId:(NSString*)value {
42 _windowId.reset([value copy]);
45 #pragma mark ProtectedMethods
47 - (NSString*)scriptPath {
51 - (NSString*)presenceBeacon {
52 return @"__gCrWeb.windowIdObject";
55 // It is important to recreate the injection content on every injection, because
56 // it cotains the randomly-generated page ID used for security checks.
57 - (NSString*)injectionContent {
58 _windowId.reset([[self generateUniqueKey] retain]);
59 NSString* script = [super injectionContent];
60 return [script stringByReplacingOccurrencesOfString:@"$(WINDOW_ID)"
61 withString:_windowId];
64 #pragma mark - Private
66 - (NSString*)generateUniqueKey {
67 char randomBytes[kUniqueKeyLength];
68 crypto::RandBytes(randomBytes, kUniqueKeyLength);
70 base::SysUTF8ToNSString(base::HexEncode(randomBytes, kUniqueKeyLength));