File: iwa_internals_handler.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (790 lines) | stat: -rw-r--r-- 31,570 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/web_app_internals/iwa_internals_handler.h"

#include <variant>

#include "base/containers/map_util.h"
#include "base/containers/to_vector.h"
#include "base/functional/overloaded.h"
#include "base/strings/stringprintf.h"
#include "base/types/expected_macros.h"
#include "base/types/optional_util.h"
#include "base/version.h"
#include "chrome/browser/file_select_helper.h"
#include "chrome/browser/ui/webui/web_app_internals/web_app_internals.mojom-forward.h"
#include "chrome/browser/ui/webui/web_app_internals/web_app_internals.mojom.h"
#include "chrome/browser/web_applications/isolated_web_apps/commands/install_isolated_web_app_command.h"
#include "chrome/browser/web_applications/isolated_web_apps/commands/isolated_web_app_install_command_helper.h"
#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_downloader.h"
#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_features.h"
#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_installation_manager.h"
#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_discovery_task.h"
#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.h"
#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_info.h"
#include "chrome/browser/web_applications/isolated_web_apps/isolation_data.h"
#include "chrome/browser/web_applications/isolated_web_apps/update_manifest/update_manifest.h"
#include "chrome/browser/web_applications/isolated_web_apps/update_manifest/update_manifest_fetcher.h"
#include "chrome/browser/web_applications/locks/app_lock.h"
#include "chrome/browser/web_applications/web_app_command_scheduler.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/web_app_registry_update.h"
#include "chrome/browser/web_applications/web_app_sync_bridge.h"
#include "components/webapps/isolated_web_apps/iwa_key_distribution_info_provider.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents_delegate.h"

namespace web_app {

namespace {

constexpr auto kUpdateManifestFetchAnnotation =
    net::DefinePartialNetworkTrafficAnnotation(
        "iwa_web_app_internals_update_manifest",
        "iwa_update_manifest_fetcher",
        R"(
    semantics {
      sender: "Web App Internals page"
      description:
        "Downloads the Update Manifest of an Isolated Web App. "
        "The Update Manifest contains the list of the available versions of "
        "the IWA and the URL to the Signed Web Bundles that correspond to each "
        "version."
      trigger:
        "User clicks on the discover button in chrome://web-app-internals."
    }
    policy {
      setting: "This feature cannot be disabled in settings."
      policy_exception_justification: "Not implemented."
    })");

constexpr auto kDownloadWebBundleAnnotation =
    net::DefinePartialNetworkTrafficAnnotation(
        "iwa_web_app_internals_web_bundle",
        "iwa_bundle_downloader",
        R"(
    semantics {
      sender: "Web App Internals page"
      description:
        "Downloads a Signed Web Bundle of an Isolated Web App which contains "
        "code and other resources of this app."
      trigger:
        "User accepts the installation dialog in chrome://web-app-internals."
    }
    policy {
      setting: "This feature cannot be disabled in settings."
      policy_exception_justification: "Not implemented."
    })");

void SendError(
    base::OnceCallback<void(::mojom::InstallIsolatedWebAppResultPtr)> callback,
    const std::string& error_message) {
  std::move(callback).Run(
      ::mojom::InstallIsolatedWebAppResult::NewError(error_message));
}

}  // namespace

class IwaInternalsHandler::IsolatedWebAppDevBundleSelectListener
    : public content::FileSelectListener {
 public:
  explicit IsolatedWebAppDevBundleSelectListener(
      base::OnceCallback<void(std::optional<base::FilePath>)> callback)
      : callback_(std::move(callback)) {}

  void Show(content::RenderFrameHost* render_frame_host) {
    blink::mojom::FileChooserParams params;
    params.mode = blink::mojom::FileChooserParams::Mode::kOpen;
    params.need_local_path = true;
    params.accept_types.push_back(u".swbn");

    FileSelectHelper::RunFileChooser(render_frame_host, this, params);
  }

  // content::FileSelectListener
  void FileSelected(std::vector<blink::mojom::FileChooserFileInfoPtr> files,
                    const base::FilePath& base_dir,
                    blink::mojom::FileChooserParams::Mode mode) override {
    CHECK(callback_);
    // `params.mode` is kOpen so a single file should have been selected.
    CHECK_EQ(files.size(), 1u);
    auto& file = *files[0];
    // `params.need_local_path` is true so the result should be a native file.
    CHECK(file.is_native_file());
    std::move(callback_).Run(file.get_native_file()->file_path);
  }

  void FileSelectionCanceled() override {
    CHECK(callback_);
    std::move(callback_).Run(std::nullopt);
  }

 private:
  ~IsolatedWebAppDevBundleSelectListener() override = default;

  base::OnceCallback<void(std::optional<base::FilePath>)> callback_;
};

class IwaInternalsHandler::IwaManifestInstallUpdateHandler
    : public IsolatedWebAppUpdateManager::Observer {
 public:
  explicit IwaManifestInstallUpdateHandler(WebAppProvider& provider)
      : provider_(provider) {
    observation_.Observe(&provider.iwa_update_manager());
  }

  void UpdateManifestInstalledIsolatedWebApp(
      const webapps::AppId& app_id,
      std::optional<base::Version> pinned_version,
      bool allow_downgrades,
      Handler::UpdateManifestInstalledIsolatedWebAppCallback callback) {
    if (base::Contains(update_requests_, app_id)) {
      std::move(callback).Run(
          "Update check skipped: please wait for the pending update request to "
          "resolve first.");
      return;
    }

    ASSIGN_OR_RETURN(
        const WebApp& iwa,
        GetIsolatedWebAppById(provider_->registrar_unsafe(), app_id),
        [&](const std::string& error) { std::move(callback).Run(error); });

    ASSIGN_OR_RETURN(
        const IsolatedWebAppUrlInfo& url_info,
        IsolatedWebAppUrlInfo::Create(iwa.manifest_id()),
        [&](const std::string& error) { std::move(callback).Run(error); })

    const IsolationData& isolation_data = *iwa.isolation_data();
    if (!isolation_data.location().dev_mode() ||
        !isolation_data.update_manifest_url()) {
      std::move(callback).Run(
          "Only dev-mode apps with update_manifest_url set can be updated via "
          "this routine.");
      return;
    }

    update_requests_.emplace(app_id, std::move(callback));

    // Some older installs might not have the `update_channel` field set -- in
    // this case we fall back to the `default` channel.
    // For now, we do not enable setting pinned_version field via iwa internals.
    // By not setting `pinned_version` argument, discovery task defaults to
    // searching for the latest available version on current update channel.
    provider_->iwa_update_manager().DiscoverUpdatesForApp(
        url_info, *isolation_data.update_manifest_url(),
        /*update_channel=*/
        isolation_data.update_channel().value_or(
            UpdateChannel::default_channel()),
        allow_downgrades, pinned_version,
        /*dev_mode=*/true);
  }

  // IsolatedWebAppUpdateManager::Observer:
  void OnUpdateDiscoveryTaskCompleted(
      const webapps::AppId& app_id,
      IsolatedWebAppUpdateDiscoveryTask::CompletionStatus status) override {
    if (status.has_value() && *status ==
                                  IsolatedWebAppUpdateDiscoveryTask::Success::
                                      kUpdateFoundAndSavedInDatabase) {
      return;
    }

    ASSIGN_OR_RETURN(auto callback, ConsumeUpdateRequest(app_id), [](auto) {});
    if (status.has_value()) {
      std::move(callback).Run(
          "Update skipped: app is already on the latest version or the updates "
          "are disabled due to set `pinned_version` field.");
    } else {
      std::move(callback).Run(
          "Update failed: " +
          IsolatedWebAppUpdateDiscoveryTask::ErrorToString(status.error()));
    }
  }

  void OnUpdateApplyTaskCompleted(
      const webapps::AppId& app_id,
      IsolatedWebAppUpdateApplyTask::CompletionStatus status) override {
    ASSIGN_OR_RETURN(auto callback, ConsumeUpdateRequest(app_id), [](auto) {});

    ASSIGN_OR_RETURN(
        const WebApp& iwa,
        GetIsolatedWebAppById(provider_->registrar_unsafe(), app_id),
        [&](const std::string& error) { std::move(callback).Run(error); });

    std::move(callback).Run(
        status.has_value()
            ? base::StringPrintf("Update to v%s successful (refresh the page "
                                 "to reflect the update).",
                                 iwa.isolation_data()->version().GetString())
            : "Update failed: " + status.error().message);
  }

 private:
  // Retrieves the pending request for `app_id` and erases the entry from the
  // requests map. If there's no matching entry for `app_id`, returns an
  // unexpected.
  base::expected<Handler::UpdateDevProxyIsolatedWebAppCallback, std::monostate>
  ConsumeUpdateRequest(const webapps::AppId& app_id) {
    auto itr = update_requests_.find(app_id);
    if (itr == update_requests_.end()) {
      return base::unexpected(std::monostate());
    }

    auto callback = std::move(itr->second);
    update_requests_.erase(itr);

    return std::move(callback);
  }

  const raw_ref<WebAppProvider> provider_;

  base::ScopedObservation<IsolatedWebAppUpdateManager,
                          IwaManifestInstallUpdateHandler>
      observation_{this};

  // Multiple parallel requests for one `app_id` are not allowed.
  base::flat_map<webapps::AppId,
                 Handler::UpdateManifestInstalledIsolatedWebAppCallback>
      update_requests_;
};

IwaInternalsHandler::IwaInternalsHandler(content::WebUI& web_ui,
                                         Profile& profile)
    : web_ui_(web_ui), profile_(profile) {
  if (auto* provider = WebAppProvider::GetForWebApps(&profile)) {
    update_handler_ =
        std::make_unique<IwaManifestInstallUpdateHandler>(*provider);
  }
}

IwaInternalsHandler::~IwaInternalsHandler() = default;

void IwaInternalsHandler::InstallIsolatedWebAppFromDevProxy(
    const GURL& url,
    Handler::InstallIsolatedWebAppFromDevProxyCallback callback) {
  auto* provider = WebAppProvider::GetForWebApps(profile());
  if (!provider) {
    SendError(std::move(callback), "could not get web app provider");
    return;
  }

  auto& manager = provider->isolated_web_app_installation_manager();
  manager.InstallIsolatedWebAppFromDevModeProxy(
      url, IsolatedWebAppInstallationManager::InstallSurface::kDevUi,
      base::BindOnce(&IwaInternalsHandler::OnInstallIsolatedWebAppInDevMode,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void IwaInternalsHandler::ParseUpdateManifestFromUrl(
    const GURL& update_manifest_url,
    Handler::ParseUpdateManifestFromUrlCallback callback) {
  if (!WebAppProvider::GetForWebApps(profile())) {
    std::move(callback).Run(::mojom::ParseUpdateManifestFromUrlResult::NewError(
        "Couldn't get the WebAppProvider."));
    return;
  }

  auto fetcher = std::make_unique<UpdateManifestFetcher>(
      update_manifest_url, kUpdateManifestFetchAnnotation,
      profile()->GetURLLoaderFactory());
  auto* fetcher_ptr = fetcher.get();

  base::OnceClosure fetcher_keep_alive =
      base::DoNothingWithBoundArgs(std::move(fetcher));
  fetcher_ptr->FetchUpdateManifest(
      base::BindOnce(
          [](const GURL& update_manifest_url,
             base::expected<UpdateManifest, UpdateManifestFetcher::Error>
                 result) -> ::mojom::ParseUpdateManifestFromUrlResultPtr {
            ASSIGN_OR_RETURN(
                auto update_manifest, std::move(result), [](auto error) {
                  return ::mojom::ParseUpdateManifestFromUrlResult::NewError(
                      "Manifest fetch failed.");
                });
            auto update_manifest_ptr = ::mojom::UpdateManifest::New();
            update_manifest_ptr->versions = base::ToVector(
                update_manifest.versions(),
                [](const UpdateManifest::VersionEntry& ve) {
                  auto version_entry = ::mojom::VersionEntry::New();
                  version_entry->version = ve.version().GetString();
                  version_entry->web_bundle_url = ve.src();
                  return version_entry;
                });
            return ::mojom::ParseUpdateManifestFromUrlResult::NewUpdateManifest(
                std::move(update_manifest_ptr));
          },
          update_manifest_url)
          .Then(std::move(callback))
          .Then(std::move(fetcher_keep_alive)));
}

void IwaInternalsHandler::InstallIsolatedWebAppFromBundleUrl(
    ::mojom::InstallFromBundleUrlParamsPtr params,
    Handler::InstallIsolatedWebAppFromBundleUrlCallback callback) {
  if (!WebAppProvider::GetForWebApps(profile())) {
    SendError(std::move(callback),
              "WebAppProvider not supported for current profile.");
    return;
  }
  if (!params->update_info) {
    SendError(std::move(callback),
             "Update info is required for this operation.");
    return;
  }
  if (!params->update_info->update_manifest_url.is_valid()) {
    SendError(std::move(callback),
              "Update manifest URL is not a valid GURL.");
    return;
  }
  if (params->update_info->update_channel.empty()) {
    SendError(std::move(callback),
              "Update channel is required for this operation.");
    return;
  }
  ScopedTempWebBundleFile::Create(
      base::BindOnce(&IwaInternalsHandler::DownloadWebBundleToFile,
                     weak_ptr_factory_.GetWeakPtr(), params->web_bundle_url,
                     std::move(params->update_info), std::move(callback)));
}

void IwaInternalsHandler::SelectFileAndInstallIsolatedWebAppFromDevBundle(
    Handler::SelectFileAndInstallIsolatedWebAppFromDevBundleCallback callback) {
  content::RenderFrameHost* render_frame_host = web_ui_->GetRenderFrameHost();
  if (!render_frame_host) {
    SendError(std::move(callback), "could not get render frame host");
    return;
  }

  base::MakeRefCounted<IsolatedWebAppDevBundleSelectListener>(
      base::BindOnce(
          &IwaInternalsHandler::OnIsolatedWebAppDevModeBundleSelected,
          weak_ptr_factory_.GetWeakPtr(), std::move(callback)))
      ->Show(render_frame_host);
}

void IwaInternalsHandler::OnIsolatedWebAppDevModeBundleSelected(
    Handler::SelectFileAndInstallIsolatedWebAppFromDevBundleCallback callback,
    std::optional<base::FilePath> path) {
  if (!path) {
    SendError(std::move(callback), "no file selected");
    return;
  }

  auto* provider = WebAppProvider::GetForWebApps(profile());
  if (!provider) {
    SendError(std::move(callback), "could not get web app provider");
    return;
  }

  auto& manager = provider->isolated_web_app_installation_manager();
  manager.InstallIsolatedWebAppFromDevModeBundle(
      *path, IsolatedWebAppInstallationManager::InstallSurface::kDevUi,
      base::BindOnce(&IwaInternalsHandler::OnInstallIsolatedWebAppInDevMode,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void IwaInternalsHandler::SelectFileAndUpdateIsolatedWebAppFromDevBundle(
    const webapps::AppId& app_id,
    Handler::SelectFileAndUpdateIsolatedWebAppFromDevBundleCallback callback) {
  content::RenderFrameHost* render_frame_host = web_ui_->GetRenderFrameHost();
  if (!render_frame_host) {
    std::move(callback).Run("could not get render frame host");
    return;
  }

  base::MakeRefCounted<IsolatedWebAppDevBundleSelectListener>(
      base::BindOnce(
          &IwaInternalsHandler::OnIsolatedWebAppDevModeBundleSelectedForUpdate,
          weak_ptr_factory_.GetWeakPtr(), app_id, std::move(callback)))
      ->Show(render_frame_host);
}

void IwaInternalsHandler::OnIsolatedWebAppDevModeBundleSelectedForUpdate(
    const webapps::AppId& app_id,
    Handler::SelectFileAndUpdateIsolatedWebAppFromDevBundleCallback callback,
    std::optional<base::FilePath> path) {
  if (!path) {
    std::move(callback).Run("no file selected");
    return;
  }

  IwaSourceDevModeWithFileOp source(
      IwaSourceBundleDevModeWithFileOp(*path, IwaSourceBundleDevFileOp::kCopy));
  ApplyDevModeUpdate(app_id, source, std::move(callback));
}

void IwaInternalsHandler::OnInstallIsolatedWebAppInDevMode(
    base::OnceCallback<void(::mojom::InstallIsolatedWebAppResultPtr)> callback,
    IsolatedWebAppInstallationManager::MaybeInstallIsolatedWebAppCommandSuccess
        result) {
  std::move(callback).Run([&] {
    if (result.has_value()) {
      auto success = ::mojom::InstallIsolatedWebAppSuccess::New();
      success->web_bundle_id = result->url_info.web_bundle_id().id();
      return ::mojom::InstallIsolatedWebAppResult::NewSuccess(
          std::move(success));
    }
    return ::mojom::InstallIsolatedWebAppResult::NewError(result.error());
  }());
}

void IwaInternalsHandler::SearchForIsolatedWebAppUpdates(
    Handler::SearchForIsolatedWebAppUpdatesCallback callback) {
  auto* provider = WebAppProvider::GetForWebApps(profile());
  if (!provider) {
    std::move(callback).Run("could not get web app provider");
    return;
  }

  size_t queued_task_count =
      provider->iwa_update_manager().DiscoverUpdatesNow();
  std::move(callback).Run(base::StringPrintf(
      "queued %zu update discovery tasks", queued_task_count));
}

void IwaInternalsHandler::GetIsolatedWebAppDevModeAppInfo(
    Handler::GetIsolatedWebAppDevModeAppInfoCallback callback) {
  if (!IsIwaDevModeEnabled(profile())) {
    std::move(callback).Run({});
    return;
  }

  auto* provider = WebAppProvider::GetForWebApps(profile());
  if (!provider) {
    std::move(callback).Run({});
    return;
  }

  std::vector<::mojom::IwaDevModeAppInfoPtr> dev_mode_apps;
  for (const WebApp& app : provider->registrar_unsafe().GetApps()) {
    if (!app.isolation_data().has_value()) {
      continue;
    }

    base::expected<IwaSourceDevMode, std::monostate> source =
        IwaSourceDevMode::FromStorageLocation(profile()->GetPath(),
                                              app.isolation_data()->location());
    if (!source.has_value()) {
      continue;
    }

    const web_app::IsolationData& isolation_data = *app.isolation_data();
    std::optional<std::string> pinned_version;
    if (base::Contains(pinned_versions_, app.app_id())) {
      pinned_version = pinned_versions_[app.app_id()].GetString();
    }
    bool allow_downgrades = app_ids_allowing_downgrades_.contains(app.app_id());
    std::visit(
        base::Overloaded{
            [&](const IwaSourceBundleDevMode& source) {
              dev_mode_apps.emplace_back(::mojom::IwaDevModeAppInfo::New(
                  app.app_id(), app.untranslated_name(),
                  ::mojom::IwaDevModeLocation::NewBundlePath(source.path()),
                  app.isolation_data()->version().GetString(),
                  /*update_info=*/isolation_data.update_manifest_url()
                      ? ::mojom::UpdateInfo::New(
                            *isolation_data.update_manifest_url(),
                            isolation_data.update_channel()
                                .value_or(UpdateChannel::default_channel())
                                .ToString(),
                            pinned_version, allow_downgrades)
                      : nullptr));
            },
            [&](const IwaSourceProxy& source) {
              dev_mode_apps.emplace_back(::mojom::IwaDevModeAppInfo::New(
                  app.app_id(), app.untranslated_name(),
                  ::mojom::IwaDevModeLocation::NewProxyOrigin(
                      source.proxy_url()),
                  app.isolation_data()->version().GetString(),
                  /*update_info=*/nullptr));
            },
        },
        source->variant());
  }

  std::move(callback).Run(std::move(dev_mode_apps));
}

void IwaInternalsHandler::UpdateDevProxyIsolatedWebApp(
    const webapps::AppId& app_id,
    Handler::UpdateDevProxyIsolatedWebAppCallback callback) {
  ApplyDevModeUpdate(app_id,
                     // For dev mode proxy apps, the location remains the same
                     // and does not change between updates.
                     /*location=*/std::nullopt, std::move(callback));
}

void IwaInternalsHandler::ApplyDevModeUpdate(
    const webapps::AppId& app_id,
    base::optional_ref<const IwaSourceDevModeWithFileOp> location,
    base::OnceCallback<void(const std::string&)> callback) {
  if (!IsIwaDevModeEnabled(profile())) {
    std::move(callback).Run("IWA dev mode is not enabled");
    return;
  }

  auto* provider = WebAppProvider::GetForWebApps(profile());
  if (!provider) {
    std::move(callback).Run("could not get web app provider");
    return;
  }

  auto* app = provider->registrar_unsafe().GetAppById(app_id);
  if (!app || !app->isolation_data().has_value()) {
    std::move(callback).Run("could not find installed IWA");
    return;
  }
  ASSIGN_OR_RETURN(IwaSourceDevMode source,
                   IwaSourceDevMode::FromStorageLocation(
                       profile()->GetPath(), app->isolation_data()->location()),
                   [&](auto error) {
                     std::move(callback).Run("can only update dev-mode apps");
                   });

  auto url_info = IsolatedWebAppUrlInfo::Create(app->manifest_id());
  if (!url_info.has_value()) {
    std::move(callback).Run("unable to create UrlInfo from start url");
    return;
  }

  auto& manager = provider->iwa_update_manager();
  manager.DiscoverApplyAndPrioritizeLocalDevModeUpdate(
      location.has_value() ? *location
                           : IwaSourceDevModeWithFileOp(source.WithFileOp(
                                 IwaSourceBundleDevFileOp::kCopy)),
      *url_info,
      base::BindOnce([](base::expected<base::Version, std::string> result) {
        if (result.has_value()) {
          return base::StrCat(
              {"Update to version ", result->GetString(),
               " successful (refresh this page to reflect the update)."});
        }
        return "Update failed: " + result.error();
      }).Then(std::move(callback)));
}

void IwaInternalsHandler::RotateKey(
    const std::string& web_bundle_id,
    const std::optional<std::vector<uint8_t>>& public_key) {
  IwaKeyDistributionInfoProvider::GetInstance()->RotateKeyForDevMode(
      base::PassKey<IwaInternalsHandler>(), web_bundle_id, public_key);
}

void IwaInternalsHandler::UpdateManifestInstalledIsolatedWebApp(
    const webapps::AppId& app_id,
    Handler::UpdateManifestInstalledIsolatedWebAppCallback callback) {
  if (!update_handler_) {
    std::move(callback).Run(
        "WebAppProvider is not available for the current profile.");
    return;
  }

  std::optional<base::Version> pinned_version =
      base::OptionalFromPtr(base::FindOrNull(pinned_versions_, app_id));
  bool allow_downgrades = app_ids_allowing_downgrades_.contains(app_id);

  update_handler_->UpdateManifestInstalledIsolatedWebApp(
      app_id, pinned_version, allow_downgrades, std::move(callback));
}

void IwaInternalsHandler::SetUpdateChannelForIsolatedWebApp(
    const webapps::AppId& app_id,
    const std::string& update_channel,
    Handler::SetUpdateChannelForIsolatedWebAppCallback callback) {
  auto* provider = WebAppProvider::GetForWebApps(profile());
  if (!provider) {
    std::move(callback).Run(/*success=*/false);
    return;
  }
  provider->scheduler().ScheduleCallbackWithResult(
      "WebAppInternalsHandler::SetUpdateChannel",
      web_app::AppLockDescription(app_id),
      base::BindOnce(
          [](const webapps::AppId& app_id, const std::string& update_channel,
             AppLock& lock, base::Value::Dict& debug_value) {
            web_app::ScopedRegistryUpdate update =
                lock.sync_bridge().BeginUpdate();

            web_app::WebApp* web_app = update->UpdateApp(app_id);
            auto channel = UpdateChannel::Create(update_channel);
            if (!web_app || !web_app->isolation_data() ||
                !web_app->isolation_data()->update_manifest_url() ||
                !channel.has_value()) {
              return false;
            }

            web_app->SetIsolationData(
                web_app::IsolationData::Builder(*web_app->isolation_data())
                    .SetUpdateChannel(std::move(*channel))
                    .Build());

            return true;
          },
          app_id, update_channel),
      std::move(callback), /*arg_for_shutdown=*/false);
}

void IwaInternalsHandler::SetPinnedVersionForIsolatedWebApp(
    const webapps::AppId& app_id,
    const std::string pinned_version,
    Handler::SetPinnedVersionForIsolatedWebAppCallback callback) {
  auto* provider = WebAppProvider::GetForWebApps(profile());
  if (!provider) {
    std::move(callback).Run(/*success=*/false);
    return;
  }

  RETURN_IF_ERROR(GetIsolatedWebAppById(provider->registrar_unsafe(), app_id), [&](auto) { std::move(callback).Run(/*success=*/false); });

  base::Version version = base::Version(pinned_version);
  if (!version.IsValid()) {
    std::move(callback).Run(/*success=*/false);
    return;
  }

  pinned_versions_[app_id] = version;
  std::move(callback).Run(/*success=*/true);
}

void IwaInternalsHandler::ResetPinnedVersionForIsolatedWebApp(
    const webapps::AppId& app_id) {
  pinned_versions_.erase(app_id);
}

void IwaInternalsHandler::SetAllowDowngradesForIsolatedWebApp(
    bool allow_downgrades,
    const webapps::AppId& app_id) {
  auto* provider = WebAppProvider::GetForWebApps(profile());
  if (!provider || provider->registrar_unsafe().GetInstallState(app_id)
      != proto::INSTALLED_WITH_OS_INTEGRATION) {
    return;
  }

  // Removes `app_id` for which downgrades were turned off.
  if (base::Contains(app_ids_allowing_downgrades_, app_id) &&
      !allow_downgrades) {
    app_ids_allowing_downgrades_.erase(app_id);
    return;
  }
  app_ids_allowing_downgrades_.insert(app_id);
}

void IwaInternalsHandler::DownloadWebBundleToFile(
    const GURL& web_bundle_url,
    ::mojom::UpdateInfoPtr update_info,
    Handler::InstallIsolatedWebAppFromBundleUrlCallback callback,
    ScopedTempWebBundleFile file) {
  if (!file) {
    std::move(callback).Run(::mojom::InstallIsolatedWebAppResult::NewError(
        "Couldn't create file."));
    return;
  }
  auto path = file.path();

  auto downloader = std::make_unique<IsolatedWebAppDownloader>(
      profile()->GetURLLoaderFactory());
  auto* downloader_ptr = downloader.get();
  base::OnceClosure downloader_keep_alive =
      base::DoNothingWithBoundArgs(std::move(downloader));

  downloader_ptr->DownloadSignedWebBundle(
      web_bundle_url, std::move(path), kDownloadWebBundleAnnotation,
      base::BindOnce(&IwaInternalsHandler::OnWebBundleDownloaded,
                     weak_ptr_factory_.GetWeakPtr(), std::move(update_info),
                     std::move(callback), std::move(file))
          .Then(std::move(downloader_keep_alive)));
}

void IwaInternalsHandler::OnWebBundleDownloaded(
    ::mojom::UpdateInfoPtr update_info,
    Handler::InstallIsolatedWebAppFromBundleUrlCallback callback,
    ScopedTempWebBundleFile bundle,
    int32_t result) {
  if (result != net::OK) {
    std::move(callback).Run(::mojom::InstallIsolatedWebAppResult::NewError(
        base::StrCat({"Network error while downloading bundle file: ",
                      base::ToString(result)})));
    return;
  }

  const base::ScopedTempFile* file = bundle.file();
  base::OnceClosure bundle_keep_alive =
      base::DoNothingWithBoundArgs(std::move(bundle));

  WebAppProvider::GetForWebApps(profile())
      ->isolated_web_app_installation_manager()
      .InstallIsolatedWebAppFromDevModeBundle(
          file, IsolatedWebAppInstallationManager::InstallSurface::kDevUi,
          base::BindOnce(
              &IwaInternalsHandler::
                  OnInstalledIsolatedWebAppInDevModeFromWebBundle,
              weak_ptr_factory_.GetWeakPtr(), std::move(update_info),
              std::move(callback).Then(std::move(bundle_keep_alive))));
}

void IwaInternalsHandler::OnInstalledIsolatedWebAppInDevModeFromWebBundle(
    ::mojom::UpdateInfoPtr update_info,
    base::OnceCallback<void(::mojom::InstallIsolatedWebAppResultPtr)> callback,
    base::expected<InstallIsolatedWebAppCommandSuccess, std::string> result) {
  ASSIGN_OR_RETURN(auto install_info, std::move(result),
                   [&](const std::string& error) {
                     std::move(callback).Run(
                         ::mojom::InstallIsolatedWebAppResult::NewError(error));
                   });

  web_app::WebAppProvider::GetForWebApps(&profile_.get())
      ->scheduler()
      .ScheduleCallbackWithResult(
          "WebAppInternalsHandler::SetUpdateInfo",
          web_app::AppLockDescription(install_info.url_info.app_id()),
          base::BindOnce(
              [](const IsolatedWebAppUrlInfo& url_info,
                 ::mojom::UpdateInfoPtr update_info, AppLock& lock,
                 base::Value::Dict& debug_value) {
                web_app::ScopedRegistryUpdate update =
                    lock.sync_bridge().BeginUpdate();

                web_app::WebApp* web_app = update->UpdateApp(url_info.app_id());
                if (!web_app || !web_app->isolation_data()) {
                  return ::mojom::InstallIsolatedWebAppResult::NewError(
                      "Something went wrong while setting the update info.");
                }

                auto update_channel =
                    UpdateChannel::Create(update_info->update_channel);
                if (!update_channel.has_value()) {
                  return ::mojom::InstallIsolatedWebAppResult::NewError(
                      "Something went wrong while setting the update "
                      "channel.");
                }

                GURL update_manifest_url = update_info->update_manifest_url;
                if (!update_manifest_url.is_valid()) {
                  return ::mojom::InstallIsolatedWebAppResult::NewError(
                      "Something went wrong while setting the update "
                      "manifest url.");
                }
                web_app->SetIsolationData(
                    web_app::IsolationData::Builder(*web_app->isolation_data())
                        .SetUpdateManifestUrl(update_info->update_manifest_url)
                        .SetUpdateChannel(std::move(*update_channel))
                        .Build());

                auto success = ::mojom::InstallIsolatedWebAppSuccess::New();
                success->web_bundle_id = url_info.web_bundle_id().id();

                return ::mojom::InstallIsolatedWebAppResult::NewSuccess(
                    std::move(success));
              },
              install_info.url_info, std::move(update_info)),
          std::move(callback), /*arg_for_shutdown=*/
          ::mojom::InstallIsolatedWebAppResult::NewError(
              "The web app system has shut down."));
}

}  // namespace web_app