electron/shell/browser/api/electron_api_session.cc

1244 lines
45 KiB
C++
Raw Normal View History

// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_session.h"
#include <algorithm>
2016-08-01 11:11:17 +00:00
#include <map>
#include <memory>
#include <set>
2015-06-24 03:59:11 +00:00
#include <string>
#include <utility>
#include <vector>
2015-06-24 03:59:11 +00:00
#include "base/command_line.h"
2015-07-26 08:30:02 +00:00
#include "base/files/file_path.h"
#include "base/guid.h"
2016-01-14 09:31:54 +00:00
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_switches.h"
2015-07-26 08:30:02 +00:00
#include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/download_url_parameters.h"
2016-08-26 22:30:02 +00:00
#include "components/prefs/pref_service.h"
#include "components/prefs/value_map_pref_store.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
#include "components/proxy_config/proxy_prefs.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager_delegate.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/storage_partition.h"
2020-05-19 17:18:12 +00:00
#include "gin/arguments.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
chore: bump chromium to 1e9f9a24aa12 (master) (#17880) * chore: bump chromium in DEPS to 1e9f9a24aa12bea9cf194a82a7e249bd1242ec4f * chore: update patches * Make WebContents' theme color a base::Optional<SkColor> https://chromium-review.googlesource.com/c/chromium/src/+/1540022 * update autofill patch for incorrect header includes * Move Shell messages to web_test and rename to BlinkTest. https://chromium-review.googlesource.com/c/chromium/src/+/1525181 * Make PlatformNotificationServiceImpl a KeyedService. https://chromium-review.googlesource.com/c/chromium/src/+/1336150 * Move MediaPlayerId to its own file. https://chromium-review.googlesource.com/c/chromium/src/+/1547057 * Remove net/base/completion_callback.h, which is no longer used https://chromium-review.googlesource.com/c/chromium/src/+/1552821 * AW NS: support file scheme cookies https://chromium-review.googlesource.com/c/chromium/src/+/1533486 * Remove SecurityInfo and adapt remaining consumers https://chromium-review.googlesource.com/c/chromium/src/+/1509455 * Remove deprecated type-specific number to string conversion functions https://chromium-review.googlesource.com/c/chromium/src/+/1545881 * DevTools: Adding new performance histograms for launch of top 4 tools https://chromium-review.googlesource.com/c/chromium/src/+/1506388 * Update include paths for //base/hash/hash.h https://chromium-review.googlesource.com/c/chromium/src/+/1544630 * build: Disable ensure_gn_version gclient hook for mac CI checkout * update patches * use maybe version of v8::String::NewFromTwoByte * bump appveyor image version * fix mac ci hopefully * Convert enum to enum class for MenuAnchorPosition https://chromium-review.googlesource.com/c/chromium/src/+/1530508 * use maybe version of ToObject * RenderViewHost::GetProcess is no longer const * Unrefcount AuthChallengeInfo https://chromium-review.googlesource.com/c/chromium/src/+/1550631 * MenuButtonController takes Button rather than MenuButton https://chromium-review.googlesource.com/c/chromium/src/+/1500935 * add //ui/views_bridge_mac to deps to fix link error * forward declare views::Button in atom::MenuDelegate * more v8 patches * base/{=> hash}/md5.h https://chromium-review.googlesource.com/c/chromium/src/+/1535124 * gfx::{PlatformFontWin => win}::* https://chromium-review.googlesource.com/c/chromium/src/+/1534178 * fix v8 patches * [base] Rename TaskScheduler to ThreadPool https://chromium-review.googlesource.com/c/chromium/src/+/1561552 * use internal_config_base for bytecode_builtins_list_generator avoids windows link errors * FIXME: temporarily disable v8/breakpad integration * FIXME: temporarily disable prevent-will-redirect test * FIXME: disable neon on aarch64 pending crbug.com/953815 * update to account for WebCursor refactor https://chromium-review.googlesource.com/c/chromium/src/+/1562755 * enable stack dumping on appveyor * Revert "FIXME: disable neon on aarch64 pending crbug.com/953815" This reverts commit 57f082026be3d83069f2a2814684abf4dc9e7b53. * fix: remove const qualifiers to match upstream * fix: remove const qualifiers to match upstream in cc files as well * don't throw an error when testing if an object is an object * use non-deprecated Buffer constructor * Remove net::CookieSameSite::DEFAULT_MODE enum value https://chromium-review.googlesource.com/c/chromium/src/+/1567955 * depend on modded dbus-native to work around buffer deprecation https://github.com/sidorares/dbus-native/pull/262 * revert clang roll to fix arm build on linux * fixup! depend on modded dbus-native to work around buffer deprecation need more coffee * update coffee-script * robustify verify-mksnapshot w.r.t. command-line parameters * Revert "robustify verify-mksnapshot w.r.t. command-line parameters" This reverts commit a49af01411f684f6025528d604895c3696e0bc57. * fix mksnapshot by matching args * update patches * TMP: enable rdp on appveyor * Changed ContentBrowserClient::CreateQuotaPermissionContext() to return scoped_refptr. https://chromium-review.googlesource.com/c/chromium/src/+/1569376 * Make content::ResourceType an enum class. https://chromium-review.googlesource.com/c/chromium/src/+/1569345 * fixup! Make content::ResourceType an enum class. * turn off rdp * use net::CompletionRepeatingCallback instead of base::Callback<void(int)> * remove disable_ensure_gn_version_gclient_hook.patch * copy repeating callback instead of std::move * fix lint * add completion_repeating_callback.h include
2019-04-20 17:20:37 +00:00
#include "net/base/completion_repeating_callback.h"
2015-06-24 03:59:11 +00:00
#include "net/base/load_flags.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h"
#include "net/http/http_cache.h"
#include "net/http/http_util.h"
#include "services/network/network_service.h"
#include "services/network/public/cpp/features.h"
2020-05-19 17:18:12 +00:00
#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/api/electron_api_cookies.h"
#include "shell/browser/api/electron_api_data_pipe_holder.h"
#include "shell/browser/api/electron_api_download_item.h"
#include "shell/browser/api/electron_api_net_log.h"
#include "shell/browser/api/electron_api_protocol.h"
#include "shell/browser/api/electron_api_service_worker_context.h"
#include "shell/browser/api/electron_api_web_request.h"
#include "shell/browser/browser.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/media/media_device_id_salt.h"
#include "shell/browser/net/cert_verifier_client.h"
#include "shell/browser/session_preferences.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "ui/base/l10n/l10n_util.h"
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/extension_registry.h"
#include "shell/browser/extensions/electron_extension_system.h"
#include "shell/common/gin_converters/extension_converter.h"
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck
#include "chrome/browser/spellchecker/spellcheck_service.h" // nogncheck
#include "components/spellcheck/browser/pref_names.h"
#include "components/spellcheck/common/spellcheck_common.h"
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
#include "components/spellcheck/browser/spellcheck_platform.h"
#include "components/spellcheck/common/spellcheck_features.h"
#endif
#endif
using content::BrowserThread;
using content::StoragePartition;
chore: bump chromium to f30828899e4cd7161f6dc6507023f (master) (#20824) * chore: bump chromium in DEPS to 0476932294da8809a19189b9f54cee11d50cc512 * update chromium patches (#20838) * chore: bump chromium in DEPS to 838863f5ec9e8a12132a10bb47be8382ad9756a7 * IsRendererTransferNeededForNavigation went away https://chromium-review.googlesource.com/c/chromium/src/+/1867031 * [arraybuffer] Move the ArrayBuffer implementation from wtf to core https://chromium-review.googlesource.com/c/chromium/src/+/1875731 * URLLoaderRequest new mojo types * context menu enums moved around https://chromium-review.googlesource.com/c/chromium/src/+/1872004 https://chromium-review.googlesource.com/c/chromium/src/+/1876088 https://chromium-review.googlesource.com/c/chromium/src/+/1866520 * chore: bump chromium in DEPS to dc9525d251bf30828899e4cd7161f6dc6507023f * update chromium patches * [WIP] Convert network hints IPC to Mojo https://chromium-review.googlesource.com/c/chromium/src/+/1881967 * jumbo build is no longer supported https://chromium-review.googlesource.com/c/chromium/src/+/1881967 * fix disable-color-correct-rendering * [FIXME] fix printing patch compiles but prob doesn't work * explicitly include ax_enums https://chromium-review.googlesource.com/c/chromium/src/+/1759821 * fixup! [WIP] Convert network hints IPC to Mojo * fix base::span * fix AsarURLLoader to not double-std::move * fix debug build * fix msstl patch * lint * more fix msstl * mooooore fix msstl * fix compile * update backport_fix_msstl_compat_in_ui_events.patch * update msstl compat patch * don't try to build chrome's prefetch predictor * build: fix compilation on windows * Fixup patches for MAS build * Free up disk space for mac debug builds * fix: apply custom site instance only for main frame * Fixup from rebase * Try not generating symbols for mac debug builds * Remove double entry of patch * FIx compile errors * Trigger CI * Set symbol_level to 1 for mac debug builds
2019-11-05 23:41:20 +00:00
namespace predictors {
// NOTE(nornagon): this is copied from
// //chrome/browser/predictors/resource_prefetch_predictor.cc we don't need
// anything in that file other than this constructor. Without it we get a link
// error. Probably upstream the constructor should be moved to
// preconnect_manager.cc.
PreconnectRequest::PreconnectRequest(
const url::Origin& origin,
chore: bump chromium to f30828899e4cd7161f6dc6507023f (master) (#20824) * chore: bump chromium in DEPS to 0476932294da8809a19189b9f54cee11d50cc512 * update chromium patches (#20838) * chore: bump chromium in DEPS to 838863f5ec9e8a12132a10bb47be8382ad9756a7 * IsRendererTransferNeededForNavigation went away https://chromium-review.googlesource.com/c/chromium/src/+/1867031 * [arraybuffer] Move the ArrayBuffer implementation from wtf to core https://chromium-review.googlesource.com/c/chromium/src/+/1875731 * URLLoaderRequest new mojo types * context menu enums moved around https://chromium-review.googlesource.com/c/chromium/src/+/1872004 https://chromium-review.googlesource.com/c/chromium/src/+/1876088 https://chromium-review.googlesource.com/c/chromium/src/+/1866520 * chore: bump chromium in DEPS to dc9525d251bf30828899e4cd7161f6dc6507023f * update chromium patches * [WIP] Convert network hints IPC to Mojo https://chromium-review.googlesource.com/c/chromium/src/+/1881967 * jumbo build is no longer supported https://chromium-review.googlesource.com/c/chromium/src/+/1881967 * fix disable-color-correct-rendering * [FIXME] fix printing patch compiles but prob doesn't work * explicitly include ax_enums https://chromium-review.googlesource.com/c/chromium/src/+/1759821 * fixup! [WIP] Convert network hints IPC to Mojo * fix base::span * fix AsarURLLoader to not double-std::move * fix debug build * fix msstl patch * lint * more fix msstl * mooooore fix msstl * fix compile * update backport_fix_msstl_compat_in_ui_events.patch * update msstl compat patch * don't try to build chrome's prefetch predictor * build: fix compilation on windows * Fixup patches for MAS build * Free up disk space for mac debug builds * fix: apply custom site instance only for main frame * Fixup from rebase * Try not generating symbols for mac debug builds * Remove double entry of patch * FIx compile errors * Trigger CI * Set symbol_level to 1 for mac debug builds
2019-11-05 23:41:20 +00:00
int num_sockets,
const net::NetworkIsolationKey& network_isolation_key)
: origin(origin),
num_sockets(num_sockets),
network_isolation_key(network_isolation_key) {
DCHECK_GE(num_sockets, 0);
}
} // namespace predictors
namespace {
struct ClearStorageDataOptions {
GURL origin;
2016-03-08 04:40:10 +00:00
uint32_t storage_types = StoragePartition::REMOVE_DATA_MASK_ALL;
uint32_t quota_types = StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL;
};
2016-03-08 04:40:10 +00:00
uint32_t GetStorageMask(const std::vector<std::string>& storage_types) {
uint32_t storage_mask = 0;
for (const auto& it : storage_types) {
2015-12-07 11:56:23 +00:00
auto type = base::ToLowerASCII(it);
if (type == "appcache")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE;
else if (type == "cookies")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES;
else if (type == "filesystem")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS;
else if (type == "indexdb")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB;
else if (type == "localstorage")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE;
else if (type == "shadercache")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE;
else if (type == "websql")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL;
else if (type == "serviceworkers")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS;
2018-04-13 17:03:16 +00:00
else if (type == "cachestorage")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE;
}
return storage_mask;
}
2016-03-08 04:40:10 +00:00
uint32_t GetQuotaMask(const std::vector<std::string>& quota_types) {
uint32_t quota_mask = 0;
for (const auto& it : quota_types) {
2015-12-07 11:56:23 +00:00
auto type = base::ToLowerASCII(it);
if (type == "temporary")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY;
else if (type == "persistent")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT;
else if (type == "syncable")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_SYNCABLE;
}
return quota_mask;
}
} // namespace
namespace gin {
2018-04-18 01:55:30 +00:00
template <>
struct Converter<ClearStorageDataOptions> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
ClearStorageDataOptions* out) {
gin_helper::Dictionary options;
if (!ConvertFromV8(isolate, val, &options))
return false;
options.Get("origin", &out->origin);
std::vector<std::string> types;
if (options.Get("storages", &types))
out->storage_types = GetStorageMask(types);
if (options.Get("quotas", &types))
out->quota_types = GetQuotaMask(types);
return true;
}
};
bool SSLProtocolVersionFromString(const std::string& version_str,
network::mojom::SSLVersion* version) {
if (version_str == switches::kSSLVersionTLSv1) {
*version = network::mojom::SSLVersion::kTLS1;
return true;
}
if (version_str == switches::kSSLVersionTLSv11) {
*version = network::mojom::SSLVersion::kTLS11;
return true;
}
if (version_str == switches::kSSLVersionTLSv12) {
*version = network::mojom::SSLVersion::kTLS12;
return true;
}
if (version_str == switches::kSSLVersionTLSv13) {
*version = network::mojom::SSLVersion::kTLS13;
return true;
}
return false;
}
template <>
struct Converter<uint16_t> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
uint16_t* out) {
auto maybe = val->IntegerValue(isolate->GetCurrentContext());
if (maybe.IsNothing())
return false;
*out = maybe.FromJust();
return true;
}
};
template <>
struct Converter<network::mojom::SSLConfigPtr> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
network::mojom::SSLConfigPtr* out) {
gin_helper::Dictionary options;
if (!ConvertFromV8(isolate, val, &options))
return false;
*out = network::mojom::SSLConfig::New();
std::string version_min_str;
if (options.Get("minVersion", &version_min_str)) {
if (!SSLProtocolVersionFromString(version_min_str, &(*out)->version_min))
return false;
}
std::string version_max_str;
if (options.Get("maxVersion", &version_max_str)) {
if (!SSLProtocolVersionFromString(version_max_str,
&(*out)->version_max) ||
(*out)->version_max < network::mojom::SSLVersion::kTLS12)
return false;
}
if (options.Has("disabledCipherSuites") &&
!options.Get("disabledCipherSuites", &(*out)->disabled_cipher_suites)) {
return false;
}
std::sort((*out)->disabled_cipher_suites.begin(),
(*out)->disabled_cipher_suites.end());
// TODO(nornagon): also support other SSLConfig properties?
return true;
}
};
} // namespace gin
namespace electron {
namespace api {
2015-06-24 03:59:11 +00:00
namespace {
const char kPersistPrefix[] = "persist:";
void DownloadIdCallback(content::DownloadManager* download_manager,
const base::FilePath& path,
const std::vector<GURL>& url_chain,
const std::string& mime_type,
int64_t offset,
int64_t length,
const std::string& last_modified,
const std::string& etag,
const base::Time& start_time,
uint32_t id) {
2016-11-24 15:16:39 +00:00
download_manager->CreateDownloadItem(
base::GenerateGUID(), id, path, path, url_chain, GURL(), GURL(), GURL(),
GURL(), base::nullopt, mime_type, mime_type, start_time, base::Time(),
etag, last_modified, offset, length, std::string(),
download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT, false, base::Time(),
false, std::vector<download::DownloadItem::ReceivedSlice>());
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
class DictionaryObserver final : public SpellcheckCustomDictionary::Observer {
private:
std::unique_ptr<gin_helper::Promise<std::set<std::string>>> promise_;
base::WeakPtr<SpellcheckService> spellcheck_;
public:
DictionaryObserver(gin_helper::Promise<std::set<std::string>> promise,
base::WeakPtr<SpellcheckService> spellcheck)
: spellcheck_(spellcheck) {
promise_ = std::make_unique<gin_helper::Promise<std::set<std::string>>>(
std::move(promise));
if (spellcheck_)
spellcheck_->GetCustomDictionary()->AddObserver(this);
}
~DictionaryObserver() {
if (spellcheck_)
spellcheck_->GetCustomDictionary()->RemoveObserver(this);
}
void OnCustomDictionaryLoaded() override {
if (spellcheck_) {
promise_->Resolve(spellcheck_->GetCustomDictionary()->GetWords());
} else {
promise_->RejectWithErrorMessage(
"Spellcheck in unexpected state: failed to load custom dictionary.");
}
delete this;
}
void OnCustomDictionaryChanged(
const SpellcheckCustomDictionary::Change& dictionary_change) override {
// noop
}
};
#endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
2020-05-19 17:18:12 +00:00
struct UserDataLink : base::SupportsUserData::Data {
explicit UserDataLink(Session* ses) : session(ses) {}
Session* session;
};
const void* kElectronApiSessionKey = &kElectronApiSessionKey;
2015-06-24 03:59:11 +00:00
} // namespace
2020-05-19 17:18:12 +00:00
gin::WrapperInfo Session::kWrapperInfo = {gin::kEmbedderNativeGin};
Session::Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context)
: isolate_(isolate),
network_emulation_token_(base::UnguessableToken::Create()),
browser_context_(browser_context) {
// Observe DownloadManager to get download notifications.
2018-04-18 01:55:30 +00:00
content::BrowserContext::GetDownloadManager(browser_context)
->AddObserver(this);
2016-04-25 01:17:54 +00:00
new SessionPreferences(browser_context);
protocol_.Reset(isolate, Protocol::Create(isolate, browser_context).ToV8());
2020-05-19 17:18:12 +00:00
browser_context->SetUserData(kElectronApiSessionKey,
std::make_unique<UserDataLink>(this));
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (service) {
service->SetHunspellObserver(this);
}
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ExtensionRegistry::Get(browser_context)->AddObserver(this);
#endif
}
Session::~Session() {
2018-04-18 01:55:30 +00:00
content::BrowserContext::GetDownloadManager(browser_context())
->RemoveObserver(this);
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (service) {
service->SetHunspellObserver(nullptr);
}
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ExtensionRegistry::Get(browser_context())->RemoveObserver(this);
#endif
}
void Session::OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) {
if (item->IsSavePackageDownload())
2015-10-14 04:41:31 +00:00
return;
2016-04-25 01:17:54 +00:00
v8::Locker locker(isolate_);
v8::HandleScope handle_scope(isolate_);
auto handle = DownloadItem::FromOrCreate(isolate_, item);
if (item->GetState() == download::DownloadItem::INTERRUPTED)
handle->SetSavePath(item->GetTargetFilePath());
content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
bool prevent_default = Emit("will-download", handle, web_contents);
if (prevent_default) {
item->Cancel(true);
item->Remove();
}
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
void Session::OnHunspellDictionaryInitialized(const std::string& language) {
Emit("spellcheck-dictionary-initialized", language);
}
void Session::OnHunspellDictionaryDownloadBegin(const std::string& language) {
Emit("spellcheck-dictionary-download-begin", language);
}
void Session::OnHunspellDictionaryDownloadSuccess(const std::string& language) {
Emit("spellcheck-dictionary-download-success", language);
}
void Session::OnHunspellDictionaryDownloadFailure(const std::string& language) {
Emit("spellcheck-dictionary-download-failure", language);
}
#endif
2020-05-19 17:18:12 +00:00
v8::Local<v8::Promise> Session::ResolveProxy(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<std::string> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
GURL url;
args->GetNext(&url);
browser_context_->GetResolveProxyHelper()->ResolveProxy(
url, base::BindOnce(gin_helper::Promise<std::string>::ResolvePromise,
std::move(promise)));
return handle;
2015-06-24 03:59:11 +00:00
}
v8::Local<v8::Promise> Session::GetCacheSize() {
gin_helper::Promise<int64_t> promise(isolate_);
auto handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext()
->ComputeHttpCacheSize(
base::Time(), base::Time::Max(),
base::BindOnce(
[](gin_helper::Promise<int64_t> promise, bool is_upper_bound,
int64_t size_or_error) {
if (size_or_error < 0) {
promise.RejectWithErrorMessage(
net::ErrorToString(size_or_error));
} else {
promise.Resolve(size_or_error);
}
},
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearCache() {
gin_helper::Promise<void> promise(isolate_);
auto handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext()
->ClearHttpCache(base::Time(), base::Time::Max(), nullptr,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
2020-05-19 17:18:12 +00:00
v8::Local<v8::Promise> Session::ClearStorageData(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ClearStorageDataOptions options;
args->GetNext(&options);
auto* storage_partition =
content::BrowserContext::GetStoragePartition(browser_context(), nullptr);
if (options.storage_types & StoragePartition::REMOVE_DATA_MASK_COOKIES) {
// Reset media device id salt when cookies are cleared.
// https://w3c.github.io/mediacapture-main/#dom-mediadeviceinfo-deviceid
MediaDeviceIDSalt::Reset(browser_context()->prefs());
}
storage_partition->ClearData(
options.storage_types, options.quota_types, options.origin, base::Time(),
base::Time::Max(),
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
2016-01-12 15:28:12 +00:00
void Session::FlushStorageData() {
auto* storage_partition =
2016-01-12 15:28:12 +00:00
content::BrowserContext::GetStoragePartition(browser_context(), nullptr);
storage_partition->Flush();
}
2020-05-19 17:18:12 +00:00
v8::Local<v8::Promise> Session::SetProxy(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
gin_helper::Dictionary options;
args->GetNext(&options);
if (!browser_context_->in_memory_pref_store()) {
promise.Resolve();
return handle;
}
std::string mode, proxy_rules, bypass_list, pac_url;
options.Get("pacScript", &pac_url);
options.Get("proxyRules", &proxy_rules);
options.Get("proxyBypassRules", &bypass_list);
ProxyPrefs::ProxyMode proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS;
if (!options.Get("mode", &mode)) {
// pacScript takes precedence over proxyRules.
if (!pac_url.empty()) {
proxy_mode = ProxyPrefs::MODE_PAC_SCRIPT;
} else {
proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS;
}
} else {
if (!ProxyPrefs::StringToProxyMode(mode, &proxy_mode)) {
promise.RejectWithErrorMessage(
"Invalid mode, must be one of direct, auto_detect, pac_script, "
"fixed_servers or system");
return handle;
}
}
std::unique_ptr<base::Value> proxy_config;
if (proxy_mode == ProxyPrefs::MODE_DIRECT) {
proxy_config =
std::make_unique<base::Value>(ProxyConfigDictionary::CreateDirect());
} else if (proxy_mode == ProxyPrefs::MODE_SYSTEM) {
proxy_config =
std::make_unique<base::Value>(ProxyConfigDictionary::CreateSystem());
} else if (proxy_mode == ProxyPrefs::MODE_AUTO_DETECT) {
proxy_config = std::make_unique<base::Value>(
ProxyConfigDictionary::CreateAutoDetect());
} else if (proxy_mode == ProxyPrefs::MODE_PAC_SCRIPT) {
proxy_config =
std::make_unique<base::Value>(ProxyConfigDictionary::CreatePacScript(
pac_url, true /* pac_mandatory */));
} else {
proxy_config = std::make_unique<base::Value>(
ProxyConfigDictionary::CreateFixedServers(proxy_rules, bypass_list));
}
browser_context_->in_memory_pref_store()->SetValue(
proxy_config::prefs::kProxy, std::move(proxy_config),
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
2015-07-16 14:36:48 +00:00
}
v8::Local<v8::Promise> Session::ForceReloadProxyConfig() {
gin_helper::Promise<void> promise(isolate_);
auto handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext()
->ForceReloadProxyConfig(base::BindOnce(
gin_helper::Promise<void>::ResolvePromise, std::move(promise)));
return handle;
}
2015-07-30 02:38:04 +00:00
void Session::SetDownloadPath(const base::FilePath& path) {
2018-04-18 01:55:30 +00:00
browser_context_->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory,
path);
2015-07-26 08:30:02 +00:00
}
void Session::EnableNetworkEmulation(const gin_helper::Dictionary& options) {
auto conditions = network::mojom::NetworkConditions::New();
options.Get("offline", &conditions->offline);
options.Get("downloadThroughput", &conditions->download_throughput);
options.Get("uploadThroughput", &conditions->upload_throughput);
double latency = 0.0;
if (options.Get("latency", &latency) && latency) {
conditions->latency = base::TimeDelta::FromMillisecondsD(latency);
}
auto* network_context =
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext();
network_context->SetNetworkConditions(network_emulation_token_,
std::move(conditions));
}
void Session::DisableNetworkEmulation() {
auto* network_context =
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext();
network_context->SetNetworkConditions(
network_emulation_token_, network::mojom::NetworkConditions::New());
}
2015-11-18 03:45:15 +00:00
void Session::SetCertVerifyProc(v8::Local<v8::Value> val,
2020-05-19 17:18:12 +00:00
gin::Arguments* args) {
CertVerifierClient::CertVerifyProc proc;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &proc))) {
2020-05-19 17:18:12 +00:00
args->ThrowTypeError("Must pass null or function");
2015-11-18 03:17:08 +00:00
return;
}
mojo::PendingRemote<network::mojom::CertVerifierClient>
cert_verifier_client_remote;
if (proc) {
mojo::MakeSelfOwnedReceiver(
std::make_unique<CertVerifierClient>(proc),
cert_verifier_client_remote.InitWithNewPipeAndPassReceiver());
}
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext()
->SetCertVerifierClient(std::move(cert_verifier_client_remote));
2015-11-18 03:17:08 +00:00
}
void Session::SetPermissionRequestHandler(v8::Local<v8::Value> val,
2020-05-19 17:18:12 +00:00
gin::Arguments* args) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
if (val->IsNull()) {
permission_manager->SetPermissionRequestHandler(
ElectronPermissionManager::RequestHandler());
return;
}
auto handler = std::make_unique<ElectronPermissionManager::RequestHandler>();
if (!gin::ConvertFromV8(args->isolate(), val, handler.get())) {
2020-05-19 17:18:12 +00:00
args->ThrowTypeError("Must pass null or function");
return;
}
permission_manager->SetPermissionRequestHandler(base::BindRepeating(
[](ElectronPermissionManager::RequestHandler* handler,
content::WebContents* web_contents,
content::PermissionType permission_type,
ElectronPermissionManager::StatusCallback callback,
const base::Value& details) {
handler->Run(web_contents, permission_type,
base::AdaptCallbackForRepeating(std::move(callback)),
details);
},
base::Owned(std::move(handler))));
}
void Session::SetPermissionCheckHandler(v8::Local<v8::Value> val,
2020-05-19 17:18:12 +00:00
gin::Arguments* args) {
ElectronPermissionManager::CheckHandler handler;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) {
2020-05-19 17:18:12 +00:00
args->ThrowTypeError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetPermissionCheckHandler(handler);
}
2020-05-19 17:18:12 +00:00
v8::Local<v8::Promise> Session::ClearHostResolverCache(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext()
->ClearHostCache(nullptr,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearAuthCache() {
gin_helper::Promise<void> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext()
->ClearHttpAuthCache(
chore: bump chromium to ec5bc1743792d64724693eb357083 (master) (#24984) * chore: bump chromium in DEPS to cbdeef954dfc34e94c8ca9cf72ad326b4a121158 * chore: bump chromium in DEPS to 29723f905baeab1d4228eef2c31cdb341ebeffe0 * chore: bump chromium in DEPS to 44d6d78e852137fff58c14ed26ab1e803e5bf822 * update patches * chore: bump chromium in DEPS to 8a3a0fccb39d6b8334c9a0496c0d5056e50cdb3f * chore: update patches * refactor: fix PrintBackend::CreateInstance() calls Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2354541 * chore: bump chromium in DEPS to b9ebec3bcb1cabdd1426f367636f54cc98e0500e * chore: remove patches to code that was deleted upstream CL: https://chromium-review.googlesource.com/c/chromium/src/+/2360314 * Remove uses of kCGColorSpaceITUR_2020_PQ_EOTF/HLG CL: https://chromium-review.googlesource.com/c/chromium/src/+/2363950 just garden variety code shear * chore: update patch indices * Move ColorModel to //printing/mojom/print.mojom https://chromium-review.googlesource.com/c/chromium/src/+/2355083 sync with printing ColorModel changes: moved to mojo, different naming scheme * chore: bump chromium in DEPS to 56c4b4d2ce5ba941acd2e0fdb5100e8a48847134 * chore: bump chromium in DEPS to 130501f220b684a79dc82c17e236e63ac1f2a093 * Convert PrintHostMsg_DidGetPrintedPagesCount to Mojo https://chromium-review.googlesource.com/c/chromium/src/+/2326857 Update argument list to Print() * chore: update patch indices * DumpAccTree: convert utf16 to utf8 in PropertyFilter https://chromium-review.googlesource.com/c/chromium/src/+/2360218 * chore: bump chromium in DEPS to 3058368c6646e0dc8be6f8ea838b0343428b7998 * chore: bump chromium in DEPS to f51b4e6555364363c61438dac7afd988c8347bfc * chore: bump chromium in DEPS to 2dcc6f8fc23ac41b2499eb69dee0b4017e9d1046 * update patches * chore: bump chromium in DEPS to 2d8e98ecedc7e4905540b053bc1c87e964715be5 * update patches * 2345900: Move content::RecordContentToVisibleTimeRequest struct to mojo https://chromium-review.googlesource.com/c/chromium/src/+/2345900 * update patches * 2345900: Move content::RecordContentToVisibleTimeRequest struct to mojo https://chromium-review.googlesource.com/c/chromium/src/+/2345900 * 2367394: Remove net::LOAD_DO_NOT_SEND_COOKIES and net::LOAD_DO_NOT_SEND_AUTH_DATA. https://chromium-review.googlesource.com/c/chromium/src/+/2367394 * 2373227: [XProto] Consolidate all <X11/*> includes to //ui/gfx/x/x11.h https://chromium-review.googlesource.com/c/chromium/src/+/2373227 * fixup! 2373227: [XProto] Consolidate all <X11/*> includes to //ui/gfx/x/x11.h * chore: bump chromium in DEPS to c090e3f960520cbd2328608b97f87238c76d6143 * update patches * chore: bump chromium in DEPS to 13a25e0a755de9a14271022c595f3d2e29829e1a * chore: bump chromium in DEPS to 6adbb767b012c41efaeab0d1bdbb3eefed0977bc * chore: bump chromium in DEPS to 339ec5455c5932ef1322ea9953a6349b0732199e * chore: bump chromium in DEPS to 20291807c33f7ef4ef4f57d62075e099b027bfe6 * chore: bump chromium in DEPS to 226fbd1b8b17d4ac84fdb9548ef3a1c646878d47 * update patches * fixup disable_color_correct_rendering patch * chore: bump chromium in DEPS to 577c45979cad4359f2e206d68efd9317d3d79315 * update patches * viz: Rename RenderPass to CompositorRenderPass (and related types). https://chromium-review.googlesource.com/c/chromium/src/+/2380730 * chore: bump chromium in DEPS to 37e2ad5303f2c03a1b5d8eda65341bf2561196cd * update patches * add kOmitCookies_Electron * update patch * chore: bump chromium in DEPS to 256e42409ea63a7e71016de07818a983a97db463 * update patches * fix worker script ready hook https://chromium-review.googlesource.com/c/chromium/src/+/2335713 * Fixup printing page ranges patch * [printing] Move PrintMsg_PrintPages_Params to print.mojom https://chromium-review.googlesource.com/c/chromium/src/+/2340854 * Add MIME sniffer overloads that take base::StringPieces https://chromium-review.googlesource.com/c/chromium/src/+/2382896 * [printing] Move PrintHostMsg_PreviewIds to print.mojom https://chromium-review.googlesource.com/c/chromium/src/+/2379455 * fixup test due to new DCHECK https://chromium-review.googlesource.com/c/chromium/src/+/2333750 * stop sending cookies when useSessionCookies is false * chore: bump chromium in DEPS to dd429dbc556449951ee8160d8a4d61fd95a139d5 * update patches * chore: bump chromium in DEPS to 5202bde3f9f44c2065f5dacf27e7000dd19e4e4d * chore: bump chromium in DEPS to 099e8e07b89da65932431bb0fd51b6f7f5344c19 * chore: bump chromium in DEPS to 104e5da2a43b759732d5b94bfc750b3a9a639653 * chore: bump chromium in DEPS to a4519ce657af25834e355315fd7fefa77b13426a * update patches * Make FileURLLoaderFactory always owned by its |receivers_|. https://chromium-review.googlesource.com/c/chromium/src/+/2337411 * Make FileURLLoaderFactory always owned by its |receivers_|. https://chromium-review.googlesource.com/c/chromium/src/+/2337411 * chore: bump chromium in DEPS to 1b62e9e8c8eaf6b8e3a9c77ee67a4c1bfa6a4d6b * chore: update patches * fixup! Make FileURLLoaderFactory always owned by its |receivers_|. * chore: update patches - mac: Disable CoreServices _CSCheckFix. https://chromium-review.googlesource.com/c/chromium/src/+/2401334 - [XProto] Remove bad DCHECK in x11_error_tracker.cc https://chromium-review.googlesource.com/c/chromium/src/+/2402304 - Move content/browser/frame_host/* over to content/browser/renderer_host/ https://chromium-review.googlesource.com/c/chromium/src/+/2401303 * Refactor WebContentSettingsClient to dedupe AllowXYZ methods https://chromium-review.googlesource.com/c/chromium/src/+/2353552 * Introduce NonNetworkURLLoaderFactoryBase class. https://chromium-review.googlesource.com/c/chromium/src/+/2357559 * [XProto] Remove usage of all Xlib headers https://chromium-review.googlesource.com/c/chromium/src/+/2392140 * fixup! chore: update patches * chore: bump chromium in DEPS to c1df55fbeb8207d036a604f59e4ea4e8ee79930a * chore: update patches * Move content::WebPreferences struct to Blink https://chromium-review.googlesource.com/c/chromium/src/+/2397670 * chore: bump chromium in DEPS to 57a23ec4884fff6c2f8d9b8536131cdc9b551ec2 * Set appid on Pip windows. https://chromium-review.googlesource.com/c/chromium/src/+/2388274 * fixup! Set appid on Pip windows. * fix: add a patch to remove deprecated factory * chore: bump chromium in DEPS to 1a9ddb7ea43955877823d5c4dcbf241b64228635 * fix compilation on windows * chore: bump chromium in DEPS to 234e6c6a77f61ffad9335099d9b13892cf88fd44 * chore: update patches * chore: bump chromium in DEPS to 7631eb0a9f57a8a47d3c28e1d265961b3a4d6b2b * chore: update patches * chore: bump chromium in DEPS to f9c34cd485845b95c2d17a7f55fdf92cda9a1b3a * chore: update patches * chore: implement GetSurveyAPIKey Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2362182 * chore: replace CreateWebUIURLLoader with CreateWebUIURLLoaderFactory Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2358309 * chore: bump chromium in DEPS to 5bdbd2373da884adf41c087be1465fcc344d168c * chore: update node patches for common.gypi * chore: update patches * chore: non_network_url_loader_factory_base was moved Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2357431 * 2415752: Reland "Reland "OOR-CORS: Remove BlinkCORS supporting code outside Blink"" Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2415752 * chore: bump chromium in DEPS to b943d006a33ec5bc1743792d64724693eb357083 * fix: replace x11::None with x11::Window::None * chore: update patches * chore: update patches * fix: cast x11::Window to int * 2402123: Use end date when deleting http auth cache Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2402123 * 2320268: Migrate DragHostMsg_StartDragging to Mojo Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2320268 * 2401303: Move content/browser/frame_host/* over to content/browser/renderer_host/ https://chromium-review.googlesource.com/c/chromium/src/+/2401303 * chore: fix lint * chore: fix build * Update config.yml Co-authored-by: Electron Bot <anonymous@electronjs.org> Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: Jeremy Rose <nornagon@nornagon.net> Co-authored-by: John Kleinschmidt <jkleinsc@github.com> Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com> Co-authored-by: Samuel Attard <sattard@slack-corp.com>
2020-09-21 08:00:36 +00:00
base::Time(), base::Time::Max(),
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
2016-11-30 16:35:15 +00:00
return handle;
2016-11-30 16:35:15 +00:00
}
void Session::AllowNTLMCredentialsForDomains(const std::string& domains) {
auto* command_line = base::CommandLine::ForCurrentProcess();
network::mojom::HttpAuthDynamicParamsPtr auth_dynamic_params =
network::mojom::HttpAuthDynamicParams::New();
auth_dynamic_params->server_allowlist = domains;
auth_dynamic_params->enable_negotiate_port =
command_line->HasSwitch(electron::switches::kEnableAuthNegotiatePort);
auth_dynamic_params->ntlm_v2_enabled =
!command_line->HasSwitch(electron::switches::kDisableNTLMv2);
content::GetNetworkService()->ConfigureHttpAuthPrefs(
std::move(auth_dynamic_params));
}
void Session::SetUserAgent(const std::string& user_agent,
2020-05-19 17:18:12 +00:00
gin::Arguments* args) {
browser_context_->SetUserAgent(user_agent);
auto* network_context =
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext();
network_context->SetUserAgent(user_agent);
std::string accept_lang;
if (args->GetNext(&accept_lang)) {
network_context->SetAcceptLanguage(
net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang));
}
}
std::string Session::GetUserAgent() {
return browser_context_->GetUserAgent();
}
void Session::SetSSLConfig(network::mojom::SSLConfigPtr config) {
browser_context_->SetSSLConfig(std::move(config));
}
bool Session::IsPersistent() {
return !browser_context_->IsOffTheRecord();
}
v8::Local<v8::Promise> Session::GetBlobData(v8::Isolate* isolate,
const std::string& uuid) {
gin::Handle<DataPipeHolder> holder = DataPipeHolder::From(isolate, uuid);
if (holder.IsEmpty()) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
promise.RejectWithErrorMessage("Could not get blob data handle");
return promise.GetHandle();
}
return holder->ReadAll(isolate);
}
void Session::DownloadURL(const GURL& url) {
auto* download_manager =
content::BrowserContext::GetDownloadManager(browser_context());
auto download_params = std::make_unique<download::DownloadUrlParameters>(
url, MISSING_TRAFFIC_ANNOTATION);
download_manager->DownloadUrl(std::move(download_params));
}
void Session::CreateInterruptedDownload(const gin_helper::Dictionary& options) {
int64_t offset = 0, length = 0;
double start_time = base::Time::Now().ToDoubleT();
std::string mime_type, last_modified, etag;
base::FilePath path;
std::vector<GURL> url_chain;
options.Get("path", &path);
options.Get("urlChain", &url_chain);
options.Get("mimeType", &mime_type);
options.Get("offset", &offset);
options.Get("length", &length);
options.Get("lastModified", &last_modified);
options.Get("eTag", &etag);
options.Get("startTime", &start_time);
2016-12-07 07:28:53 +00:00
if (path.empty() || url_chain.empty() || length == 0) {
isolate_->ThrowException(v8::Exception::Error(gin::StringToV8(
isolate_, "Must pass non-empty path, urlChain and length.")));
return;
2016-12-07 07:28:53 +00:00
}
if (offset >= length) {
isolate_->ThrowException(v8::Exception::Error(gin::StringToV8(
isolate_, "Must pass an offset value less than length.")));
2016-12-07 07:28:53 +00:00
return;
}
auto* download_manager =
content::BrowserContext::GetDownloadManager(browser_context());
2020-04-03 00:22:46 +00:00
download_manager->GetNextId(base::BindRepeating(
&DownloadIdCallback, download_manager, path, url_chain, mime_type, offset,
length, last_modified, etag, base::Time::FromDoubleT(start_time)));
}
void Session::SetPreloads(const std::vector<base::FilePath>& preloads) {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
prefs->set_preloads(preloads);
}
2017-12-05 02:50:06 +00:00
std::vector<base::FilePath> Session::GetPreloads() const {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
return prefs->preloads();
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
v8::Local<v8::Promise> Session::LoadExtension(
const base::FilePath& extension_path,
gin::Arguments* args) {
gin_helper::Promise<const extensions::Extension*> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!extension_path.IsAbsolute()) {
promise.RejectWithErrorMessage(
"The path to the extension in 'loadExtension' must be absolute");
return handle;
}
if (browser_context()->IsOffTheRecord()) {
promise.RejectWithErrorMessage(
"Extensions cannot be loaded in a temporary session");
return handle;
}
int load_flags = extensions::Extension::FOLLOW_SYMLINKS_ANYWHERE;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
bool allowFileAccess = false;
options.Get("allowFileAccess", &allowFileAccess);
if (allowFileAccess)
load_flags |= extensions::Extension::ALLOW_FILE_ACCESS;
}
auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>(
extensions::ExtensionSystem::Get(browser_context()));
extension_system->LoadExtension(
extension_path, load_flags,
base::BindOnce(
[](gin_helper::Promise<const extensions::Extension*> promise,
const extensions::Extension* extension,
const std::string& error_msg) {
if (extension) {
if (!error_msg.empty()) {
node::Environment* env =
node::Environment::GetCurrent(promise.isolate());
EmitWarning(env, error_msg, "ExtensionLoadWarning");
}
promise.Resolve(extension);
} else {
promise.RejectWithErrorMessage(error_msg);
}
},
std::move(promise)));
return handle;
}
void Session::RemoveExtension(const std::string& extension_id) {
auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>(
extensions::ExtensionSystem::Get(browser_context()));
extension_system->RemoveExtension(extension_id);
}
v8::Local<v8::Value> Session::GetExtension(const std::string& extension_id) {
auto* registry = extensions::ExtensionRegistry::Get(browser_context());
const extensions::Extension* extension =
registry->GetInstalledExtension(extension_id);
if (extension) {
return gin::ConvertToV8(isolate_, extension);
} else {
return v8::Null(isolate_);
}
}
v8::Local<v8::Value> Session::GetAllExtensions() {
auto* registry = extensions::ExtensionRegistry::Get(browser_context());
auto installed_extensions = registry->GenerateInstalledExtensionsSet();
std::vector<const extensions::Extension*> extensions_vector;
for (const auto& extension : *installed_extensions) {
2020-02-13 00:39:12 +00:00
if (extension->location() != extensions::Manifest::COMPONENT)
extensions_vector.emplace_back(extension.get());
}
return gin::ConvertToV8(isolate_, extensions_vector);
}
void Session::OnExtensionLoaded(content::BrowserContext* browser_context,
const extensions::Extension* extension) {
Emit("extension-loaded", extension);
}
void Session::OnExtensionUnloaded(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason reason) {
Emit("extension-unloaded", extension);
}
void Session::OnExtensionReady(content::BrowserContext* browser_context,
const extensions::Extension* extension) {
Emit("extension-ready", extension);
}
#endif
v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) {
if (cookies_.IsEmpty()) {
auto handle = Cookies::Create(isolate, browser_context());
cookies_.Reset(isolate, handle.ToV8());
}
2020-03-26 17:34:32 +00:00
return cookies_.Get(isolate);
}
v8::Local<v8::Value> Session::Protocol(v8::Isolate* isolate) {
2020-03-26 17:34:32 +00:00
return protocol_.Get(isolate);
}
v8::Local<v8::Value> Session::ServiceWorkerContext(v8::Isolate* isolate) {
if (service_worker_context_.IsEmpty()) {
v8::Local<v8::Value> handle;
handle = ServiceWorkerContext::Create(isolate, browser_context()).ToV8();
service_worker_context_.Reset(isolate, handle);
}
2020-03-26 17:34:32 +00:00
return service_worker_context_.Get(isolate);
}
2015-12-01 04:52:22 +00:00
v8::Local<v8::Value> Session::WebRequest(v8::Isolate* isolate) {
if (web_request_.IsEmpty()) {
auto handle = WebRequest::Create(isolate, browser_context());
web_request_.Reset(isolate, handle.ToV8());
2015-12-01 04:52:22 +00:00
}
2020-03-26 17:34:32 +00:00
return web_request_.Get(isolate);
2015-12-01 04:52:22 +00:00
}
v8::Local<v8::Value> Session::NetLog(v8::Isolate* isolate) {
if (net_log_.IsEmpty()) {
2020-03-26 17:34:32 +00:00
auto handle = NetLog::Create(isolate, browser_context());
net_log_.Reset(isolate, handle.ToV8());
}
2020-03-26 17:34:32 +00:00
return net_log_.Get(isolate);
}
static void StartPreconnectOnUI(ElectronBrowserContext* browser_context,
const GURL& url,
int num_sockets_to_preconnect) {
std::vector<predictors::PreconnectRequest> requests = {
{url::Origin::Create(url), num_sockets_to_preconnect,
net::NetworkIsolationKey()}};
browser_context->GetPreconnectManager()->Start(url, requests);
}
void Session::Preconnect(const gin_helper::Dictionary& options,
2020-05-19 17:18:12 +00:00
gin::Arguments* args) {
GURL url;
if (!options.Get("url", &url) || !url.is_valid()) {
2020-05-19 17:18:12 +00:00
args->ThrowTypeError(
"Must pass non-empty valid url to session.preconnect.");
return;
}
int num_sockets_to_preconnect = 1;
if (options.Get("numSockets", &num_sockets_to_preconnect)) {
const int kMinSocketsToPreconnect = 1;
const int kMaxSocketsToPreconnect = 6;
if (num_sockets_to_preconnect < kMinSocketsToPreconnect ||
num_sockets_to_preconnect > kMaxSocketsToPreconnect) {
2020-05-19 17:18:12 +00:00
args->ThrowTypeError(
base::StringPrintf("numSocketsToPreconnect is outside range [%d,%d]",
kMinSocketsToPreconnect, kMaxSocketsToPreconnect));
return;
}
}
DCHECK_GT(num_sockets_to_preconnect, 0);
base::PostTask(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&StartPreconnectOnUI, base::Unretained(browser_context_),
url, num_sockets_to_preconnect));
}
v8::Local<v8::Promise> Session::CloseAllConnections() {
gin_helper::Promise<void> promise(isolate_);
auto handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext()
->CloseAllConnections(base::BindOnce(
gin_helper::Promise<void>::ResolvePromise, std::move(promise)));
return handle;
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
base::Value Session::GetSpellCheckerLanguages() {
return browser_context_->prefs()
->Get(spellcheck::prefs::kSpellCheckDictionaries)
->Clone();
}
void Session::SetSpellCheckerLanguages(
gin_helper::ErrorThrower thrower,
const std::vector<std::string>& languages) {
base::ListValue language_codes;
for (const std::string& lang : languages) {
std::string code = spellcheck::GetCorrespondingSpellCheckLanguage(lang);
if (code.empty()) {
thrower.ThrowError("Invalid language code provided: \"" + lang +
"\" is not a valid language code");
return;
}
language_codes.AppendString(code);
}
browser_context_->prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries,
language_codes);
// Enable spellcheck if > 0 languages, disable if no languages set
browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable,
!languages.empty());
}
void SetSpellCheckerDictionaryDownloadURL(gin_helper::ErrorThrower thrower,
const GURL& url) {
if (!url.is_valid()) {
thrower.ThrowError(
"The URL you provided to setSpellCheckerDictionaryDownloadURL is not a "
"valid URL");
return;
}
SpellcheckHunspellDictionary::SetBaseDownloadURL(url);
}
v8::Local<v8::Promise> Session::ListWordsInSpellCheckerDictionary() {
gin_helper::Promise<std::set<std::string>> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
SpellcheckService* spellcheck =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (!spellcheck) {
promise.RejectWithErrorMessage(
"Spellcheck in unexpected state: failed to load custom dictionary.");
return handle;
}
if (spellcheck->GetCustomDictionary()->IsLoaded()) {
promise.Resolve(spellcheck->GetCustomDictionary()->GetWords());
} else {
new DictionaryObserver(std::move(promise), spellcheck->GetWeakPtr());
// Dictionary loads by default asynchronously,
// call the load function anyways just to be sure.
spellcheck->GetCustomDictionary()->Load();
}
return handle;
}
bool Session::AddWordToSpellCheckerDictionary(const std::string& word) {
// don't let in-memory sessions add spellchecker words
// because files will persist unintentionally
bool is_in_memory = browser_context_->IsOffTheRecord();
if (is_in_memory)
return false;
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (!service)
return false;
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
if (spellcheck::UseBrowserSpellChecker()) {
spellcheck_platform::AddWord(service->platform_spell_checker(),
base::UTF8ToUTF16(word));
}
#endif
return service->GetCustomDictionary()->AddWord(word);
}
bool Session::RemoveWordFromSpellCheckerDictionary(const std::string& word) {
// don't let in-memory sessions remove spellchecker words
// because files will persist unintentionally
bool is_in_memory = browser_context_->IsOffTheRecord();
if (is_in_memory)
return false;
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (!service)
return false;
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
if (spellcheck::UseBrowserSpellChecker()) {
spellcheck_platform::RemoveWord(service->platform_spell_checker(),
base::UTF8ToUTF16(word));
}
#endif
return service->GetCustomDictionary()->RemoveWord(word);
}
void Session::SetSpellCheckerEnabled(bool b) {
browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable,
b);
}
bool Session::IsSpellCheckerEnabled() const {
return browser_context_->prefs()->GetBoolean(
spellcheck::prefs::kSpellCheckEnable);
}
#endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
2020-05-19 17:18:12 +00:00
// static
Session* Session::FromBrowserContext(content::BrowserContext* context) {
auto* data =
2020-05-19 17:18:12 +00:00
static_cast<UserDataLink*>(context->GetUserData(kElectronApiSessionKey));
return data ? data->session : nullptr;
}
// static
gin::Handle<Session> Session::CreateFrom(
v8::Isolate* isolate,
ElectronBrowserContext* browser_context) {
2020-05-19 17:18:12 +00:00
Session* existing = FromBrowserContext(browser_context);
2015-06-24 07:37:04 +00:00
if (existing)
2020-05-19 17:18:12 +00:00
return gin::CreateHandle(isolate, existing);
2015-06-24 07:37:04 +00:00
2018-04-18 01:55:30 +00:00
auto handle =
gin::CreateHandle(isolate, new Session(isolate, browser_context));
2016-08-01 11:11:17 +00:00
// The Sessions should never be garbage collected, since the common pattern is
// to use partition strings, instead of using the Session object directly.
2020-05-19 17:18:12 +00:00
handle->Pin(isolate);
App::Get()->EmitCustomEvent("session-created",
handle.ToV8().As<v8::Object>());
2016-08-01 11:11:17 +00:00
2015-09-01 10:02:14 +00:00
return handle;
}
// static
gin::Handle<Session> Session::FromPartition(v8::Isolate* isolate,
const std::string& partition,
base::DictionaryValue options) {
ElectronBrowserContext* browser_context;
if (partition.empty()) {
browser_context =
ElectronBrowserContext::From("", false, std::move(options));
} else if (base::StartsWith(partition, kPersistPrefix,
base::CompareCase::SENSITIVE)) {
std::string name = partition.substr(8);
browser_context =
ElectronBrowserContext::From(name, false, std::move(options));
} else {
browser_context =
ElectronBrowserContext::From(partition, true, std::move(options));
}
return CreateFrom(isolate, browser_context);
}
2020-05-19 17:18:12 +00:00
gin::ObjectTemplateBuilder Session::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin_helper::EventEmitterMixin<Session>::GetObjectTemplateBuilder(
isolate)
.SetMethod("resolveProxy", &Session::ResolveProxy)
.SetMethod("getCacheSize", &Session::GetCacheSize)
.SetMethod("clearCache", &Session::ClearCache)
.SetMethod("clearStorageData", &Session::ClearStorageData)
2016-01-12 15:28:12 +00:00
.SetMethod("flushStorageData", &Session::FlushStorageData)
.SetMethod("setProxy", &Session::SetProxy)
.SetMethod("forceReloadProxyConfig", &Session::ForceReloadProxyConfig)
.SetMethod("setDownloadPath", &Session::SetDownloadPath)
.SetMethod("enableNetworkEmulation", &Session::EnableNetworkEmulation)
.SetMethod("disableNetworkEmulation", &Session::DisableNetworkEmulation)
.SetMethod("setCertificateVerifyProc", &Session::SetCertVerifyProc)
.SetMethod("setPermissionRequestHandler",
&Session::SetPermissionRequestHandler)
.SetMethod("setPermissionCheckHandler",
&Session::SetPermissionCheckHandler)
.SetMethod("clearHostResolverCache", &Session::ClearHostResolverCache)
2016-11-30 16:35:15 +00:00
.SetMethod("clearAuthCache", &Session::ClearAuthCache)
.SetMethod("allowNTLMCredentialsForDomains",
&Session::AllowNTLMCredentialsForDomains)
.SetMethod("isPersistent", &Session::IsPersistent)
.SetMethod("setUserAgent", &Session::SetUserAgent)
.SetMethod("getUserAgent", &Session::GetUserAgent)
.SetMethod("setSSLConfig", &Session::SetSSLConfig)
.SetMethod("getBlobData", &Session::GetBlobData)
.SetMethod("downloadURL", &Session::DownloadURL)
.SetMethod("createInterruptedDownload",
&Session::CreateInterruptedDownload)
.SetMethod("setPreloads", &Session::SetPreloads)
.SetMethod("getPreloads", &Session::GetPreloads)
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
.SetMethod("loadExtension", &Session::LoadExtension)
.SetMethod("removeExtension", &Session::RemoveExtension)
.SetMethod("getExtension", &Session::GetExtension)
.SetMethod("getAllExtensions", &Session::GetAllExtensions)
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
.SetMethod("getSpellCheckerLanguages", &Session::GetSpellCheckerLanguages)
.SetMethod("setSpellCheckerLanguages", &Session::SetSpellCheckerLanguages)
.SetProperty("availableSpellCheckerLanguages",
&spellcheck::SpellCheckLanguages)
.SetMethod("setSpellCheckerDictionaryDownloadURL",
&SetSpellCheckerDictionaryDownloadURL)
.SetMethod("listWordsInSpellCheckerDictionary",
&Session::ListWordsInSpellCheckerDictionary)
.SetMethod("addWordToSpellCheckerDictionary",
&Session::AddWordToSpellCheckerDictionary)
.SetMethod("removeWordFromSpellCheckerDictionary",
&Session::RemoveWordFromSpellCheckerDictionary)
.SetMethod("setSpellCheckerEnabled", &Session::SetSpellCheckerEnabled)
.SetMethod("isSpellCheckerEnabled", &Session::IsSpellCheckerEnabled)
.SetProperty("spellCheckerEnabled", &Session::IsSpellCheckerEnabled,
&Session::SetSpellCheckerEnabled)
#endif
.SetMethod("preconnect", &Session::Preconnect)
.SetMethod("closeAllConnections", &Session::CloseAllConnections)
2015-12-01 04:52:22 +00:00
.SetProperty("cookies", &Session::Cookies)
.SetProperty("netLog", &Session::NetLog)
.SetProperty("protocol", &Session::Protocol)
.SetProperty("serviceWorkers", &Session::ServiceWorkerContext)
2015-12-01 04:52:22 +00:00
.SetProperty("webRequest", &Session::WebRequest);
}
2020-05-19 17:18:12 +00:00
const char* Session::GetTypeName() {
return "Session";
}
} // namespace api
} // namespace electron
2015-09-01 10:02:14 +00:00
namespace {
using electron::api::Cookies;
using electron::api::Protocol;
using electron::api::ServiceWorkerContext;
using electron::api::Session;
2016-08-02 11:38:35 +00:00
2018-04-18 01:55:30 +00:00
v8::Local<v8::Value> FromPartition(const std::string& partition,
2020-05-19 17:18:12 +00:00
gin::Arguments* args) {
if (!electron::Browser::Get()->is_ready()) {
2020-05-19 17:18:12 +00:00
args->ThrowTypeError("Session can only be received when app is ready");
2016-07-12 11:21:59 +00:00
return v8::Null(args->isolate());
}
2016-07-12 12:53:19 +00:00
base::DictionaryValue options;
args->GetNext(&options);
return Session::FromPartition(args->isolate(), partition, std::move(options))
.ToV8();
2016-07-12 11:21:59 +00:00
}
2018-04-18 01:55:30 +00:00
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
2015-09-01 10:02:14 +00:00
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
2016-07-12 11:21:59 +00:00
dict.SetMethod("fromPartition", &FromPartition);
2015-09-01 10:02:14 +00:00
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_session, Initialize)