1 // Copyright (c) 2012 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.
4 
5 #include "chrome/browser/extensions/convert_user_script.h"
6 
7 #include <stddef.h>
8 
9 #include <memory>
10 #include <string>
11 #include <utility>
12 #include <vector>
13 
14 #include "base/base64.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/files/scoped_temp_dir.h"
18 #include "base/json/json_file_value_serializer.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/values.h"
22 #include "chrome/common/chrome_paths.h"
23 #include "crypto/sha2.h"
24 #include "extensions/browser/extension_user_script_loader.h"
25 #include "extensions/common/api/content_scripts.h"
26 #include "extensions/common/constants.h"
27 #include "extensions/common/extension.h"
28 #include "extensions/common/file_util.h"
29 #include "extensions/common/manifest_constants.h"
30 #include "extensions/common/user_script.h"
31 #include "url/gurl.h"
32 
33 namespace extensions {
34 
ConvertUserScriptToExtension(const base::FilePath & user_script_path,const GURL & original_url,const base::FilePath & extensions_dir,base::string16 * error)35 scoped_refptr<Extension> ConvertUserScriptToExtension(
36     const base::FilePath& user_script_path, const GURL& original_url,
37     const base::FilePath& extensions_dir, base::string16* error) {
38   using ContentScript = api::content_scripts::ContentScript;
39 
40   std::string content;
41   if (!base::ReadFileToString(user_script_path, &content)) {
42     *error = base::ASCIIToUTF16("Could not read source file.");
43     return nullptr;
44   }
45 
46   if (!base::IsStringUTF8(content)) {
47     *error = base::ASCIIToUTF16("User script must be UTF8 encoded.");
48     return nullptr;
49   }
50 
51   UserScript script;
52   if (!UserScriptLoader::ParseMetadataHeader(content, &script)) {
53     *error = base::ASCIIToUTF16("Invalid script header.");
54     return nullptr;
55   }
56 
57   base::FilePath install_temp_dir =
58       file_util::GetInstallTempDir(extensions_dir);
59   if (install_temp_dir.empty()) {
60     *error = base::ASCIIToUTF16(
61         "Could not get path to profile temporary directory.");
62     return nullptr;
63   }
64 
65   base::ScopedTempDir temp_dir;
66   if (!temp_dir.CreateUniqueTempDirUnderPath(install_temp_dir)) {
67     *error = base::ASCIIToUTF16("Could not create temporary directory.");
68     return nullptr;
69   }
70 
71   // Create the manifest
72   std::unique_ptr<base::DictionaryValue> root(new base::DictionaryValue);
73   std::string script_name;
74   if (!script.name().empty() && !script.name_space().empty())
75     script_name = script.name_space() + "/" + script.name();
76   else
77     script_name = original_url.spec();
78 
79   // Create the public key.
80   // User scripts are not signed, but the public key for an extension doubles as
81   // its unique identity, and we need one of those. A user script's unique
82   // identity is its namespace+name, so we hash that to create a public key.
83   // There will be no corresponding private key, which means user scripts cannot
84   // be auto-updated, or claimed in the gallery.
85   char raw[crypto::kSHA256Length] = {0};
86   std::string key;
87   crypto::SHA256HashString(script_name, raw, crypto::kSHA256Length);
88   base::Base64Encode(base::StringPiece(raw, crypto::kSHA256Length), &key);
89 
90   // The script may not have a name field, but we need one for an extension. If
91   // it is missing, use the filename of the original URL.
92   if (!script.name().empty())
93     root->SetString(manifest_keys::kName, script.name());
94   else
95     root->SetString(manifest_keys::kName, original_url.ExtractFileName());
96 
97   // Not all scripts have a version, but we need one. Default to 1.0 if it is
98   // missing.
99   if (!script.version().empty())
100     root->SetString(manifest_keys::kVersion, script.version());
101   else
102     root->SetString(manifest_keys::kVersion, "1.0");
103 
104   root->SetString(manifest_keys::kDescription, script.description());
105   root->SetString(manifest_keys::kPublicKey, key);
106   root->SetBoolean(manifest_keys::kConvertedFromUserScript, true);
107 
108   // If the script provides its own match patterns, we use those. Otherwise, we
109   // generate some using the include globs.
110   std::vector<std::string> matches;
111   if (!script.url_patterns().is_empty()) {
112     matches.reserve(script.url_patterns().size());
113     for (const URLPattern& pattern : script.url_patterns())
114       matches.push_back(pattern.GetAsString());
115   } else {
116     // TODO(aa): Derive tighter matches where possible.
117     matches.push_back("http://*/*");
118     matches.push_back("https://*/*");
119   }
120 
121   // Read the exclude matches, if any are present.
122   std::vector<std::string> exclude_matches;
123   exclude_matches.reserve(script.exclude_url_patterns().size());
124   for (const URLPattern& pattern : script.exclude_url_patterns())
125     exclude_matches.push_back(pattern.GetAsString());
126 
127   ContentScript content_script;
128   content_script.matches = std::move(matches);
129   content_script.exclude_matches =
130       std::make_unique<std::vector<std::string>>(std::move(exclude_matches));
131   content_script.include_globs =
132       std::make_unique<std::vector<std::string>>(script.globs());
133   content_script.exclude_globs =
134       std::make_unique<std::vector<std::string>>(script.exclude_globs());
135 
136   content_script.js = std::make_unique<std::vector<std::string>>();
137   content_script.js->push_back("script.js");
138 
139   if (script.run_location() == UserScript::DOCUMENT_START) {
140     content_script.run_at = api::content_scripts::RUN_AT_DOCUMENT_START;
141   } else if (script.run_location() == UserScript::DOCUMENT_END) {
142     content_script.run_at = api::content_scripts::RUN_AT_DOCUMENT_END;
143   } else if (script.run_location() == UserScript::DOCUMENT_IDLE) {
144     // This is the default, but store it just in case we change that.
145     content_script.run_at = api::content_scripts::RUN_AT_DOCUMENT_IDLE;
146   }
147 
148   auto content_scripts = std::make_unique<base::ListValue>();
149   content_scripts->Append(content_script.ToValue());
150   root->Set(api::content_scripts::ManifestKeys::kContentScripts,
151             std::move(content_scripts));
152 
153   base::FilePath manifest_path = temp_dir.GetPath().Append(kManifestFilename);
154   JSONFileValueSerializer serializer(manifest_path);
155   if (!serializer.Serialize(*root)) {
156     *error = base::ASCIIToUTF16("Could not write JSON.");
157     return nullptr;
158   }
159 
160   // Write the script file.
161   if (!base::CopyFile(user_script_path,
162                       temp_dir.GetPath().AppendASCII("script.js"))) {
163     *error = base::ASCIIToUTF16("Could not copy script file.");
164     return nullptr;
165   }
166 
167   // TODO(rdevlin.cronin): Continue removing std::string errors and replacing
168   // with base::string16
169   std::string utf8_error;
170   scoped_refptr<Extension> extension =
171       Extension::Create(temp_dir.GetPath(), Manifest::INTERNAL, *root,
172                         Extension::NO_FLAGS, &utf8_error);
173   *error = base::UTF8ToUTF16(utf8_error);
174   if (!extension.get()) {
175     NOTREACHED() << "Could not init extension " << *error;
176     return nullptr;
177   }
178 
179   temp_dir.Take();  // The caller takes ownership of the directory.
180   return extension;
181 }
182 
183 }  // namespace extensions
184