Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Imported Web Store extensions become the store's own installs and stay on after a reload (#203)

Victore1bf43331fe3
diff --git a/Packages/CraCore/Sources/CraCore/WebStoreInstalls.swift b/Packages/CraCore/Sources/CraCore/WebStoreInstalls.swift
new file mode 100644
index 0000000..8f970ed
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/WebStoreInstalls.swift
@@ -0,0 +1,73 @@
+import Foundation
+
+/// Web Store extensions live in each profile as Chrome's own store installs (GitHub #203).
+///
+/// An import from Arc, Dia or Chrome copies an extension's files into Extensions/<id>, which
+/// Chromium loads with --load-extension (location 8, COMMAND_LINE). Such a copy never updates,
+/// and before Cra's CEF fix a reload (`chrome.runtime.reload()`, chrome://extensions) turned it
+/// into an UNPACKED one (location 4), which Chromium turns off without developer mode. A copy
+/// of a Web Store extension is installed again from the store in each profile it loads in, the
+/// way the store's "Add to Chrome" does (Cra.installFromWebStore): the signed CRX, location 1
+/// (INTERNAL), from the Web Store, updated by Chromium. Once a profile has that install, the
+/// folder stops loading there, and the folder goes when no profile loads it any more. A copy
+/// the store doesn't take (offline, delisted, asks for more permissions) keeps loading from
+/// the folder; the next launch asks again.
+public enum WebStoreInstalls {
+ /// The update URL the Web Store writes into every manifest it serves.
+ public static let storeUpdateURL = "https://clients2.google.com/service/update2/crx"
+
+ /// Location 1 in Chromium's extensions.settings: installed into the profile (INTERNAL).
+ public static let internalLocation = 1
+
+ /// A folder in Extensions/ that holds a Web Store extension: the store's update URL, and
+ /// the folder named after the ID its manifest key gives (as the import names it), so the
+ /// store's install is the same extension with the same data.
+ public static func isWebStoreCopy(folder: String, extensionID: String, updateURL: String?) -> Bool {
+ guard let updateURL, normalized(updateURL) == storeUpdateURL else { return false }
+ return folder == extensionID && isExtensionID(extensionID)
+ }
+
+ /// Chromium's extension IDs: 32 letters a–p.
+ public static func isExtensionID(_ id: String) -> Bool {
+ id.utf8.count == 32 && id.utf8.allSatisfy { (UInt8(ascii: "a")...UInt8(ascii: "p")).contains($0) }
+ }
+
+ /// Whether a profile's extensions.settings entry is a store install.
+ public static func isStoreInstall(settings entry: [String: Any]?) -> Bool {
+ guard let entry else { return false }
+ return (entry["location"] as? Int) == internalLocation && (entry["from_webstore"] as? Bool) == true
+ }
+
+ /// The profiles a Web Store copy in `folder` still loads in from the folder, where Chromium
+ /// has no store install of it yet, in `profiles` order.
+ public static func pendingProfiles(folder: String, extensionID: String, scopes: ExtensionProfiles,
+ profiles: [String], settings: (String) -> [String: Any]) -> [String] {
+ profiles.filter { profile in
+ scopes.loads(folder: folder, inProfile: profile)
+ && !isStoreInstall(settings: settings(profile)[extensionID] as? [String: Any])
+ }
+ }
+
+ private static func normalized(_ url: String) -> String {
+ var u = url.trimmingCharacters(in: .whitespaces)
+ if let q = u.firstIndex(of: "?") { u = String(u[..<q]) }
+ while u.hasSuffix("/") { u.removeLast() }
+ return u.replacingOccurrences(of: "http://", with: "https://")
+ }
+}
+
+extension ExtensionProfiles {
+ /// `profile` has `folder`'s extension from the Web Store now, so the folder stops loading
+ /// there; a folder without a list loaded in every one of `allProfiles`. True when it loads in
+ /// no profile any more: the folder can go (and its entry goes with it).
+ @discardableResult
+ public mutating func movedToWebStore(folder: String, profile: String, allProfiles: Set<String>) -> Bool {
+ let remaining = (profiles(ofFolder: folder) ?? allProfiles).subtracting([profile])
+ if remaining.isEmpty {
+ folders[folder] = nil
+ return true
+ }
+ folders[folder] = remaining.sorted()
+ return false
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/WebStoreInstallsTests.swift b/Packages/CraCore/Tests/CraCoreTests/WebStoreInstallsTests.swift
new file mode 100644
index 0000000..c9828c6
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/WebStoreInstallsTests.swift
@@ -0,0 +1,60 @@
+import CraCore
+import Foundation
+import Testing
+
+/// Imported Web Store extensions become the store's own installs (GitHub #203).
+struct WebStoreInstallsTests {
+ let id = "bcjindcccaagfpapjjmafapmmgkkhgoa"
+
+ @Test func onlyStoreCopiesNamedAfterTheirID() {
+ let store = WebStoreInstalls.storeUpdateURL
+ #expect(WebStoreInstalls.isWebStoreCopy(folder: id, extensionID: id, updateURL: store))
+ #expect(WebStoreInstalls.isWebStoreCopy(folder: id, extensionID: id, updateURL: store + "/"))
+ #expect(WebStoreInstalls.isWebStoreCopy(folder: id, extensionID: id, updateURL: "http://clients2.google.com/service/update2/crx"))
+ #expect(!WebStoreInstalls.isWebStoreCopy(folder: id, extensionID: id, updateURL: nil), "an unpacked extension of someone's own")
+ #expect(!WebStoreInstalls.isWebStoreCopy(folder: id, extensionID: id, updateURL: "https://example.com/updates.xml"),
+ "self-hosted updates are not the store's")
+ #expect(!WebStoreInstalls.isWebStoreCopy(folder: "my-extension", extensionID: id, updateURL: store),
+ "Add Unpacked Extension… copies keep their folder name")
+ #expect(!WebStoreInstalls.isWebStoreCopy(folder: "x", extensionID: "x", updateURL: store), "not an extension ID")
+ }
+
+ @Test func storeInstallsAreInternalFromTheWebStore() {
+ #expect(WebStoreInstalls.isStoreInstall(settings: ["location": 1, "from_webstore": true]))
+ #expect(!WebStoreInstalls.isStoreInstall(settings: ["location": 8, "from_webstore": false]), "--load-extension")
+ #expect(!WebStoreInstalls.isStoreInstall(settings: ["location": 4]), "unpacked")
+ #expect(!WebStoreInstalls.isStoreInstall(settings: ["location": 1, "from_webstore": false]), "an off-store CRX")
+ #expect(!WebStoreInstalls.isStoreInstall(settings: nil))
+ }
+
+ @Test func pendingWhereTheFolderLoadsAndTheStoreHasNotInstalledIt() {
+ let profiles = ["Default", "Profile 1", "Profile 2"]
+ let settings: [String: [String: Any]] = [
+ "Default": [id: ["location": 8]],
+ "Profile 1": [id: ["location": 1, "from_webstore": true]],
+ ]
+ let everywhere = WebStoreInstalls.pendingProfiles(folder: id, extensionID: id, scopes: ExtensionProfiles(),
+ profiles: profiles, settings: { settings[$0] ?? [:] })
+ #expect(everywhere == ["Default", "Profile 2"])
+ let scoped = WebStoreInstalls.pendingProfiles(folder: id, extensionID: id, scopes: ExtensionProfiles(folders: [id: ["Profile 1"]]),
+ profiles: profiles, settings: { settings[$0] ?? [:] })
+ #expect(scoped.isEmpty, "loads only where the store already has it")
+ }
+
+ @Test func folderStopsLoadingWhereTheStoreHasIt() {
+ var scopes = ExtensionProfiles()
+ let all: Set<String> = ["Default", "Profile 1"]
+ let goneAfterDefault = scopes.movedToWebStore(folder: id, profile: "Default", allProfiles: all)
+ #expect(!goneAfterDefault)
+ #expect(scopes.folders[id] == ["Profile 1"], "a folder that loaded everywhere keeps the other profiles")
+ #expect(scopes.commandLineValue(forFolders: [id]) == "Profile 1")
+ let goneAfterBoth = scopes.movedToWebStore(folder: id, profile: "Profile 1", allProfiles: all)
+ #expect(goneAfterBoth, "loads nowhere: the folder can go")
+ #expect(scopes.folders[id] == nil)
+
+ var listed = ExtensionProfiles(folders: [id: ["Profile 2"]])
+ let gone = listed.movedToWebStore(folder: id, profile: "Profile 2", allProfiles: all)
+ #expect(gone)
+ #expect(listed.folders.isEmpty)
+ }
+}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index f9fad60..6ec1afc 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -1065,6 +1065,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
log(id, "loaded \(site(url, id, browser)) (HTTP \(statusCode))")
if statusCode != 0 { runtimes[id]?.extensionPageRetries = 0 }
guard !browser.isIncognito else { return }
+ // The profile's extensions are up: imported Web Store copies become store installs (#203).
+ ExtensionStore.shared.installFromWebStore(using: browser, profile: store.profileDirectoryName(item: id))
if url.hasPrefix("chrome://settings") { watchClearBrowsingData(browser) }
store.recordVisit(url: url, title: title.isEmpty ? (store.item(id)?.tab?.savedTitle ?? "") : title)
}
diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swift
index 37d6e33..8fd2a61 100644
--- a/Sources/Cra/Services/ExtensionStore.swift
+++ b/Sources/Cra/Services/ExtensionStore.swift
@@ -55,6 +55,10 @@ final class ExtensionStore {
/// which profiles load each (CraCEFRuntime.setExtensionPaths).
nonisolated static func loadList() -> (paths: [String], profiles: String?) {
let fm = FileManager.default
+ // Before Chromium starts: a copy the store already installed in a profile must not load
+ // there again, or --load-extension would put the copy back over the store's install.
+ let profiles = chromiumProfiles()
+ dropWebStoreCopies(profiles: profiles) { ExtensionImporter.settings(inProfile: AppPaths.chromiumCache.appendingPathComponent($0, isDirectory: true)) }
let names = ((try? fm.contentsOfDirectory(atPath: directory.path)) ?? []).sorted()
.filter { fm.fileExists(atPath: directory.appendingPathComponent($0).appendingPathComponent("manifest.json").path) }
return (names.map { directory.appendingPathComponent($0, isDirectory: true).path }, loadProfiles().commandLineValue(forFolders: names))
@@ -97,6 +101,73 @@ final class ExtensionStore {
try fm.moveItem(at: staging, to: dest)
}
+ /// Cra's Chromium profile folders ("Default", "Profile <id>"), sorted.
+ nonisolated static func chromiumProfiles() -> [String] {
+ ((try? FileManager.default.contentsOfDirectory(atPath: AppPaths.chromiumCache.path)) ?? [])
+ .filter { $0 == "Default" || $0.hasPrefix("Profile ") }.sorted()
+ }
+
+ // MARK: Web Store installs (GitHub #203)
+
+ /// The folders in Extensions/ that hold a Web Store extension (an import from Arc, Dia or
+ /// Chrome), with their manifest.
+ nonisolated static func webStoreCopies() -> [(folder: String, manifest: [String: Any])] {
+ let names = ((try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []).sorted()
+ return names.compactMap { name in
+ let dir = directory.appendingPathComponent(name, isDirectory: true)
+ guard let data = try? Data(contentsOf: dir.appendingPathComponent("manifest.json")),
+ let m = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ WebStoreInstalls.isWebStoreCopy(folder: name, extensionID: chromiumID(key: m["key"] as? String, folder: dir),
+ updateURL: m["update_url"] as? String) else { return nil }
+ return (name, m)
+ }
+ }
+
+ /// Each profile where the store has installed a copy's extension stops loading the copy;
+ /// a copy no profile loads any more is deleted. True when anything changed.
+ @discardableResult
+ nonisolated static func dropWebStoreCopies(profiles: [String], settings: (String) -> [String: Any]) -> Bool {
+ var scopes = loadProfiles()
+ var changed = false
+ for copy in webStoreCopies() {
+ for profile in profiles where scopes.loads(folder: copy.folder, inProfile: profile)
+ && WebStoreInstalls.isStoreInstall(settings: settings(profile)[copy.folder] as? [String: Any]) {
+ changed = true
+ CraLog.note("extension \(copy.folder) is the Web Store's install in \(profile) now")
+ if scopes.movedToWebStore(folder: copy.folder, profile: profile, allProfiles: Set(profiles)) {
+ try? FileManager.default.removeItem(at: directory.appendingPathComponent(copy.folder, isDirectory: true))
+ break
+ }
+ }
+ }
+ if changed { try? saveProfiles(scopes) }
+ return changed
+ }
+
+ /// Extension IDs asked of the store in a profile this session ("<profile>/<id>"), each once.
+ @ObservationIgnored private var webStoreAsked: Set<String> = []
+
+ /// A page in `profile` has loaded, so the profile's extensions are up: its Web Store copies
+ /// are installed from the store there (Cra.installFromWebStore, the store's own install).
+ /// The store's version may not ask for more permissions than the copy the person picked.
+ func installFromWebStore(using browser: CraBrowser, profile: String) {
+ let scopes = Self.loadProfiles()
+ let live = Self.extensionSettings(inProfile: profile)
+ for copy in Self.webStoreCopies() where !webStoreAsked.contains("\(profile)/\(copy.folder)") {
+ guard !WebStoreInstalls.pendingProfiles(folder: copy.folder, extensionID: copy.folder, scopes: scopes,
+ profiles: [profile], settings: { _ in live }).isEmpty,
+ let params = try? JSONSerialization.data(withJSONObject: ["id": copy.folder, "manifest": copy.manifest]) else { continue }
+ webStoreAsked.insert("\(profile)/\(copy.folder)")
+ CraLog.note("extension \(copy.folder): installing from the Web Store in \(profile)")
+ browser.sendDevToolsMethod("Cra.installFromWebStore", params: String(decoding: params, as: UTF8.self)) { [weak self] _, error in
+ DispatchQueue.main.async {
+ if let error { CraLog.note("extension \(copy.folder): Web Store install in \(profile) failed (\(error)); it keeps loading from its folder") }
+ self?.reload()
+ }
+ }
+ }
+ }
+
// MARK: Profiles of the Extensions/ folders (GitHub #131)
nonisolated private static var profilesFile: URL { AppPaths.file("extension-profiles.json") }
@@ -127,13 +198,15 @@ final class ExtensionStore {
func reload() {
let fm = FileManager.default
try? fm.createDirectory(at: ExtensionStore.directory, withIntermediateDirectories: true)
- let names = (try? fm.contentsOfDirectory(atPath: ExtensionStore.directory.path)) ?? []
let root = AppPaths.chromiumCache
- let profiles = ((try? fm.contentsOfDirectory(atPath: root.path)) ?? []).filter { $0 == "Default" || $0.hasPrefix("Profile ") }.sorted()
+ let profiles = Self.chromiumProfiles()
let settings = Dictionary(uniqueKeysWithValues: profiles.map { ($0, Self.extensionSettings(inProfile: $0)) })
+ // A copy the store just installed (Cra.installFromWebStore) gives way to the store's install.
+ Self.dropWebStoreCopies(profiles: profiles) { settings[$0] ?? [:] }
+ let names = (try? fm.contentsOfDirectory(atPath: ExtensionStore.directory.path)) ?? []
let disabled = settings.mapValues(ExtensionImporter.disabledIDs(settings:))
let scopes = Self.loadProfiles()
- let list = names.sorted().compactMap { name -> Entry? in
+ var list = names.sorted().compactMap { name -> Entry? in
guard var entry = Self.entry(id: name, folder: ExtensionStore.directory.appendingPathComponent(name, isDirectory: true),
extensionID: nil) else { return nil }
entry.profiles = scopes.profiles(ofFolder: name)
@@ -145,8 +218,14 @@ final class ExtensionStore {
var managed: [Entry] = []
for profile in profiles {
// Turned-off ones stay listed (as off) so their pins come back with them.
- for e in ExtensionImporter.extensions(settings: settings[profile] ?? [:], inProfile: root.appendingPathComponent(profile, isDirectory: true))
- where !loaded.contains(e.id) {
+ for e in ExtensionImporter.extensions(settings: settings[profile] ?? [:], inProfile: root.appendingPathComponent(profile, isDirectory: true)) {
+ // The store's install of a copy that still loads from its folder in other profiles.
+ if loaded.contains(e.id) {
+ guard let i = list.firstIndex(where: { $0.extensionID == e.id }), list[i].profiles?.contains(profile) == false else { continue }
+ list[i].profiles?.insert(profile)
+ if !e.isEnabled { list[i].disabledProfiles.insert(profile) }
+ continue
+ }
var i = managed.firstIndex(where: { $0.extensionID == e.id })
if i == nil, var entry = Self.entry(id: e.id, folder: e.folder, extensionID: e.id) {
entry.managedByChrome = true
@@ -256,7 +335,7 @@ final class ExtensionStore {
/// Chromium's ID: the first 128 bits of SHA-256 over the manifest key (or the
/// unpacked folder's path), each hex digit mapped 0-f → a-p.
- static func chromiumID(key: String?, folder: URL) -> String {
+ nonisolated static func chromiumID(key: String?, folder: URL) -> String {
let input = key.flatMap { Data(base64Encoded: $0) } ?? Data(folder.path.utf8)
let digest = SHA256.hash(data: input).prefix(16)
let a = UInt8(ascii: "a")
diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swift
index be351ee..0308329 100644
--- a/Tests/BrowserManagerLifecycleTests.swift
+++ b/Tests/BrowserManagerLifecycleTests.swift
@@ -965,7 +965,10 @@ enum BrowserManagerLifecycleTests {
manager.browser(rt.browser, didFailLoadingURL: url, errorCode: -20)
clock.advance(by: 60)
expect(rt.browser.loads.count == ExtensionPageRetry.attempts, "after the last attempt the error page stays")
+ ExtensionStore.shared.webStoreProfiles = []
manager.browser(rt.browser, didFinishLoadingURL: url, title: "Options", statusCode: 200)
+ expect(ExtensionStore.shared.webStoreProfiles == ["Default"],
+ "a loaded page lets its profile's imported Web Store copies install from the store (#203)")
manager.browser(rt.browser, didFailLoadingURL: url, errorCode: -20)
clock.advance(by: 0.25)
expect(rt.browser.loads.count == ExtensionPageRetry.attempts + 1, "a page that loaded starts counting again")
diff --git a/Tests/BrowserManagerSupport/AppServices.swift b/Tests/BrowserManagerSupport/AppServices.swift
index 3e7b85d..efb1fca 100644
--- a/Tests/BrowserManagerSupport/AppServices.swift
+++ b/Tests/BrowserManagerSupport/AppServices.swift
@@ -56,6 +56,9 @@ enum TestRoot { case today }
var entries: [Entry] = []
func entries(inProfile name: String) -> [Entry] { entries }
func proxyLine(inProfile name: String) -> String { "not set by an extension" }
+ /// The profiles a loaded page asked for Web Store installs in (#203), in order.
+ var webStoreProfiles: [String] = []
+ func installFromWebStore(using browser: CraBrowser, profile: String) { webStoreProfiles.append(profile) }
}
enum FaviconKey { static func key(for url: String) -> String? { url } }
enum BrowsingDataClear {
diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.md
index 6fa6470..7a60aa2 100644
--- a/docs/arc-reverse-engineering.md
+++ b/docs/arc-reverse-engineering.md
@@ -1317,6 +1317,17 @@ opened from Dia ▸ Import from Another Browser… (stopped before "Begin Import
Cra copies the version folder to `<data dir>/Extensions/<id>` (location 8 in Cra's prefs);
verified: 21 of Arc's extensions load with Arc's IDs. [U] Extension storage (Local Extension
Settings) is not copied, so sign-ins inside extensions start fresh.
+- [O] Since GitHub #203 a copy of a Web Store extension (the store's `update_url`, folder named
+ after the ID its `key` gives) becomes the store's own install in each profile it loads in, as
+ Dia's `ExtensionsController` installs from the store: the first page a profile loads sends
+ `Cra.installFromWebStore` (scripts/cef-patches/freezing-vote.patch, WebstoreInstaller, the
+ signed CRX), which lands as location 1 with `from_webstore`; the copy then stops loading there
+ and is deleted once no profile loads it. The store's version may not ask for more permissions
+ than the copy. Before, a copy that reloaded itself (`chrome.runtime.reload()`) came back as
+ location 4 (UNPACKED), which Chromium turns off without developer mode
+ (DISABLE_UNSUPPORTED_DEVELOPER_EXTENSION, 1 << 24), and the reason stuck after the next launch
+ loaded it as location 8 again; extension-reload-location.patch keeps such a reload at location
+ 8 and clears that reason.
- Not reproduced: the Arc space step and the extensions step were not opened in Dia (the menu flow
goes browser → "Unlock your data" → import; the space and extension steps belong to first-run
onboarding), so their layout follows the reflection metadata and the measured browser step.
diff --git a/scripts/cef-patches/extension-reload-location.patch b/scripts/cef-patches/extension-reload-location.patch
new file mode 100644
index 0000000..ec668eb
--- /dev/null
+++ b/scripts/cef-patches/extension-reload-location.patch
@@ -0,0 +1,82 @@
+diff --git a/chrome/browser/extensions/chrome_extension_registrar_delegate.cc b/chrome/browser/extensions/chrome_extension_registrar_delegate.cc
+index 7ff5fb3095..63b6de5564 100644
+--- a/chrome/browser/extensions/chrome_extension_registrar_delegate.cc
++++ b/chrome/browser/extensions/chrome_extension_registrar_delegate.cc
+@@ -289,6 +289,12 @@ void ChromeExtensionRegistrarDelegate::DoLoadExtensionForReload(
+ unpacked_installer->set_completion_callback(base::BindOnce(
+ &ChromeExtensionRegistrarDelegate::OnUnpackedReloadFailure,
+ weak_factory_.GetWeakPtr()));
++ // Cra: prefs keep no manifest for a --load-extension extension either, so
++ // it comes here too; it reloads as what it was, not as kUnpacked.
++ if (installed_extension && installed_extension->extension_location ==
++ mojom::ManifestLocation::kCommandLine) {
++ unpacked_installer->set_location(mojom::ManifestLocation::kCommandLine);
++ }
+ unpacked_installer->Load(path);
+ }
+ }
+diff --git a/extensions/browser/unpacked_installer.cc b/extensions/browser/unpacked_installer.cc
+index c3626959e7..b2d1a88fa0 100644
+--- a/extensions/browser/unpacked_installer.cc
++++ b/extensions/browser/unpacked_installer.cc
+@@ -24,6 +24,7 @@
+ #include "content/public/browser/browser_task_traits.h"
+ #include "content/public/browser/browser_thread.h"
+ #include "extensions/browser/api/declarative_net_request/install_index_helper.h"
++#include "extensions/browser/disable_reason.h"
+ #include "extensions/browser/event_router_factory.h"
+ #include "extensions/browser/extension_file_task_runner.h"
+ #include "extensions/browser/extension_management_client.h"
+@@ -406,7 +407,7 @@ void UnpackedInstaller::CheckExtensionFileAccess() {
+
+ void UnpackedInstaller::LoadWithFileAccessOnFileThread(int flags) {
+ std::u16string error;
+- if (!LoadExtension(mojom::ManifestLocation::kUnpacked, flags, &error)) {
++ if (!LoadExtension(location_, flags, &error)) {
+ // Set priority explicitly to avoid unwanted task priority inheritance.
+ content::GetUIThreadTaskRunner({base::TaskPriority::USER_BLOCKING})
+ ->PostTask(FROM_HERE,
+@@ -445,6 +446,17 @@ void UnpackedInstaller::InstallExtension() {
+ // Force file access and/or incognito state and set install param if
+ // requested.
+ ExtensionPrefs* prefs = ExtensionPrefs::Get(browser_context_);
++ // Cra: developer mode never applies to a --load-extension extension. A
++ // reload used to turn one into kUnpacked, which got it this reason, and the
++ // reason stayed when the command line loaded it again: clear it.
++ if (extension()->location() == mojom::ManifestLocation::kCommandLine &&
++ prefs->HasDisableReason(
++ extension()->id(),
++ disable_reason::DISABLE_UNSUPPORTED_DEVELOPER_EXTENSION)) {
++ prefs->RemoveDisableReason(
++ extension()->id(),
++ disable_reason::DISABLE_UNSUPPORTED_DEVELOPER_EXTENSION);
++ }
+ if (allow_file_access_.has_value()) {
+ prefs->SetAllowFileAccess(extension()->id(), *allow_file_access_);
+ }
+diff --git a/extensions/browser/unpacked_installer.h b/extensions/browser/unpacked_installer.h
+index 723fcd2407..56ad8fa4a6 100644
+--- a/extensions/browser/unpacked_installer.h
++++ b/extensions/browser/unpacked_installer.h
+@@ -103,6 +103,11 @@ class UnpackedInstaller : public base::RefCountedThreadSafe<
+ installed_via_cdp_ = installed_via_cdp;
+ }
+
++ // Cra: the location Load() installs with. A --load-extension extension that
++ // reloads (chrome.runtime.reload(), chrome://extensions) keeps kCommandLine;
++ // as kUnpacked it would be turned off without developer mode.
++ void set_location(mojom::ManifestLocation location) { location_ = location; }
++
+ private:
+ friend struct content::BrowserThread::DeleteOnThread<
+ content::BrowserThread::UI>;
+@@ -206,6 +211,9 @@ class UnpackedInstaller : public base::RefCountedThreadSafe<
+
+ bool installed_via_cdp_ = false;
+
++ // Cra: see set_location().
++ mojom::ManifestLocation location_ = mojom::ManifestLocation::kUnpacked;
++
+ // Subscription for a callback that runs when the BrowserContext* is
+ // destroyed.
+ base::CallbackListSubscription browser_context_shutdown_subscription_;
diff --git a/scripts/cef-patches/freezing-vote.patch b/scripts/cef-patches/freezing-vote.patch
index 371af73..9827b8b 100644
--- a/scripts/cef-patches/freezing-vote.patch
+++ b/scripts/cef-patches/freezing-vote.patch
@@ -11,22 +11,26 @@ index dd0a558c0..a54f79de4 100644
"//components/pref_registry",
"//components/printing/browser",
diff --git a/cef/libcef/browser/devtools/devtools_controller.cc b/cef/libcef/browser/devtools/devtools_controller.cc
-index c60f22d..3be66a2 100644
+index c60f22d..da94ae0 100644
--- a/cef/libcef/browser/devtools/devtools_controller.cc
+++ b/cef/libcef/browser/devtools/devtools_controller.cc
-@@ -5,10 +5,268 @@
+@@ -5,10 +5,416 @@
#include "cef/libcef/browser/devtools/devtools_controller.h"
#include "base/json/json_reader.h"
+#include "base/feature_list.h"
+#include "base/functional/callback_helpers.h"
#include "base/json/json_writer.h"
++#include "base/memory/ref_counted.h"
++#include "base/strings/string_number_conversions.h"
+#include "base/supports_user_data.h"
+#include "base/task/sequenced_task_runner.h"
#include "cef/libcef/browser/devtools/devtools_util.h"
#include "cef/libcef/browser/thread_util.h"
+#include "chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.h"
+#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
++#include "chrome/browser/profiles/profile.h"
++#include "components/crx_file/id_util.h"
+#include "components/performance_manager/freezing/freezing_policy.h"
+#include "components/performance_manager/public/freezing/freezing.h"
+#include "components/performance_manager/public/performance_manager.h"
@@ -37,6 +41,11 @@ index c60f22d..3be66a2 100644
+#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/common/content_features.h"
++#include "extensions/browser/extension_registry.h"
++#include "extensions/browser/install_approval.h"
++#include "extensions/browser/webstore_installer.h"
++#include "extensions/common/extension.h"
++#include "extensions/common/mojom/manifest.mojom-shared.h"
+
+namespace {
+
@@ -181,6 +190,145 @@ index c60f22d..3be66a2 100644
+ std::string_view message,
+ int* message_id,
+ base::DictValue* result,
++ std::string* error);
++
++// A reply to a Cra.* method, in the protocol's shape. "id" comes first:
++// CEF's ProtocolParser only reads a result that starts with {"id":, and
++// JSONWriter would sort "error" ahead of it, so error replies never arrived.
++std::string CraReplyJson(int message_id,
++ base::DictValue result,
++ const std::string& error) {
++ std::string body;
++ if (error.empty()) {
++ base::JSONWriter::Write(result, &body);
++ } else {
++ base::DictValue error_dict;
++ error_dict.Set("code", -32000);
++ error_dict.Set("message", error);
++ base::JSONWriter::Write(error_dict, &body);
++ }
++ return "{\"id\":" + base::NumberToString(message_id) +
++ (error.empty() ? ",\"result\":" : ",\"error\":") + body + "}";
++}
++
++// The page that downloads the store's CRX, as WebstoreInstallWithPrompt has
++// one: never shown, so the download stays out of every window's UI. It lives
++// until the install is over.
++struct CraWebStoreInstallPage
++ : public base::RefCountedThreadSafe<CraWebStoreInstallPage> {
++ explicit CraWebStoreInstallPage(Profile* profile)
++ : contents(content::WebContents::Create(
++ content::WebContents::CreateParams(profile))) {}
++ std::unique_ptr<content::WebContents> contents;
++
++ private:
++ friend class base::RefCountedThreadSafe<CraWebStoreInstallPage>;
++ ~CraWebStoreInstallPage() = default;
++};
++
++// Cra (GitHub #203): {"id":N,"method":"Cra.installFromWebStore","params":
++// {"id":extension id,"manifest":{...}}} installs a Chrome Web Store item in
++// this page's profile the way the store's "Add to Chrome" does
++// (webstorePrivate.completeInstall): WebstoreInstaller fetches the signed CRX
++// from the store's update service and CrxInstaller checks it carries the
++// store's signature. It lands as INTERNAL and from the Web Store, updates and
++// is verified like any store install, which an unpacked copy (Arc's, Dia's,
++// Chrome's, loaded with --load-extension) never is. `manifest` is the copy
++// the person picked; the store's version may not ask for more permissions
++// (a loose check). No prompt: the client asks only for extensions the person
++// chose to bring over. Replies {"installed":true} once the extension is
++// installed, else an error; the download can take a while.
++// Returns false for any other message.
++bool StartCraWebStoreInstall(
++ content::WebContents* contents,
++ std::string_view message,
++ base::OnceCallback<void(std::string json)> send) {
++ if (message.find("\"Cra.installFromWebStore\"") == std::string_view::npos) {
++ return false;
++ }
++ std::optional<base::DictValue> dict =
++ base::JSONReader::ReadDict(message, base::JSON_PARSE_RFC);
++ if (!dict) {
++ return false;
++ }
++ const std::string* method = dict->FindString("method");
++ std::optional<int> message_id = dict->FindInt("id");
++ if (!method || !message_id || *method != "Cra.installFromWebStore") {
++ return false;
++ }
++ auto fail = [&](const std::string& error) {
++ base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
++ FROM_HERE, base::BindOnce(std::move(send),
++ CraReplyJson(*message_id, base::DictValue(),
++ error)));
++ return true;
++ };
++ const base::DictValue* params = dict->FindDict("params");
++ const std::string* id = params ? params->FindString("id") : nullptr;
++ const base::DictValue* manifest =
++ params ? params->FindDict("manifest") : nullptr;
++ if (!id || !crx_file::id_util::IdIsValid(*id) || !manifest) {
++ return fail("needs a valid extension id and its manifest");
++ }
++ Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
++ if (!profile || profile->IsOffTheRecord()) {
++ return fail("not in an off-the-record profile");
++ }
++ const extensions::Extension* installed =
++ extensions::ExtensionRegistry::Get(profile)->GetInstalledExtension(*id);
++ if (installed &&
++ installed->location() == extensions::mojom::ManifestLocation::kInternal &&
++ installed->from_webstore()) {
++ base::DictValue result;
++ result.Set("installed", true);
++ result.Set("already", true);
++ base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
++ FROM_HERE, base::BindOnce(std::move(send),
++ CraReplyJson(*message_id, std::move(result),
++ std::string())));
++ return true;
++ }
++ std::unique_ptr<extensions::InstallApproval> approval =
++ extensions::InstallApproval::CreateWithNoInstallPrompt(
++ profile, *id, manifest->Clone(), /*strict_manifest_check=*/false);
++ approval->skip_post_install_ui = true;
++ approval->use_app_installed_bubble = false;
++ auto page = base::MakeRefCounted<CraWebStoreInstallPage>(profile);
++ // One of the two callbacks runs; both hold the page and the reply.
++ auto split = base::SplitOnceCallback(std::move(send));
++ auto installer = base::MakeRefCounted<extensions::WebstoreInstaller>(
++ profile,
++ base::BindOnce(
++ [](scoped_refptr<CraWebStoreInstallPage>, int message_id,
++ base::OnceCallback<void(std::string)> send, const std::string&) {
++ base::DictValue result;
++ result.Set("installed", true);
++ std::move(send).Run(CraReplyJson(message_id, std::move(result),
++ std::string()));
++ },
++ page, *message_id, std::move(split.first)),
++ base::BindOnce(
++ [](scoped_refptr<CraWebStoreInstallPage>, int message_id,
++ base::OnceCallback<void(std::string)> send, const std::string& id,
++ const std::string& error,
++ extensions::WebstoreInstaller::FailureReason) {
++ LOG(WARNING) << "Cra: Web Store install of " << id
++ << " failed: " << error;
++ std::move(send).Run(CraReplyJson(
++ message_id, base::DictValue(),
++ error.empty() ? std::string("install failed") : error));
++ },
++ page, *message_id, std::move(split.second)),
++ page->contents.get(), *id, std::move(approval),
++ extensions::WebstoreInstaller::INSTALL_SOURCE_OTHER);
++ installer->Start();
++ return true;
++}
++
++bool HandleCraMethod(content::WebContents* contents,
++ std::string_view message,
++ int* message_id,
++ base::DictValue* result,
+ std::string* error) {
+ if (message.find("\"Cra.") == std::string_view::npos) {
+ return false;
@@ -283,28 +431,30 @@ index c60f22d..3be66a2 100644
CefDevToolsController::CefDevToolsController(
content::WebContents* inspected_contents)
-@@ -30,6 +288,36 @@ CefDevToolsController::~CefDevToolsController() {
+@@ -30,6 +436,38 @@ CefDevToolsController::~CefDevToolsController() {
bool CefDevToolsController::SendDevToolsMessage(
const std::string_view& message) {
CEF_REQUIRE_UIT();
++ if (StartCraWebStoreInstall(
++ inspected_contents_, message,
++ base::BindOnce(
++ [](base::WeakPtr<CefDevToolsController> self, std::string json) {
++ if (self) {
++ self->DispatchProtocolMessage(
++ nullptr, base::as_bytes(base::span(json)));
++ }
++ },
++ weak_ptr_factory_.GetWeakPtr()))) {
++ return true;
++ }
+ int cra_message_id = 0;
+ base::DictValue cra_result;
+ std::string cra_error;
+ if (HandleCraMethod(inspected_contents_, message, &cra_message_id,
+ &cra_result, &cra_error)) {
+ // Answered like a protocol method, after the caller has returned.
-+ base::DictValue reply;
-+ reply.Set("id", cra_message_id);
-+ if (cra_error.empty()) {
-+ reply.Set("result", std::move(cra_result));
-+ } else {
-+ base::DictValue error;
-+ error.Set("code", -32000);
-+ error.Set("message", cra_error);
-+ reply.Set("error", std::move(error));
-+ }
-+ std::string json;
-+ base::JSONWriter::Write(reply, &json);
++ std::string json =
++ CraReplyJson(cra_message_id, std::move(cra_result), cra_error);
+ base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
+ FROM_HERE,
+ base::BindOnce(
diff --git a/scripts/cef-patches/webstore-install-downloads.patch b/scripts/cef-patches/webstore-install-downloads.patch
new file mode 100644
index 0000000..80fba6e
--- /dev/null
+++ b/scripts/cef-patches/webstore-install-downloads.patch
@@ -0,0 +1,47 @@
+diff --git a/cef/libcef/browser/download_manager_delegate_impl.cc b/cef/libcef/browser/download_manager_delegate_impl.cc
+index e5363cc46..786bc5c86 100644
+--- a/cef/libcef/browser/download_manager_delegate_impl.cc
++++ b/cef/libcef/browser/download_manager_delegate_impl.cc
+@@ -27,6 +27,22 @@
+ #include "net/http/http_response_headers.h"
+ #include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h"
+
++namespace {
++
++// Cra (GitHub #203): the CRX a Web Store install downloads (WebstoreInstaller,
++// from the store page's "Add to Chrome" or Cra.installFromWebStore) is Chrome's
++// own: it goes to the path WebstoreInstaller set, under the profile's "Webstore
++// Downloads", and CrxInstaller takes it from there. The client's download
++// handler never sees it, so no save panel asks where to put it and it never
++// lands in the Downloads folder; and one from a page with no CefBrowser
++// (Cra.installFromWebStore's) isn't cancelled.
++bool IsCraExtensionInstall(download::DownloadItem* item) {
++ return item->GetDownloadSource() ==
++ download::DownloadSource::EXTENSION_INSTALLER;
++}
++
++} // namespace
++
+ using content::DownloadManager;
+ using content::WebContents;
+ using download::DownloadItem;
+@@ -379,6 +395,9 @@ void CefDownloadManagerDelegateImpl::OnDownloadCreated(DownloadManager* manager,
+ // This callback may arrive after DetermineDownloadTarget, so we allow
+ // association from either method.
+ CefRefPtr<CefBrowserHostBase> browser = GetOrAssociateBrowser(item);
++ if (!browser && IsCraExtensionInstall(item)) {
++ return;
++ }
+ if (!browser) {
+ // If the download is rejected (e.g. ALT+click on an invalid protocol link)
+ // then an "interrupted" download will be started via DownloadManagerImpl::
+@@ -487,6 +506,9 @@ CefDownloadManagerDelegateImpl::GetOrAssociateBrowser(
+ if (it != item_browser_map_.end()) {
+ return it->second.get();
+ }
++ if (IsCraExtensionInstall(item)) {
++ return nullptr;
++ }
+
+ CefRefPtr<CefBrowserHostBase> browser;
+ content::WebContents* contents =
diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.sh
index 5b4fa46..62661d8 100755
--- a/scripts/fetch-cef.sh
+++ b/scripts/fetch-cef.sh
@@ -13,7 +13,7 @@ CEF_VERSION="${CEF_VERSION:-156.0.15+gcf671c0+chromium-156.0.8078.80}"
ARCH="${CEF_ARCH:-macosarm64}"
NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"
# Bump the suffix (codecs2, …) when the build changes but CEF_VERSION does not.
-CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs13}"
+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs14}"
URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"
mkdir -p vendor