diff --git a/garage_updates/LICENSE b/garage_updates/LICENSE
new file mode 100644
index 0000000..72fab54
--- /dev/null
+++ b/garage_updates/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 IMBENJI.NET LTD
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/garage_updates/analysis_options.yaml b/garage_updates/analysis_options.yaml
new file mode 100644
index 0000000..a907916
--- /dev/null
+++ b/garage_updates/analysis_options.yaml
@@ -0,0 +1,6 @@
+include: package:flutter_lints/flutter.yaml
+
+linter:
+ rules:
+ # the SDK prints caught errors to console on purpose for debugging
+ avoid_print: false
diff --git a/garage_updates/android/.gitignore b/garage_updates/android/.gitignore
new file mode 100644
index 0000000..161bdcd
--- /dev/null
+++ b/garage_updates/android/.gitignore
@@ -0,0 +1,9 @@
+*.iml
+.gradle
+/local.properties
+/.idea/workspace.xml
+/.idea/libraries
+.DS_Store
+/build
+/captures
+.cxx
diff --git a/garage_updates/android/build.gradle.kts b/garage_updates/android/build.gradle.kts
new file mode 100644
index 0000000..87a6dd7
--- /dev/null
+++ b/garage_updates/android/build.gradle.kts
@@ -0,0 +1,58 @@
+group = "net.imbenji.garage_updates"
+version = "1.0-SNAPSHOT"
+
+buildscript {
+ val kotlinVersion = "2.3.20"
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+ dependencies {
+ classpath("com.android.tools.build:gradle:9.0.1")
+ classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
+ }
+}
+
+allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+plugins {
+ id("com.android.library")
+}
+
+android {
+ namespace = "net.imbenji.garage_updates"
+
+ compileSdk = 36
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ sourceSets {
+ getByName("main") {
+ java.srcDirs("src/main/kotlin")
+ }
+ }
+
+ defaultConfig {
+ minSdk = 24
+ }
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
+ }
+}
+
+dependencies {
+ // FileProvider, the only way to hand the installer a file since android 7
+ implementation("androidx.core:core:1.13.1")
+}
diff --git a/garage_updates/android/settings.gradle.kts b/garage_updates/android/settings.gradle.kts
new file mode 100644
index 0000000..0d6f0f4
--- /dev/null
+++ b/garage_updates/android/settings.gradle.kts
@@ -0,0 +1 @@
+rootProject.name = "garage_updates"
diff --git a/garage_updates/android/src/main/AndroidManifest.xml b/garage_updates/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..fc6070e
--- /dev/null
+++ b/garage_updates/android/src/main/AndroidManifest.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesFileProvider.kt b/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesFileProvider.kt
new file mode 100644
index 0000000..1cbe68d
--- /dev/null
+++ b/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesFileProvider.kt
@@ -0,0 +1,6 @@
+package net.imbenji.garage_updates
+
+import androidx.core.content.FileProvider
+
+// nothing in it. it exists so the manifest entry has a class name of its own
+class GarageUpdatesFileProvider : FileProvider()
diff --git a/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesPlugin.kt b/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesPlugin.kt
new file mode 100644
index 0000000..a5e720d
--- /dev/null
+++ b/garage_updates/android/src/main/kotlin/net/imbenji/garage_updates/GarageUpdatesPlugin.kt
@@ -0,0 +1,106 @@
+package net.imbenji.garage_updates
+
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+import android.util.Log
+import androidx.core.content.FileProvider
+import io.flutter.embedding.engine.plugins.FlutterPlugin
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import io.flutter.plugin.common.MethodChannel.Result
+import java.io.File
+
+// The android half of garage_updates. Two things dart cant do for itself:
+// find out who installed the app, and hand an apk to the system installer.
+// The installer always asks the person, theres no silent path and we dont
+// want one.
+class GarageUpdatesPlugin : FlutterPlugin, MethodCallHandler {
+ private lateinit var channel: MethodChannel
+ private lateinit var context: Context
+
+ override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
+ context = binding.applicationContext
+ channel = MethodChannel(binding.binaryMessenger, "net.imbenji.garage_updates")
+ channel.setMethodCallHandler(this)
+ }
+
+ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
+ channel.setMethodCallHandler(null)
+ }
+
+ override fun onMethodCall(call: MethodCall, result: Result) {
+ when (call.method) {
+ "info" -> result.success(
+ mapOf(
+ "installer" to installerPackageName(),
+ "cacheDir" to context.cacheDir.absolutePath,
+ )
+ )
+
+ "installerPackageName" -> result.success(installerPackageName())
+
+ "install" -> {
+ val path = call.argument("path")
+ if (path == null) {
+ result.error("bad_args", "install needs a path", null)
+ return
+ }
+ install(File(path), result)
+ }
+
+ else -> result.notImplemented()
+ }
+ }
+
+ // "com.android.vending" for a play store install, null for a sideload
+ private fun installerPackageName(): String? {
+ val pm = context.packageManager
+ return try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ pm.getInstallSourceInfo(context.packageName).installingPackageName
+ } else {
+ @Suppress("DEPRECATION")
+ pm.getInstallerPackageName(context.packageName)
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "couldnt read the installer package name", e)
+ null
+ }
+ }
+
+ private fun install(apk: File, result: Result) {
+ if (!apk.exists()) {
+ result.error("missing", "No apk at ${apk.path}", null)
+ return
+ }
+
+ try {
+ val uri = FileProvider.getUriForFile(
+ context,
+ "${context.packageName}.garage_updates.files",
+ apk,
+ )
+
+ val intent = Intent(Intent.ACTION_VIEW).apply {
+ setDataAndType(uri, "application/vnd.android.package-archive")
+ // the installer is another app, it needs lending the file
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ // we only have the application context, not an activity
+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+
+ context.startActivity(intent)
+ result.success(null)
+ } catch (e: Exception) {
+ // an apk outside the shared cache folder lands here too
+ Log.e(TAG, "couldnt open the installer for ${apk.path}", e)
+ result.error("install_failed", e.message ?: "The installer could not be opened", null)
+ }
+ }
+
+ companion object {
+ private const val TAG = "garage_updates"
+ }
+}
diff --git a/garage_updates/android/src/main/res/xml/garage_updates_paths.xml b/garage_updates/android/src/main/res/xml/garage_updates_paths.xml
new file mode 100644
index 0000000..ea88c70
--- /dev/null
+++ b/garage_updates/android/src/main/res/xml/garage_updates_paths.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/garage_updates/example/lib/main.dart b/garage_updates/example/lib/main.dart
new file mode 100644
index 0000000..0bb9d1e
--- /dev/null
+++ b/garage_updates/example/lib/main.dart
@@ -0,0 +1,117 @@
+import "package:flutter/widgets.dart";
+import "package:garage_ui/garage_ui.dart";
+import "package:garage_updates/garage_updates.dart";
+import "package:go_router/go_router.dart";
+
+// The whole integration is the one call at the top of main. Everything under
+// it is just an app with a "restart to update" button, which is the only
+// other thing an app has to do for itself.
+//
+// Run it with `flutter run` and the updater prints that this copy isnt an
+// install and stays out of the way - it only ever touches a release build
+// that the installer (or a previous update) put in place.
+
+Future main(List args) async {
+ // an app with helpers of its own (an agent, a tray) stops them here
+ GarageUpdater.instance.onBeforeRestart = () async {
+ print("about to restart into the new build");
+ };
+
+ await GarageUpdater.launch(
+ args: args,
+ project: "proj_example",
+ build: 12, // the number after the + in pubspec's version
+ label: "v2610-1",
+ branding: const UpdaterBranding(
+ name: "Example App",
+ logo: Icon(LucideIcons.package),
+ ),
+ mode: UpdateMode.prompt,
+ );
+
+ runApp(const ExampleApp());
+}
+
+final _theme = ThemeData(
+ colorScheme: GarageSchemes.carbon,
+ density: const Density.product(),
+);
+
+final _router = GoRouter(
+ routes: [
+ GoRoute(path: "/", builder: (context, state) => const HomePage()),
+ ],
+);
+
+class ExampleApp extends StatelessWidget {
+ const ExampleApp({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return GarageApp.router(routerConfig: _router, theme: _theme, title: "Example App");
+ }
+}
+
+class HomePage extends StatefulWidget {
+ const HomePage({super.key});
+
+ @override
+ State createState() => _HomePageState();
+}
+
+class _HomePageState extends State {
+ String? _error;
+
+ Future _restart() async {
+ try {
+ await GarageUpdater.instance.restartToUpdate();
+ } on UpdateError catch (e) {
+ // a UAC prompt turned down, say. the update is still waiting
+ print("couldnt restart into the update: $e");
+ if (mounted) setState(() => _error = e.message);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final updater = GarageUpdater.instance;
+
+ return Scaffold(
+ child: Center(
+ child: ValueListenableBuilder(
+ valueListenable: updater.ready,
+ builder: (context, waiting, _) {
+ final latest = waiting?.latest;
+
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text("Example App ${updater.label}").large().semiBold(),
+ const Gap.sm(),
+ if (latest == null)
+ const Text("Up to date").muted()
+ else ...[
+ Text("${latest.label} is ready to install").muted(),
+ const Gap.sm(),
+
+ // the notes are the apps to show, the splash never does
+ if (latest.notes.isNotEmpty) Text(latest.notes).muted(),
+ const Gap.lg(),
+ Button(
+ style: const ButtonStyle.primary(),
+ onPressed: _restart,
+ child: const Text("Restart to update"),
+ ),
+ ],
+ if (_error != null) ...[
+ const Gap.md(),
+ Text(_error!).muted(),
+ ],
+ ],
+ );
+ },
+ ),
+ ),
+ );
+ }
+}
diff --git a/garage_updates/example/pubspec.yaml b/garage_updates/example/pubspec.yaml
new file mode 100644
index 0000000..fd91331
--- /dev/null
+++ b/garage_updates/example/pubspec.yaml
@@ -0,0 +1,24 @@
+name: garage_updates_example
+description: "Minimal example of an app that updates itself with garage_updates."
+publish_to: 'none'
+version: 0.1.0+12
+
+environment:
+ sdk: ^3.10.0
+ flutter: ">=3.5.0"
+
+dependencies:
+ flutter:
+ sdk: flutter
+
+ garage_ui:
+ path: ../../garage_ui
+ garage_updates:
+ path: ../
+
+ go_router: ^14.6.2
+
+dev_dependencies:
+ flutter_lints: ^6.0.0
+
+flutter:
diff --git a/garage_updates/lib/core.dart b/garage_updates/lib/core.dart
new file mode 100644
index 0000000..ae1b274
--- /dev/null
+++ b/garage_updates/lib/core.dart
@@ -0,0 +1,20 @@
+// The updater without flutter: ask Garage for the newest release, download it
+// with resume, check the sha256, install it and restart.
+//
+// A headless dart program (an agent, a cli) imports this one. A flutter app
+// wants package:garage_updates/garage_updates.dart instead, which is this
+// plus the splash.
+//
+// final engine = UpdateEngine.detect(project: "", build: 12);
+// final info = await engine.check();
+// if (info.hasUpdate) {
+// await engine.download(info.latest!);
+// await engine.install(info.latest!);
+// await engine.restart(args: args);
+// }
+//
+// android isnt in here, installing an apk needs a platform channel.
+library;
+
+export "src/core/models.dart";
+export "src/core/io.dart" if (dart.library.js_interop) "src/core/web.dart";
diff --git a/garage_updates/lib/garage_updates.dart b/garage_updates/lib/garage_updates.dart
new file mode 100644
index 0000000..3ca38af
--- /dev/null
+++ b/garage_updates/lib/garage_updates.dart
@@ -0,0 +1,25 @@
+// Auto updates for a flutter app, akin to Discord's. One call at the top of
+// main and the rest happens on its own:
+//
+// Future main(List args) async {
+// await GarageUpdater.launch(
+// args: args,
+// project: "",
+// build: 12,
+// label: "v2610-1",
+// branding: UpdaterBranding(name: "Garage Stash", logo: "assets/logo.png"),
+// );
+// runApp(const MyApp());
+// }
+//
+// While the app runs, GarageUpdater.instance.ready says when a newer build has
+// been downloaded, and restartToUpdate() moves over to it.
+//
+// On the web every call is a no-op.
+library;
+
+export "src/core/models.dart"
+ show UpdateInfo, UpdateRelease, UpdateAsset, UpdateStatus, UpdateError, UpdateDriver, DownloadProgress;
+export "src/branding.dart" show UpdaterBranding, UpdateMode;
+export "src/splash.dart" show UpdateSplash, UpdateSplashApp, SplashController, SplashStage;
+export "src/updater.dart" show GarageUpdater;
diff --git a/garage_updates/lib/src/branding.dart b/garage_updates/lib/src/branding.dart
new file mode 100644
index 0000000..72e7aaf
--- /dev/null
+++ b/garage_updates/lib/src/branding.dart
@@ -0,0 +1,39 @@
+import "package:flutter/widgets.dart";
+import "package:garage_ui/garage_ui.dart";
+
+/// What happens to an update the app could carry on without.
+enum UpdateMode {
+ /// found at launch = downloaded and installed there and then, behind the
+ /// splash. The app starts allready up to date
+ silent,
+
+ /// never installed from the splash. Its fetched in the background and
+ /// `GarageUpdater.instance.ready` tells the app, which asks the person
+ prompt,
+}
+
+/// Whose splash it is.
+class UpdaterBranding {
+ const UpdaterBranding({required this.name, this.logo, this.theme})
+ : assert(
+ logo == null || logo is Widget || logo is String || logo is ImageProvider,
+ "logo is an asset path, an ImageProvider or a Widget",
+ );
+
+ /// the developers name for the app, shown under the logo
+ final String name;
+
+ /// an asset path ("assets/logo.png"), an [ImageProvider], or any widget
+ final Object? logo;
+
+ /// the splash wears carbon at the product tier unless told otherwise
+ final ThemeData? theme;
+
+ Widget? buildLogo() {
+ final l = logo;
+ if (l is Widget) return l;
+ if (l is String) return Image.asset(l);
+ if (l is ImageProvider) return Image(image: l);
+ return null;
+ }
+}
diff --git a/garage_updates/lib/src/core/client.dart b/garage_updates/lib/src/core/client.dart
new file mode 100644
index 0000000..bf8f588
--- /dev/null
+++ b/garage_updates/lib/src/core/client.dart
@@ -0,0 +1,138 @@
+import "dart:async";
+import "dart:convert";
+import "dart:ffi" show Abi;
+import "dart:io";
+
+import "models.dart";
+
+const kDefaultApiBase = "https://pay.imbenji.net/api";
+
+/// Asks Garage what the newest release is. No sign in, one GET.
+class UpdateClient {
+ UpdateClient({
+ required this.project,
+ String apiBase = kDefaultApiBase,
+ HttpClient? httpClient,
+ this.timeout = const Duration(seconds: 20),
+ }) : apiBase = apiBase.endsWith("/") ? apiBase.substring(0, apiBase.length - 1) : apiBase,
+ _http = httpClient ?? HttpClient();
+
+ final String project;
+ final String apiBase;
+ final Duration timeout;
+ final HttpClient _http;
+
+ Uri checkUri({required String platform, required String arch, required int build}) {
+ return Uri.parse("$apiBase/v1/updates/${Uri.encodeComponent(project)}").replace(
+ queryParameters: {"platform": platform, "arch": arch, "build": "$build"},
+ );
+ }
+
+ /// `GET /v1/updates/:pid`. Throws [UpdateError] when the server cant be
+ /// reached or says no, a 200 with an odd body comes back as unknown.
+ Future check({
+ required String platform,
+ required String arch,
+ required int build,
+ }) async {
+ final uri = checkUri(platform: platform, arch: arch, build: build);
+
+ final HttpClientResponse res;
+ final String body;
+ try {
+ final req = await _http.getUrl(uri).timeout(timeout);
+ req.headers.set(HttpHeaders.acceptHeader, "application/json");
+ res = await req.close().timeout(timeout);
+ body = await res.transform(utf8.decoder).join().timeout(timeout);
+ } on TimeoutException catch (e) {
+ print("[garage_updates] the update check timed out: $e");
+ throw UpdateError("timeout", "The update check timed out");
+ } catch (e, st) {
+ print("[garage_updates] the update check didnt get through: $e\n$st");
+ throw UpdateError("network", "Couldn't reach the update server");
+ }
+
+ if (res.statusCode != 200) {
+ // the store api's errors are {"error": code, "message": ...}
+ var code = "http_${res.statusCode}";
+ var message = "The update server answered ${res.statusCode}";
+ try {
+ final j = jsonDecode(body);
+ if (j is Map) {
+ if (j["error"] is String) code = j["error"] as String;
+ if (j["message"] is String) message = j["message"] as String;
+ }
+ } catch (e) {
+ print("[garage_updates] update check ${res.statusCode} with a body that isnt json: $e");
+ }
+ throw UpdateError(code, message);
+ }
+
+ Object? json;
+ try {
+ json = jsonDecode(body);
+ } catch (e) {
+ print("[garage_updates] the update check answered something that isnt json: $e");
+ return const UpdateInfo(status: UpdateStatus.unknown);
+ }
+
+ final info = UpdateInfo.fromJson(json);
+ final latest = info.latest;
+ if (latest == null) return info;
+
+ // hosted assets come back absolute, but dont fall over on a relative one
+ final resolved = _resolve(latest.asset.url);
+ if (resolved == latest.asset.url) return info;
+ return UpdateInfo(
+ status: info.status,
+ minimumBuild: info.minimumBuild,
+ latest: UpdateRelease(
+ label: latest.label,
+ build: latest.build,
+ notes: latest.notes,
+ publishedAt: latest.publishedAt,
+ asset: UpdateAsset(
+ url: resolved,
+ filename: latest.asset.filename,
+ format: latest.asset.format,
+ size: latest.asset.size,
+ sha256: latest.asset.sha256,
+ ),
+ ),
+ );
+ }
+
+ String _resolve(String url) {
+ final u = Uri.tryParse(url);
+ if (u == null || u.hasScheme) return url;
+ return Uri.parse("$apiBase/").resolve(url.startsWith("/") ? url.substring(1) : url).toString();
+ }
+
+ void close() => _http.close(force: true);
+}
+
+
+/// "windows" | "macos" | "android", or null where theres nothing to update
+String? currentUpdatePlatform() {
+ if (Platform.isWindows) return "windows";
+ if (Platform.isMacOS) return "macos";
+ if (Platform.isAndroid) return "android";
+ return null;
+}
+
+/// The arch to ask for. The server falls back to `universal` by itself, so
+/// this only has to be honest about the machine.
+String currentUpdateArch() {
+ final abi = Abi.current();
+ if (abi == Abi.windowsX64 || abi == Abi.macosX64 || abi == Abi.androidX64 || abi == Abi.linuxX64) {
+ return "x64";
+ }
+ if (abi == Abi.windowsArm64 ||
+ abi == Abi.macosArm64 ||
+ abi == Abi.androidArm64 ||
+ abi == Abi.linuxArm64) {
+ return "arm64";
+ }
+ // 32 bit android and the like. only a universal asset can suit it
+ return "universal";
+}
diff --git a/garage_updates/lib/src/core/downloader.dart b/garage_updates/lib/src/core/downloader.dart
new file mode 100644
index 0000000..b6ccae2
--- /dev/null
+++ b/garage_updates/lib/src/core/downloader.dart
@@ -0,0 +1,276 @@
+import "dart:async";
+import "dart:convert";
+import "dart:io";
+
+import "package:crypto/crypto.dart";
+
+import "models.dart";
+
+// Fetches one release asset into the staging folder.
+//
+// The bytes land in `update.part`, with a little json beside it saying which
+// build + sha they belong to. A cut connection leaves both where they are and
+// the next go asks for `Range: bytes=N-`. Only once the whole file hashes to
+// what Garage recorded does it get its real name.
+
+const _partName = "update.part";
+const _metaName = "update.part.json";
+
+class Downloader {
+ Downloader({
+ HttpClient? httpClient,
+ this.quietTimeout = const Duration(seconds: 30),
+ this.retries = 3,
+ this.retryPause = const Duration(seconds: 2),
+ }) : _http = httpClient ?? HttpClient();
+
+ final HttpClient _http;
+
+ /// how long the line may say nothing before we call it dead
+ final Duration quietTimeout;
+
+ /// extra goes after the first, each one resuming
+ final int retries;
+ final Duration retryPause;
+
+ static File partFile(Directory staging) => File(_join(staging.path, _partName));
+ static File metaFile(Directory staging) => File(_join(staging.path, _metaName));
+
+ /// where a finished, verified download of [release] sits
+ static File finishedFile(Directory staging, UpdateRelease release) {
+ final ext = release.asset.format.isEmpty ? "bin" : release.asset.format;
+ return File(_join(staging.path, "update-${release.build}.$ext"));
+ }
+
+ Future fetch({
+ required UpdateRelease release,
+ required Directory staging,
+ DownloadProgress? onProgress,
+ }) async {
+ final asset = release.asset;
+ if (asset.sha256.isEmpty) {
+ // never install something we cant check
+ throw UpdateError("no_checksum", "The release has no checksum to verify against");
+ }
+
+ await staging.create(recursive: true);
+ final done = finishedFile(staging, release);
+ final part = partFile(staging);
+ final meta = metaFile(staging);
+
+ if (await done.exists()) {
+ if (await sha256Of(done) == asset.sha256) {
+ onProgress?.call(await done.length(), await done.length());
+ return done;
+ }
+ print("[garage_updates] ${done.path} doesnt match its checksum any more, fetching it again");
+ await _remove(done);
+ }
+ await _sweep(staging, keep: done);
+
+ if (!await _partIsOurs(meta, release)) {
+ if (await part.exists()) {
+ print("[garage_updates] throwing away a stale part file, it was for another build");
+ }
+ await _remove(part);
+ await _writeMeta(meta, release);
+ }
+
+
+ var attempt = 0;
+ while (true) {
+ try {
+ await _pull(asset, part, onProgress);
+ break;
+ } on UpdateError catch (e) {
+ if (!_worthRetrying(e) || attempt >= retries) rethrow;
+ print("[garage_updates] download stopped (${e.message}), going again");
+ } catch (e, st) {
+ // a cut connection, a quiet line. the part file stays for the resume
+ print("[garage_updates] download stopped: $e\n$st");
+ if (attempt >= retries) {
+ throw UpdateError("download", "The download kept failing: $e");
+ }
+ }
+ attempt++;
+ await Future.delayed(retryPause);
+ }
+
+ final got = await sha256Of(part);
+ if (got != asset.sha256) {
+ print("[garage_updates] checksum mismatch, wanted ${asset.sha256} got $got");
+ await _remove(part);
+ await _remove(meta);
+ throw UpdateError("checksum_mismatch", "The download didn't match its checksum");
+ }
+
+ await part.rename(done.path);
+ await _remove(meta);
+ return done;
+ }
+
+ bool _worthRetrying(UpdateError e) => e.code == "restart" || e.code == "server";
+
+ Future _pull(UpdateAsset asset, File part, DownloadProgress? onProgress) async {
+ var have = await part.exists() ? await part.length() : 0;
+
+ if (asset.size > 0 && have > asset.size) {
+ print("[garage_updates] the part file is bigger than the release, starting over");
+ await _remove(part);
+ have = 0;
+ }
+ // all there allready, only the checksum left to do
+ if (asset.size > 0 && have == asset.size) {
+ onProgress?.call(have, asset.size);
+ return;
+ }
+
+ final res = await _open(Uri.parse(asset.url), have);
+ var append = false;
+
+ if (res.statusCode == HttpStatus.partialContent) {
+ final start = _rangeStart(res.headers.value(HttpHeaders.contentRangeHeader));
+ if (start == have) {
+ append = true;
+ } else if (start == 0) {
+ have = 0;
+ } else {
+ await _drain(res);
+ await _remove(part);
+ throw UpdateError("restart", "The server resumed from the wrong place");
+ }
+ } else if (res.statusCode == HttpStatus.ok) {
+ // it ignored the range and sent the lot. fine, start the file again
+ if (have > 0) print("[garage_updates] the server ignored the range, downloading from the top");
+ have = 0;
+ } else if (res.statusCode == HttpStatus.requestedRangeNotSatisfiable) {
+ await _drain(res);
+ await _remove(part);
+ throw UpdateError("restart", "The server wouldn't resume the download");
+ } else {
+ await _drain(res);
+ if (res.statusCode >= 500) {
+ throw UpdateError("server", "The download server answered ${res.statusCode}");
+ }
+ throw UpdateError("http_${res.statusCode}", "The download was refused (${res.statusCode})");
+ }
+
+ int? total;
+ if (res.contentLength >= 0) {
+ total = have + res.contentLength;
+ } else if (asset.size > 0) {
+ total = asset.size;
+ }
+
+ final out = await part.open(mode: append ? FileMode.writeOnlyAppend : FileMode.writeOnly);
+ var received = have;
+ try {
+ onProgress?.call(received, total);
+ await for (final chunk in res.timeout(quietTimeout)) {
+ await out.writeFrom(chunk);
+ received += chunk.length;
+ onProgress?.call(received, total);
+ }
+ } finally {
+ await out.close();
+ }
+
+ if (total != null && received < total) {
+ throw HttpException("the download ended early, $received of $total bytes");
+ }
+ }
+
+ // Walks the redirects by hand. A hosted download is a 302 to a presigned url
+ // that only lives a few minutes, so a resume has to start from the original
+ // link every time - which is why nothing here remembers where it ended up.
+ Future _open(Uri uri, int have) async {
+ for (var hop = 0; hop < 6; hop++) {
+ final req = await _http.getUrl(uri).timeout(quietTimeout);
+ req.followRedirects = false;
+ // dart asks for gzip by itself and unpacks it, which makes a nonsense
+ // of byte ranges
+ req.headers.removeAll(HttpHeaders.acceptEncodingHeader);
+ if (have > 0) req.headers.set(HttpHeaders.rangeHeader, "bytes=$have-");
+
+ final res = await req.close().timeout(quietTimeout);
+ final location = res.headers.value(HttpHeaders.locationHeader);
+ if (res.isRedirect || (_redirects.contains(res.statusCode) && location != null)) {
+ await _drain(res);
+ if (location == null) {
+ throw UpdateError("redirect", "The download redirected to nowhere");
+ }
+ uri = uri.resolve(location);
+ continue;
+ }
+ return res;
+ }
+ throw UpdateError("redirect", "The download redirected too many times");
+ }
+
+ static const _redirects = {301, 302, 303, 307, 308};
+
+ int? _rangeStart(String? contentRange) {
+ // "bytes 100-999/1000"
+ if (contentRange == null) return null;
+ final m = RegExp(r"bytes\s+(\d+)-").firstMatch(contentRange);
+ return m == null ? null : int.tryParse(m.group(1)!);
+ }
+
+ Future _drain(HttpClientResponse res) async {
+ try {
+ await res.drain().timeout(quietTimeout);
+ } catch (e) {
+ print("[garage_updates] couldnt drain a response we didnt want: $e");
+ }
+ }
+
+ Future _partIsOurs(File meta, UpdateRelease release) async {
+ if (!await meta.exists()) return false;
+ try {
+ final j = jsonDecode(await meta.readAsString());
+ return j is Map && j["build"] == release.build && j["sha256"] == release.asset.sha256;
+ } catch (e) {
+ print("[garage_updates] unreadable part note, treating the part as stale: $e");
+ return false;
+ }
+ }
+
+ Future _writeMeta(File meta, UpdateRelease release) async {
+ await meta.writeAsString(
+ jsonEncode({"build": release.build, "sha256": release.asset.sha256}),
+ flush: true,
+ );
+ }
+
+ // finished downloads of other builds, nobody is going to install those now
+ Future _sweep(Directory staging, {required File keep}) async {
+ try {
+ await for (final e in staging.list()) {
+ if (e is! File || e.path == keep.path) continue;
+ final name = e.uri.pathSegments.last;
+ if (name.startsWith("update-")) await _remove(e);
+ }
+ } catch (e) {
+ print("[garage_updates] couldnt tidy the staging folder: $e");
+ }
+ }
+
+ void close() => _http.close(force: true);
+}
+
+/// sha256 of a file as lower case hex, read as a stream so a big download
+/// never sits in memory
+Future sha256Of(File f) async {
+ final digest = await sha256.bind(f.openRead()).first;
+ return digest.toString();
+}
+
+Future _remove(File f) async {
+ try {
+ if (await f.exists()) await f.delete();
+ } catch (e) {
+ print("[garage_updates] couldnt delete ${f.path}: $e");
+ }
+}
+
+String _join(String a, String b) => a.endsWith(Platform.pathSeparator) ? "$a$b" : "$a${Platform.pathSeparator}$b";
diff --git a/garage_updates/lib/src/core/engine.dart b/garage_updates/lib/src/core/engine.dart
new file mode 100644
index 0000000..6e532a1
--- /dev/null
+++ b/garage_updates/lib/src/core/engine.dart
@@ -0,0 +1,184 @@
+import "dart:async";
+import "dart:io";
+
+import "client.dart";
+import "downloader.dart";
+import "installer.dart";
+import "models.dart";
+
+/// The whole updater with no flutter in it: check, download, install,
+/// restart. The splash drives one of these, and so can a headless program.
+///
+/// final engine = UpdateEngine.detect(project: "...", build: 12);
+/// final info = await engine.check();
+/// if (info.hasUpdate) {
+/// await engine.download(info.latest!);
+/// await engine.install(info.latest!);
+/// await engine.restart(args: args);
+/// }
+class UpdateEngine implements UpdateDriver {
+ UpdateEngine({
+ required this.project,
+ required this.build,
+ String apiBase = kDefaultApiBase,
+ Installer? installer,
+ String? notInstalledReason,
+ UpdateClient? client,
+ Downloader? downloader,
+ String? arch,
+ void Function(int code)? exitProcess,
+ }) : _installer = installer,
+ notInstalledReason = installer != null ? null : (notInstalledReason ?? "no installer"),
+ client = client ?? UpdateClient(project: project, apiBase: apiBase),
+ downloader = downloader ?? Downloader(),
+ arch = arch ?? currentUpdateArch(),
+ _exit = exitProcess ?? exit;
+
+ /// Looks at where this process is running from and builds the engine for
+ /// it. Somewhere the updater didnt put it = an engine that does nothing.
+ factory UpdateEngine.detect({
+ required String project,
+ required int build,
+ String apiBase = kDefaultApiBase,
+ }) {
+ final found = detectInstall();
+ return UpdateEngine(
+ project: project,
+ build: build,
+ apiBase: apiBase,
+ installer: found.installer,
+ notInstalledReason: found.reason,
+ );
+ }
+
+ final String project;
+
+ /// the build this process is
+ final int build;
+ final String arch;
+
+ final UpdateClient client;
+ final Downloader downloader;
+ final Installer? _installer;
+ final void Function(int code) _exit;
+
+ @override
+ final String? notInstalledReason;
+
+ @override
+ FutureOr Function()? onBeforeRestart;
+
+ @override
+ bool get installed => _installer != null;
+
+ Installer? get installer => _installer;
+
+ bool _saidNotInstalled = false;
+ final Set _saidBlocked = {};
+
+ /// Says once why this copy wont be updated. Returns [installed].
+ bool reportIfNotInstalled() {
+ if (installed) return true;
+ if (!_saidNotInstalled) {
+ _saidNotInstalled = true;
+ print("[garage_updates] not updating this copy: $notInstalledReason");
+ }
+ return false;
+ }
+
+ @override
+ Future noteStart() async {
+ final inst = _installer;
+ if (inst == null) return false;
+ return inst.noteStart(build);
+ }
+
+ @override
+ Future check() async {
+ final inst = _installer;
+ if (inst == null) {
+ reportIfNotInstalled();
+ return const UpdateInfo(status: UpdateStatus.unknown);
+ }
+
+ final info = await client.check(platform: inst.platform, arch: arch, build: build);
+ final latest = info.latest;
+ if (latest == null) return info;
+
+ if (latest.build <= build) {
+ // the server only offers newer ones, but never go backwards on its say so
+ return UpdateInfo(status: UpdateStatus.current, minimumBuild: info.minimumBuild);
+ }
+
+ if (inst.blockedBuilds().contains(latest.build)) {
+ if (_saidBlocked.add(latest.build)) {
+ print("[garage_updates] build ${latest.build} failed to start on this machine before, not taking it again");
+ }
+ // still required if it was, theres just nothing here that can be installed
+ return UpdateInfo(
+ status: info.isRequired ? UpdateStatus.required : UpdateStatus.current,
+ minimumBuild: info.minimumBuild,
+ );
+ }
+ return info;
+ }
+
+ @override
+ Future download(UpdateRelease release, {DownloadProgress? onProgress}) async {
+ final inst = _need();
+ await downloader.fetch(release: release, staging: inst.staging, onProgress: onProgress);
+ }
+
+ /// true when [release] is allready downloaded and verified
+ Future isDownloaded(UpdateRelease release) async {
+ final inst = _installer;
+ if (inst == null) return false;
+ return Downloader.finishedFile(inst.staging, release).exists();
+ }
+
+ @override
+ Future install(UpdateRelease release) async {
+ final inst = _need();
+ final file = Downloader.finishedFile(inst.staging, release);
+ if (!await file.exists()) {
+ throw UpdateError("not_downloaded", "Build ${release.build} hasn't been downloaded");
+ }
+ await inst.apply(file, release, runningBuild: build);
+ }
+
+ @override
+ Future restart({List args = const []}) async {
+ final inst = _need();
+
+ final before = onBeforeRestart;
+ if (before != null) {
+ try {
+ await before();
+ } catch (e, st) {
+ // the apps own tidy up going wrong shouldnt strand it on the old build
+ print("[garage_updates] onBeforeRestart threw, restarting anyway: $e\n$st");
+ }
+ }
+
+ await inst.relaunch(args);
+ if (inst.exitsOnRestart) _exit(0);
+ }
+
+ @override
+ Future markHealthy() async {
+ await _installer?.markHealthy();
+ }
+
+ Installer _need() {
+ final inst = _installer;
+ if (inst == null) {
+ throw UpdateError("not_installed", "This copy of the app can't be updated: $notInstalledReason");
+ }
+ return inst;
+ }
+
+ void close() {
+ client.close();
+ downloader.close();
+ }
+}
diff --git a/garage_updates/lib/src/core/installer.dart b/garage_updates/lib/src/core/installer.dart
new file mode 100644
index 0000000..923a035
--- /dev/null
+++ b/garage_updates/lib/src/core/installer.dart
@@ -0,0 +1,99 @@
+import "dart:io";
+
+import "mac_installer.dart";
+import "models.dart";
+import "windows_installer.dart";
+
+/// The part that differs per platform: where downloads go, how a verified
+/// archive becomes the installed app, and how the app is started again.
+abstract class Installer {
+ /// "windows" | "macos" | "android", what the check is asked for
+ String get platform;
+
+ /// where the `.part` file and the finished download live
+ Directory get staging;
+
+ /// builds that failed to start here and must not be offered again
+ List blockedBuilds();
+
+ /// Turns the verified [archive] into the installed app. Does not restart.
+ Future apply(File archive, UpdateRelease release, {required int runningBuild});
+
+ /// Starts the app again. The caller ends this process afterwards when
+ /// [exitsOnRestart] says so.
+ Future relaunch(List args);
+
+ /// false on android, where the system installer does the restarting
+ bool get exitsOnRestart;
+
+ /// Counts a start of [build]. true = the previous build was just put back
+ /// because this one kept dying, relaunch.
+ Future noteStart(int build);
+
+ Future markHealthy();
+}
+
+typedef ProcessRunner = Future Function(String exe, List args);
+typedef ProcessStarter = Future Function(String exe, List args);
+
+Future defaultRunner(String exe, List args) => Process.run(exe, args);
+
+Future defaultStarter(String exe, List args) async {
+ // detached, it has to outlive us
+ await Process.start(exe, args, mode: ProcessStartMode.detached);
+}
+
+/// What [detectInstall] found. Exactly one of the two is set.
+class InstallDetection {
+ const InstallDetection.found(Installer this.installer) : reason = null;
+ const InstallDetection.none(String this.reason) : installer = null;
+
+ final Installer? installer;
+
+ /// why this copy of the app isnt one we can update
+ final String? reason;
+}
+
+/// Works out whether this process is running from somewhere the updater put
+/// it. A dev build, `flutter run`, `dart run`, a folder that isnt
+/// `app-`, a translocated or read only mac bundle: all "none", and the
+/// updater then leaves the app completly alone.
+InstallDetection detectInstall({
+ String? executable,
+ Map? environment,
+ String? platform,
+ bool? product,
+}) {
+ // debug + profile builds and anything run off the jit. a release build is
+ // the only thing that should ever get swapped
+ product ??= const bool.fromEnvironment("dart.vm.product");
+ if (!product) return const InstallDetection.none("this isn't a release build");
+
+ final exe = executable ?? Platform.resolvedExecutable;
+ final env = environment ?? Platform.environment;
+
+ switch (platform ?? Platform.operatingSystem) {
+ case "windows":
+ return WindowsInstaller.locate(exe, environment: env);
+ case "macos":
+ return MacInstaller.locate(exe, environment: env);
+ default:
+ return InstallDetection.none("no installer for ${platform ?? Platform.operatingSystem} here");
+ }
+}
+
+/// last bit of a path, whichever way the slashes lean
+String baseName(String path) {
+ var p = path;
+ while (p.length > 1 && (p.endsWith("/") || p.endsWith("\\"))) {
+ p = p.substring(0, p.length - 1);
+ }
+ final cut = p.lastIndexOf(RegExp(r"[/\\]"));
+ return cut < 0 ? p : p.substring(cut + 1);
+}
+
+String joinPath(String a, String b, [String? c]) {
+ final sep = Platform.pathSeparator;
+ final ab = a.endsWith(sep) ? "$a$b" : "$a$sep$b";
+ return c == null ? ab : "$ab$sep$c";
+}
diff --git a/garage_updates/lib/src/core/io.dart b/garage_updates/lib/src/core/io.dart
new file mode 100644
index 0000000..017a824
--- /dev/null
+++ b/garage_updates/lib/src/core/io.dart
@@ -0,0 +1,12 @@
+// everything in core that needs dart:io. see core.dart
+
+export "client.dart";
+export "downloader.dart";
+export "engine.dart";
+export "installer.dart";
+export "mac_installer.dart";
+export "state.dart";
+export "windows_installer.dart";
+
+/// false on the web, where theres nothing to update
+const bool kUpdatesSupported = true;
diff --git a/garage_updates/lib/src/core/mac_installer.dart b/garage_updates/lib/src/core/mac_installer.dart
new file mode 100644
index 0000000..3d671a6
--- /dev/null
+++ b/garage_updates/lib/src/core/mac_installer.dart
@@ -0,0 +1,343 @@
+import "dart:convert";
+import "dart:io";
+
+import "installer.dart";
+import "models.dart";
+import "state.dart";
+
+// macOS. No stub here, the bundle is swapped where it stands:
+//
+// unpack the zip with ditto, move the running .app out to
+// ~/Library/Application Support//garage_updates/previous.app,
+// move the new one into its place, `open -n` it.
+//
+// A running app carries on fine after its bundle is moved, the files are
+// still open. The fallback the windows stub does (3 starts that never get to
+// markHealthy = go back) is done in here too, by noteStart().
+
+const _maxFailedStarts = 3;
+
+class MacInstaller implements Installer {
+ MacInstaller({
+ required this.bundle,
+ required this.bundleId,
+ required this.support,
+ ProcessRunner? run,
+ }) : _run = run ?? defaultRunner;
+
+ /// the .app we are running out of
+ final Directory bundle;
+ final String bundleId;
+
+ /// `~/Library/Application Support//garage_updates`
+ final Directory support;
+
+ final ProcessRunner _run;
+
+ late final StateFile state = StateFile(File(joinPath(support.path, "state.json")));
+
+ Directory get previousApp => Directory(joinPath(support.path, "previous.app"));
+
+ static InstallDetection locate(String executable, {Map? environment}) {
+ final env = environment ?? Platform.environment;
+
+ final bundle = _bundleOf(executable);
+ if (bundle == null) {
+ return InstallDetection.none("${baseName(executable)} isn't running from an app bundle");
+ }
+
+ final path = bundle.path;
+ if (path.contains("/AppTranslocation/")) {
+ // gatekeeper runs a quarantined app from a random read only mount untill
+ // its been moved by hand. nothing to swap there
+ return const InstallDetection.none("the app is translocated, move it to Applications first");
+ }
+ if (path.contains("/Build/Products/") || path.contains("/DerivedData/")) {
+ return const InstallDetection.none("the app is running out of a build folder");
+ }
+ if (!_writable(bundle.parent.path) || !_writable(path)) {
+ return InstallDetection.none("$path can't be replaced by this user");
+ }
+
+ final id = readBundleId(bundle);
+ if (id == null) {
+ return const InstallDetection.none("the bundle has no CFBundleIdentifier");
+ }
+
+ final home = env["HOME"];
+ if (home == null || home.isEmpty) {
+ return const InstallDetection.none("no HOME to keep the update state in");
+ }
+
+ return InstallDetection.found(MacInstaller(
+ bundle: bundle,
+ bundleId: id,
+ support: Directory("$home/Library/Application Support/$id/garage_updates"),
+ ));
+ }
+
+ // the OUTERMOST .app in the path. a helper in Contents/MacOS, or in a login
+ // item bundle nested inside, still belongs to the app around it
+ static Directory? _bundleOf(String executable) {
+ final parts = executable.split("/");
+ for (var i = 0; i < parts.length - 1; i++) {
+ if (parts[i].endsWith(".app") && parts[i].length > 4) {
+ return Directory(parts.sublist(0, i + 1).join("/"));
+ }
+ }
+ return null;
+ }
+
+ static bool _writable(String path) {
+ try {
+ return Process.runSync("/bin/test", ["-w", path]).exitCode == 0;
+ } catch (e) {
+ print("[garage_updates] couldnt check whether $path is writable: $e");
+ return false;
+ }
+ }
+
+ @override
+ String get platform => "macos";
+
+ @override
+ bool get exitsOnRestart => true;
+
+ @override
+ Directory get staging => Directory(joinPath(support.path, "staging"));
+
+ @override
+ List blockedBuilds() => state.read()?.blocked ?? const [];
+
+ @override
+ Future apply(File archive, UpdateRelease release, {required int runningBuild}) async {
+ final unpack = Directory(joinPath(support.path, "unpack"));
+ await _wipe(unpack);
+ await unpack.create(recursive: true);
+
+ try {
+ switch (release.asset.format) {
+ case "zip":
+ await _must("/usr/bin/ditto", ["-x", "-k", archive.path, unpack.path], "unpack the update");
+ case "dmg":
+ await _fromDmg(archive, unpack);
+ default:
+ throw UpdateError("format", "A mac release has to be a zip or a dmg, not ${release.asset.format}");
+ }
+
+ final fresh = _findApp(unpack);
+ if (fresh == null) {
+ throw UpdateError("no_app", "There's no .app inside the update");
+ }
+
+ // dont let a mislabelled asset replace us with some other app
+ final freshId = readBundleId(fresh);
+ if (freshId != null && freshId != bundleId) {
+ throw UpdateError("wrong_app", "The update is for $freshId, this is $bundleId");
+ }
+
+ await _swap(fresh);
+ } finally {
+ await _wipe(unpack);
+ }
+
+ state.update((s) {
+ // what we are running is the truth, whatever the file last thought
+ s.previous = runningBuild;
+ s.current = release.build;
+ s.failedStarts = 0;
+ }, createIfMissing: true);
+
+ try {
+ if (archive.existsSync()) archive.deleteSync();
+ } catch (e) {
+ print("[garage_updates] couldnt remove ${archive.path} after installing it: $e");
+ }
+ }
+
+ Future _swap(Directory fresh) async {
+ await _wipe(previousApp);
+ await support.create(recursive: true);
+
+ await _move(bundle.path, previousApp.path);
+ try {
+ await _move(fresh.path, bundle.path);
+ } catch (e, st) {
+ print("[garage_updates] couldnt move the new bundle in, putting the old one back: $e\n$st");
+ await _move(previousApp.path, bundle.path);
+ rethrow;
+ }
+ }
+
+ Future _fromDmg(File dmg, Directory unpack) async {
+ final mount = Directory(joinPath(support.path, "mount"));
+ await _wipe(mount);
+ await mount.create(recursive: true);
+
+ await _must(
+ "/usr/bin/hdiutil",
+ ["attach", "-nobrowse", "-readonly", "-noautoopen", "-mountpoint", mount.path, dmg.path],
+ "open the disk image",
+ );
+ try {
+ final app = _findApp(mount);
+ if (app == null) throw UpdateError("no_app", "There's no .app inside the disk image");
+ await _must(
+ "/usr/bin/ditto",
+ [app.path, joinPath(unpack.path, baseName(app.path))],
+ "copy the app off the disk image",
+ );
+ } finally {
+ final res = await _run("/usr/bin/hdiutil", ["detach", mount.path, "-force"]);
+ if (res.exitCode != 0) {
+ print("[garage_updates] couldnt detach ${mount.path}: ${res.stderr}");
+ }
+ await _wipe(mount);
+ }
+ }
+
+ // top level, or one folder down (a zip of a folder holding the app)
+ Directory? _findApp(Directory dir) {
+ final found = [];
+ void look(Directory d, int depth) {
+ for (final e in d.listSync(followLinks: false)) {
+ if (e is! Directory) continue;
+ final name = baseName(e.path);
+ if (name == "__MACOSX") continue;
+ if (name.endsWith(".app")) {
+ found.add(e);
+ } else if (depth == 0) {
+ look(e, 1);
+ }
+ }
+ }
+
+ look(dir, 0);
+ if (found.isEmpty) return null;
+
+ final ours = baseName(bundle.path);
+ for (final f in found) {
+ if (baseName(f.path) == ours) return f;
+ }
+ return found.first;
+ }
+
+ @override
+ Future relaunch(List args) async {
+ await _must(
+ "/usr/bin/open",
+ ["-n", bundle.path, if (args.isNotEmpty) ...["--args", ...args]],
+ "start the app again",
+ );
+ }
+
+ @override
+ Future noteStart(int build) async {
+ final s = state.read() ?? UpdateState();
+
+ if (s.current != build) {
+ // a build this file has never seen start. put there by hand, most likely
+ if (!previousApp.existsSync()) s.previous = null;
+ s.current = build;
+ s.failedStarts = 0;
+ }
+
+ if (s.failedStarts >= _maxFailedStarts && s.previous != null && previousApp.existsSync()) {
+ print("[garage_updates] build $build failed to start ${s.failedStarts} times, going back to ${s.previous}");
+ try {
+ await _swapBack();
+ } catch (e, st) {
+ print("[garage_updates] couldnt put the previous build back: $e\n$st");
+ return false;
+ }
+
+ if (!s.blocked.contains(build)) s.blocked.add(build);
+ s.current = s.previous;
+ s.previous = null;
+ s.failedStarts = 0;
+ state.write(s);
+ return true;
+ }
+
+ s.failedStarts++;
+ state.write(s);
+ return false;
+ }
+
+ Future _swapBack() async {
+ final failed = Directory(joinPath(support.path, "failed.app"));
+ await _wipe(failed);
+
+ await _move(bundle.path, failed.path);
+ try {
+ await _move(previousApp.path, bundle.path);
+ } catch (e) {
+ print("[garage_updates] the previous bundle wouldnt move back, restoring: $e");
+ await _move(failed.path, bundle.path);
+ rethrow;
+ }
+ await _wipe(failed);
+ }
+
+ @override
+ Future markHealthy() async {
+ final s = state.read();
+ if (s != null && s.failedStarts == 0) return;
+ state.update((s) => s.failedStarts = 0, createIfMissing: true);
+ }
+
+
+ Future _move(String from, String to) async {
+ try {
+ await Directory(from).rename(to);
+ return;
+ } on FileSystemException catch (e) {
+ // another volume, rename cant cross those. mv copies when it has to
+ print("[garage_updates] rename $from -> $to failed (${e.osError?.message}), trying mv");
+ }
+ await _must("/bin/mv", [from, to], "move ${baseName(from)}");
+ }
+
+ Future _must(String exe, List args, String what) async {
+ final res = await _run(exe, args);
+ if (res.exitCode != 0) {
+ print("[garage_updates] ${baseName(exe)} ${args.join(" ")} exited ${res.exitCode}\n${res.stdout}\n${res.stderr}");
+ throw UpdateError("install_failed", "Couldn't $what");
+ }
+ }
+
+ Future _wipe(Directory d) async {
+ try {
+ if (await d.exists()) await d.delete(recursive: true);
+ } catch (e) {
+ print("[garage_updates] couldnt remove ${d.path}: $e");
+ }
+ }
+}
+
+/// CFBundleIdentifier out of a bundles Info.plist, null when there isnt one
+String? readBundleId(Directory app) {
+ final plist = File("${app.path}/Contents/Info.plist");
+ if (!plist.existsSync()) return null;
+
+ try {
+ final text = utf8.decode(plist.readAsBytesSync(), allowMalformed: true);
+ if (!text.startsWith("bplist")) {
+ final m = RegExp(r"\s*CFBundleIdentifier\s*\s*([^<]+)").firstMatch(text);
+ if (m != null) return m.group(1)!.trim();
+ }
+
+ // a binary plist, or xml laid out some way the regex didnt expect
+ final res = Process.runSync(
+ "/usr/libexec/PlistBuddy",
+ ["-c", "Print :CFBundleIdentifier", plist.path],
+ );
+ if (res.exitCode == 0) {
+ final id = (res.stdout as String).trim();
+ if (id.isNotEmpty) return id;
+ }
+ } catch (e) {
+ print("[garage_updates] couldnt read ${plist.path}: $e");
+ }
+ return null;
+}
diff --git a/garage_updates/lib/src/core/models.dart b/garage_updates/lib/src/core/models.dart
new file mode 100644
index 0000000..63cee47
--- /dev/null
+++ b/garage_updates/lib/src/core/models.dart
@@ -0,0 +1,208 @@
+import "dart:async";
+
+// The shapes the update check hands back, and the one interface the flutter
+// half drives. Nothing in here touches dart:io, so it compiles for the web
+// where the whole package is a no-op.
+
+enum UpdateStatus {
+ /// nothing newer for this platform
+ current,
+
+ /// theres a newer build, the app may carry on without it
+ available,
+
+ /// this build is below the projects minimum. the app must not start
+ required,
+
+ /// the server couldnt tell (no build sent), or we couldnt read its answer
+ unknown,
+}
+
+class UpdateAsset {
+ const UpdateAsset({
+ required this.url,
+ required this.filename,
+ required this.format,
+ required this.size,
+ required this.sha256,
+ });
+
+ final String url;
+ final String filename;
+
+ /// "zip" | "dmg" | "apk"
+ final String format;
+ final int size;
+ final String sha256;
+
+ static UpdateAsset? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final url = _str(raw["url"]);
+ if (url == null || url.isEmpty) return null;
+
+ final filename = _str(raw["filename"]) ?? "";
+ var format = (_str(raw["format"]) ?? "").toLowerCase();
+ if (format.isEmpty) {
+ // older answers might not carry it, the filename says the same thing
+ final dot = filename.lastIndexOf(".");
+ if (dot >= 0) format = filename.substring(dot + 1).toLowerCase();
+ }
+
+ return UpdateAsset(
+ url: url,
+ filename: filename,
+ format: format,
+ size: _int(raw["size"]) ?? 0,
+ sha256: (_str(raw["sha256"]) ?? "").toLowerCase(),
+ );
+ }
+
+ Map toJson() => {
+ "url": url,
+ "filename": filename,
+ "format": format,
+ "size": size,
+ "sha256": sha256,
+ };
+}
+
+class UpdateRelease {
+ const UpdateRelease({
+ required this.label,
+ required this.build,
+ required this.asset,
+ this.notes = "",
+ this.publishedAt,
+ });
+
+ final String label;
+ final int build;
+ final String notes;
+ final DateTime? publishedAt;
+ final UpdateAsset asset;
+
+ static UpdateRelease? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final build = _int(raw["build"]);
+ final asset = UpdateAsset.fromJson(raw["asset"]);
+ // a release we cant order or cant download is no use to anyone
+ if (build == null || asset == null) return null;
+
+ final published = _str(raw["published_at"]);
+ return UpdateRelease(
+ label: _str(raw["label"]) ?? "",
+ build: build,
+ notes: _str(raw["notes"]) ?? "",
+ publishedAt: published == null ? null : DateTime.tryParse(published),
+ asset: asset,
+ );
+ }
+
+ Map toJson() => {
+ "label": label,
+ "build": build,
+ "notes": notes,
+ "published_at": publishedAt?.toUtc().toIso8601String(),
+ "asset": asset.toJson(),
+ };
+}
+
+class UpdateInfo {
+ const UpdateInfo({required this.status, this.minimumBuild, this.latest});
+
+ final UpdateStatus status;
+ final int? minimumBuild;
+ final UpdateRelease? latest;
+
+ /// true when theres something to download
+ bool get hasUpdate =>
+ latest != null && (status == UpdateStatus.available || status == UpdateStatus.required);
+
+ bool get isRequired => status == UpdateStatus.required;
+
+ /// Reads the body of `GET /v1/updates/:pid`. Never throws on a strange
+ /// shape, it just comes back as unknown.
+ factory UpdateInfo.fromJson(Object? raw) {
+ if (raw is! Map) return const UpdateInfo(status: UpdateStatus.unknown);
+
+ final latest = UpdateRelease.fromJson(raw["latest"]);
+ var status = switch (_str(raw["status"])) {
+ "current" => UpdateStatus.current,
+ "available" => UpdateStatus.available,
+ "required" => UpdateStatus.required,
+ _ => UpdateStatus.unknown,
+ };
+
+ // says theres an update but didnt send one we can use
+ if (latest == null && (status == UpdateStatus.available || status == UpdateStatus.required)) {
+ print("[garage_updates] the check said ${status.name} but sent no usable release");
+ status = UpdateStatus.unknown;
+ }
+
+ return UpdateInfo(
+ status: status,
+ minimumBuild: _int(raw["minimum_build"]),
+ latest: latest,
+ );
+ }
+
+ UpdateInfo withStatus(UpdateStatus s) =>
+ UpdateInfo(status: s, minimumBuild: minimumBuild, latest: latest);
+}
+
+
+/// Anything the updater gives up on. `code` is stable, `message` is for a log.
+class UpdateError implements Exception {
+ UpdateError(this.code, this.message);
+
+ final String code;
+ final String message;
+
+ @override
+ String toString() => "UpdateError($code): $message";
+}
+
+/// bytes so far, and the total when we know it
+typedef DownloadProgress = void Function(int received, int? total);
+
+/// What the splash and the background check drive. The real one is
+/// `UpdateEngine` in core, the web gets none at all.
+abstract class UpdateDriver {
+ /// false for a dev build, `flutter run`, a translocated mac bundle and so
+ /// on. When its false nothing else here does anything
+ bool get installed;
+
+ /// why not, for the one line that gets printed
+ String? get notInstalledReason;
+
+ /// Run right before the app is restarted into the new build, so an app can
+ /// stop its own helper processes first.
+ FutureOr Function()? onBeforeRestart;
+
+ /// Counts this start. Comes back true when the last update kept failing to
+ /// start and the old build was put back - the caller should [restart].
+ Future noteStart();
+
+ Future check();
+
+ /// Downloads + verifies. Safe to call again, it picks up where it stopped.
+ Future download(UpdateRelease release, {DownloadProgress? onProgress});
+
+ /// Installs what [download] fetched. Does not restart.
+ Future install(UpdateRelease release);
+
+ /// Starts the app again and ends this process. On android the system
+ /// installer does the restarting, so this returns.
+ Future restart({List args = const []});
+
+ Future markHealthy();
+}
+
+String? _str(Object? v) => v is String ? v : null;
+
+int? _int(Object? v) {
+ if (v is int) return v;
+ if (v is double && v.isFinite) return v.toInt();
+ if (v is String) return int.tryParse(v.trim());
+ return null;
+}
diff --git a/garage_updates/lib/src/core/state.dart b/garage_updates/lib/src/core/state.dart
new file mode 100644
index 0000000..74f1ded
--- /dev/null
+++ b/garage_updates/lib/src/core/state.dart
@@ -0,0 +1,228 @@
+import "dart:convert";
+import "dart:io";
+
+// `garage_updates.json` on windows (shared with the stub) and `state.json` on
+// the mac. Same fields on both.
+
+class UpdateState {
+ UpdateState({
+ this.exe,
+ this.current,
+ this.previous,
+ this.failedStarts = 0,
+ List? blocked,
+ Map? extra,
+ }) : blocked = blocked ?? [],
+ extra = extra ?? {};
+
+ /// the real exe inside a version folder. windows only
+ String? exe;
+
+ int? current;
+ int? previous;
+
+ /// starts of `current` that never reached markHealthy
+ int failedStarts;
+
+ /// builds that failed 3 starts on this machine, never offered here again
+ List blocked;
+
+ /// keys we dont know about. the stub may write more than we read, and
+ /// writing the file back must not lose them
+ Map extra;
+
+ factory UpdateState.fromJson(Map j) {
+ final known = {"exe", "current", "previous", "failed_starts", "blocked"};
+ final blocked = [];
+ final raw = j["blocked"];
+ if (raw is List) {
+ for (final b in raw) {
+ final n = _int(b);
+ if (n != null && !blocked.contains(n)) blocked.add(n);
+ }
+ }
+
+ return UpdateState(
+ exe: j["exe"] is String ? j["exe"] as String : null,
+ current: _int(j["current"]),
+ previous: _int(j["previous"]),
+ failedStarts: _int(j["failed_starts"]) ?? 0,
+ blocked: blocked,
+ extra: {
+ for (final e in j.entries)
+ if (e.key is String && !known.contains(e.key)) e.key as String: e.value,
+ },
+ );
+ }
+
+ Map toJson() => {
+ ...extra,
+ if (exe != null) "exe": exe,
+ "current": current,
+ "previous": previous,
+ "failed_starts": failedStarts,
+ "blocked": blocked,
+ };
+}
+
+class StateFile {
+ StateFile(this.file);
+
+ final File file;
+
+ /// null when its missing, half written or not ours. Says which on the
+ /// console, never throws.
+ UpdateState? read() {
+ final j = _readObject(file);
+ return j == null ? null : UpdateState.fromJson(j);
+ }
+
+ /// Write to a temp file beside it, then rename over the top, so a reader
+ /// never sees half a file.
+ bool write(UpdateState state) => _writeObject(file, state.toJson());
+
+ /// Read, change, write. Without [createIfMissing] it does nothing when the
+ /// file cant be read, rather than writing an empty state over whatever the
+ /// stub had in there. The mac owns its file so it passes true, a damaged
+ /// one just gets started again.
+ bool update(void Function(UpdateState s) change, {bool createIfMissing = false}) {
+ var state = read();
+ if (state == null) {
+ if (!createIfMissing) return false;
+ state = UpdateState();
+ }
+ change(state);
+ return write(state);
+ }
+}
+
+/// What one person on the machine knows about the install, for when the
+/// install itself is somewhere they cant write (Program Files). The stub
+/// keeps it in `%LOCALAPPDATA%\\garage_updates.json` and it only
+/// ever exists for an install like that.
+class UserState {
+ UserState({
+ this.failedStarts = 0,
+ List? blocked,
+ this.forCurrent,
+ this.runInstead,
+ }) : blocked = blocked ?? [];
+
+ int failedStarts;
+
+ /// builds that failed 3 starts for this user
+ List blocked;
+
+ /// the `current` of the install the count was made against
+ int? forCurrent;
+
+ /// the build the stub starts for this user instead of `current`
+ int? runInstead;
+
+ factory UserState.fromJson(Map j) {
+ final blocked = [];
+ final raw = j["blocked"];
+ if (raw is List) {
+ for (final b in raw) {
+ final n = _int(b);
+ if (n != null && !blocked.contains(n)) blocked.add(n);
+ }
+ }
+ final count = _int(j["failed_starts"]) ?? 0;
+
+ return UserState(
+ failedStarts: count < 0 ? 0 : count,
+ blocked: blocked,
+ forCurrent: _int(j["for_current"]),
+ runInstead: _int(j["run_instead"]),
+ );
+ }
+
+ Map toJson() => {
+ "failed_starts": failedStarts,
+ "blocked": blocked,
+ "for_current": forCurrent,
+ "run_instead": runInstead,
+ };
+
+ /// The count and the build to run instead only mean anything for the
+ /// `current` they were made against. Once an update has gone in they start
+ /// again, what got blocked stays blocked. Same rule as the stub.
+ void settleFor(int? current) {
+ if (forCurrent == current) return;
+ forCurrent = current;
+ failedStarts = 0;
+ runInstead = null;
+ }
+}
+
+class UserStateFile {
+ UserStateFile(this.file);
+
+ final File file;
+
+ UserState? read() {
+ final j = _readObject(file);
+ return j == null ? null : UserState.fromJson(j);
+ }
+
+ bool write(UserState state) => _writeObject(file, state.toJson());
+
+ /// Same deal as [StateFile.update]. The app never passes
+ /// [createIfMissing], starting this file is the stubs job.
+ bool update(void Function(UserState s) change, {bool createIfMissing = false}) {
+ var state = read();
+ if (state == null) {
+ if (!createIfMissing) return false;
+ state = UserState();
+ }
+ change(state);
+ return write(state);
+ }
+}
+
+Map? _readObject(File file) {
+ try {
+ if (!file.existsSync()) return null;
+ final text = file.readAsStringSync();
+ if (text.trim().isEmpty) {
+ print("[garage_updates] ${file.path} is empty");
+ return null;
+ }
+ final j = jsonDecode(text);
+ if (j is! Map) {
+ print("[garage_updates] ${file.path} isnt an object");
+ return null;
+ }
+ return j;
+ } catch (e) {
+ // most likely caught mid write by the other side
+ print("[garage_updates] couldnt read ${file.path}: $e");
+ return null;
+ }
+}
+
+bool _writeObject(File file, Map json) {
+ final tmp = File("${file.path}.tmp");
+ try {
+ file.parent.createSync(recursive: true);
+ tmp.writeAsStringSync(const JsonEncoder.withIndent(" ").convert(json), flush: true);
+ tmp.renameSync(file.path);
+ return true;
+ } catch (e, st) {
+ print("[garage_updates] couldnt write ${file.path}: $e\n$st");
+ try {
+ if (tmp.existsSync()) tmp.deleteSync();
+ } catch (e2) {
+ print("[garage_updates] and couldnt clear up ${tmp.path}: $e2");
+ }
+ return false;
+ }
+}
+
+int? _int(Object? v) {
+ if (v is int) return v;
+ if (v is double && v.isFinite) return v.toInt();
+ if (v is String) return int.tryParse(v.trim());
+ return null;
+}
diff --git a/garage_updates/lib/src/core/web.dart b/garage_updates/lib/src/core/web.dart
new file mode 100644
index 0000000..9d8153b
--- /dev/null
+++ b/garage_updates/lib/src/core/web.dart
@@ -0,0 +1,4 @@
+// the web's half of core: nothing. a site is updated by deploying it
+
+/// false on the web, where theres nothing to update
+const bool kUpdatesSupported = false;
diff --git a/garage_updates/lib/src/core/windows_installer.dart b/garage_updates/lib/src/core/windows_installer.dart
new file mode 100644
index 0000000..83cb9c7
--- /dev/null
+++ b/garage_updates/lib/src/core/windows_installer.dart
@@ -0,0 +1,294 @@
+import "dart:io";
+
+import "installer.dart";
+import "models.dart";
+import "state.dart";
+
+// Windows. The app never unpacks anything itself, the stub in does:
+//
+// \.exe the stub
+// \app-\... a version folder, we are running out of one
+// \garage_updates.json state, the stubs and ours
+//
+// An install in Program Files cant be written by whoever is running the app,
+// so there the stub keeps the count of starts in a file of the users own
+// (see [UserState]). Everything read here is the two put together.
+//
+// All this side does is hand the stub a verified zip (`--garage-apply`), with
+// a UAC prompt in front of it when is in Program Files, and then start
+// the stub again so it launches the new folder.
+
+class WindowsInstaller implements Installer {
+ WindowsInstaller({
+ required this.root,
+ required this.stub,
+ required this.runningFolderBuild,
+ Map? environment,
+ ProcessRunner? run,
+ ProcessStarter? start,
+ bool Function()? rootWritable,
+ }) : _env = environment ?? Platform.environment,
+ _run = run ?? defaultRunner,
+ _start = start ?? defaultStarter,
+ _rootWritableOverride = rootWritable;
+
+ final Directory root;
+ final File stub;
+
+ /// the number off the `app-` folder this process lives in
+ final int runningFolderBuild;
+
+ final Map _env;
+ final ProcessRunner _run;
+ final ProcessStarter _start;
+ final bool Function()? _rootWritableOverride;
+
+ late final StateFile state = StateFile(File(joinPath(root.path, "garage_updates.json")));
+
+ static final _versionFolder = RegExp(r"^app-(\d+)$");
+
+ static InstallDetection locate(String executable, {Map? environment}) {
+ final folder = File(executable).parent;
+ final m = _versionFolder.firstMatch(baseName(folder.path));
+ if (m == null) {
+ return InstallDetection.none("${baseName(executable)} isn't running out of an app- folder");
+ }
+
+ final root = folder.parent;
+ final stateFile = File(joinPath(root.path, "garage_updates.json"));
+ if (!stateFile.existsSync()) {
+ return const InstallDetection.none("there's no garage_updates.json beside the version folder");
+ }
+
+ final stub = _findStub(root, StateFile(stateFile).read(), executable);
+ if (stub == null) {
+ return const InstallDetection.none("there's no stub exe beside the version folder");
+ }
+
+ return InstallDetection.found(WindowsInstaller(
+ root: root,
+ stub: stub,
+ runningFolderBuild: int.parse(m.group(1)!),
+ environment: environment,
+ ));
+ }
+
+ // the stub carries the apps exe name. a helper (stash-agent.exe) isnt named
+ // after it, so the state file is asked first and our own name second
+ static File? _findStub(Directory root, UpdateState? state, String executable) {
+ final names = [
+ if (state?.exe != null) baseName(state!.exe!),
+ baseName(executable),
+ ];
+ for (final n in names) {
+ final f = File(joinPath(root.path, n));
+ if (f.existsSync()) return f;
+ }
+
+ try {
+ final exes = root
+ .listSync()
+ .whereType()
+ .where((f) => f.path.toLowerCase().endsWith(".exe"))
+ .toList();
+ if (exes.length == 1) return exes.single;
+ } catch (e) {
+ print("[garage_updates] couldnt look for the stub in ${root.path}: $e");
+ }
+ return null;
+ }
+
+ @override
+ String get platform => "windows";
+
+ @override
+ bool get exitsOnRestart => true;
+
+ /// "just me" installs are, Program Files isnt
+ bool get rootWritable {
+ final over = _rootWritableOverride;
+ if (over != null) return over();
+
+ final probe = File(joinPath(root.path, ".garage_updates_probe"));
+ try {
+ probe.writeAsStringSync("");
+ probe.deleteSync();
+ return true;
+ } on FileSystemException {
+ // the expected answer for Program Files, not worth a line in the log
+ return false;
+ }
+ }
+
+ /// The installer may leave `app_id` in the state file, otherwise the
+ /// folders name does.
+ String get appId {
+ final id = state.read()?.extra["app_id"];
+ // the stub wont make a folder out of one with these in, so neither do we
+ if (id is String && id.trim().isNotEmpty && !id.contains(RegExp("[\\\\/:*?\"<>|]"))) return id.trim();
+ return baseName(root.path);
+ }
+
+ /// `%LOCALAPPDATA%\\garage_updates.json`, the stubs count of starts
+ /// for this user when it couldnt write the one in root. The file is only
+ /// there for an install like that, we never make it.
+ UserStateFile? get userState {
+ final local = _env["LOCALAPPDATA"];
+ if (local == null || local.isEmpty) return null;
+ return UserStateFile(File(joinPath(local, appId, "garage_updates.json")));
+ }
+
+ UserState? _mine(UpdateState? rootState) {
+ final mine = userState?.read();
+ mine?.settleFor(rootState?.current);
+ return mine;
+ }
+
+
+ /// The build the stub starts for this user. `current`, unless that one
+ /// kept dying on them and the stub went back a build without being able to
+ /// say so in root.
+ int? get startsBuild {
+ final s = state.read();
+ final other = _mine(s)?.runInstead;
+ if (other != null && other != s?.current && Directory(joinPath(root.path, "app-$other")).existsSync()) {
+ return other;
+ }
+ return s?.current;
+ }
+
+ @override
+ Directory get staging {
+ if (rootWritable) return Directory(joinPath(root.path, "staging"));
+
+ final local = _env["LOCALAPPDATA"];
+ if (local == null || local.isEmpty) {
+ print("[garage_updates] no LOCALAPPDATA, staging in the temp folder");
+ return Directory(joinPath(Directory.systemTemp.path, appId, "staging"));
+ }
+ return Directory(joinPath(local, appId, "staging"));
+ }
+
+ @override
+ List blockedBuilds() {
+ final s = state.read();
+ final out = [...?s?.blocked];
+ // what failed for this user, on an install they cant write to
+ for (final b in _mine(s)?.blocked ?? const []) {
+ if (!out.contains(b)) out.add(b);
+ }
+ return out;
+ }
+
+ @override
+ Future apply(File archive, UpdateRelease release, {required int runningBuild}) async {
+ if (release.asset.format != "zip") {
+ throw UpdateError("format", "A windows release has to be a zip, not ${release.asset.format}");
+ }
+
+ final args = ["--garage-apply", archive.path, "${release.build}"];
+ final ProcessResult res;
+ if (rootWritable) {
+ res = await _run(stub.path, args);
+ } else {
+ // one UAC prompt. powershell is only the thing that can ask for it
+ res = await _run(powershellPath(_env), elevationArgs(stub.path, args));
+ }
+
+ if (res.exitCode != 0) {
+ print("[garage_updates] the stub exited ${res.exitCode}\n${res.stdout}\n${res.stderr}");
+ if (res.exitCode == kElevationRefused) {
+ throw UpdateError("elevation_refused", "Administrator permission was not given");
+ }
+ throw UpdateError("install_failed", "The update could not be installed (${res.exitCode})");
+ }
+
+ // belt and braces. a stub that said 0 but didnt move `current` would have
+ // us restart straight back into the old build, forever
+ final now = state.read();
+ if (now != null && now.current != release.build) {
+ throw UpdateError("install_failed", "The update did not take, still on build ${now.current}");
+ }
+
+ try {
+ if (archive.existsSync()) archive.deleteSync();
+ } catch (e) {
+ print("[garage_updates] couldnt remove ${archive.path} after installing it: $e");
+ }
+ }
+
+ @override
+ Future relaunch(List args) => _start(stub.path, args);
+
+ /// the stub counts starts on windows, before it launches us
+ @override
+ Future noteStart(int build) async => false;
+
+ @override
+ Future markHealthy() async {
+ final s = state.read();
+ if (s != null && s.failedStarts != 0) state.update((s) => s.failedStarts = 0);
+
+ // the stub counted in here instead if it couldnt write to root
+ final mine = userState;
+ final u = mine?.read();
+ if (mine != null && u != null && u.failedStarts != 0) mine.update((u) => u.failedStarts = 0);
+ }
+}
+
+/// ERROR_CANCELLED, what windows gives when the UAC prompt is turned down
+const kElevationRefused = 1223;
+
+String powershellPath(Map env) {
+ final sys = env["SystemRoot"] ?? env["SYSTEMROOT"] ?? env["windir"];
+ if (sys != null && sys.isNotEmpty) {
+ final full = "$sys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
+ if (File(full).existsSync()) return full;
+ }
+ return "powershell";
+}
+
+/// The powershell command line that runs [exe] elevated and passes its exit
+/// code back out. Start-Process -Verb RunAs is ShellExecute "runas".
+List elevationArgs(String exe, List args) {
+ final line = args.map(windowsQuoteArg).join(" ");
+ // without the try a refused prompt leaves $p null and powershell exits 0
+ final script = "\$ErrorActionPreference = 'Stop'; "
+ "try { "
+ "\$p = Start-Process -FilePath ${powershellQuote(exe)} -ArgumentList ${powershellQuote(line)} "
+ "-Verb RunAs -Wait -PassThru -WindowStyle Hidden; "
+ "exit \$p.ExitCode "
+ "} catch { [Console]::Error.WriteLine(\$_); exit $kElevationRefused }";
+
+ return ["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command", script];
+}
+
+/// a single quoted powershell string, nothing inside it is expanded
+String powershellQuote(String s) => "'${s.replaceAll("'", "''")}'";
+
+/// One argument the way CommandLineToArgvW wants it. Backslashes only matter
+/// in front of a quote, which is the bit everyone gets wrong with a path that
+/// ends in one.
+String windowsQuoteArg(String arg) {
+ if (arg.isNotEmpty && !arg.contains(RegExp("[ \t\n\"]"))) return arg;
+
+ final out = StringBuffer("\"");
+ var slashes = 0;
+ for (final ch in arg.split("")) {
+ if (ch == "\\") {
+ slashes++;
+ continue;
+ }
+ if (ch == "\"") {
+ out.write("\\" * (slashes * 2 + 1));
+ out.write("\"");
+ } else {
+ out.write("\\" * slashes);
+ out.write(ch);
+ }
+ slashes = 0;
+ }
+ out.write("\\" * (slashes * 2));
+ out.write("\"");
+ return out.toString();
+}
diff --git a/garage_updates/lib/src/platform/android_installer.dart b/garage_updates/lib/src/platform/android_installer.dart
new file mode 100644
index 0000000..7201821
--- /dev/null
+++ b/garage_updates/lib/src/platform/android_installer.dart
@@ -0,0 +1,83 @@
+import "dart:io";
+
+import "package:flutter/foundation.dart";
+import "package:flutter/services.dart";
+
+import "../core/installer.dart";
+import "../core/models.dart";
+
+// Android. The apk is downloaded into the apps cache and handed to the system
+// installer, which always asks. It also does the restarting, so theres no
+// relaunch and no fallback here - a build that wont start is androids problem.
+
+const _channel = MethodChannel("net.imbenji.garage_updates");
+
+const _playStore = "com.android.vending";
+
+class AndroidInstaller implements Installer {
+ AndroidInstaller(this.cacheDir);
+
+ final Directory cacheDir;
+
+ static Future locate() async {
+ if (!kReleaseMode) {
+ // a debug apk is signed with the debug key, a release wouldnt install
+ // over it anyway
+ return const InstallDetection.none("this isn't a release build");
+ }
+
+ final Map? info;
+ try {
+ info = await _channel.invokeMapMethod("info");
+ } catch (e, st) {
+ print("[garage_updates] couldnt ask android about the install: $e\n$st");
+ return const InstallDetection.none("the garage_updates plugin didn't answer");
+ }
+
+ if (info?["installer"] == _playStore) {
+ return const InstallDetection.none("installed from the Play Store, which does the updating");
+ }
+
+ final cache = info?["cacheDir"];
+ if (cache is! String || cache.isEmpty) {
+ return const InstallDetection.none("android gave no cache folder to download into");
+ }
+ return InstallDetection.found(AndroidInstaller(Directory(cache)));
+ }
+
+ @override
+ String get platform => "android";
+
+ @override
+ bool get exitsOnRestart => false;
+
+ // has to match the cache-path in the plugins file provider xml
+ @override
+ Directory get staging => Directory("${cacheDir.path}/garage_updates");
+
+ @override
+ List blockedBuilds() => const [];
+
+ @override
+ Future apply(File archive, UpdateRelease release, {required int runningBuild}) async {
+ if (release.asset.format != "apk") {
+ throw UpdateError("format", "An android release has to be an apk, not ${release.asset.format}");
+ }
+
+ try {
+ await _channel.invokeMethod("install", {"path": archive.path});
+ } on PlatformException catch (e, st) {
+ print("[garage_updates] the system installer wouldnt open: $e\n$st");
+ throw UpdateError("install_failed", e.message ?? "The installer could not be opened");
+ }
+ }
+
+ @override
+ Future relaunch(List args) async {}
+
+ @override
+ Future noteStart(int build) async => false;
+
+ @override
+ Future markHealthy() async {}
+}
diff --git a/garage_updates/lib/src/platform/driver.dart b/garage_updates/lib/src/platform/driver.dart
new file mode 100644
index 0000000..557bf54
--- /dev/null
+++ b/garage_updates/lib/src/platform/driver.dart
@@ -0,0 +1 @@
+export "driver_io.dart" if (dart.library.js_interop) "driver_stub.dart";
diff --git a/garage_updates/lib/src/platform/driver_io.dart b/garage_updates/lib/src/platform/driver_io.dart
new file mode 100644
index 0000000..47a4dfd
--- /dev/null
+++ b/garage_updates/lib/src/platform/driver_io.dart
@@ -0,0 +1,31 @@
+import "dart:io";
+
+import "../core/engine.dart";
+import "../core/models.dart";
+import "android_installer.dart";
+
+/// The engine for whatever this is running on. null where the package has
+/// nothing to do at all (linux, ios).
+Future openDriver({
+ required String project,
+ required int build,
+ required String apiBase,
+}) async {
+ if (Platform.isWindows || Platform.isMacOS) {
+ return UpdateEngine.detect(project: project, build: build, apiBase: apiBase);
+ }
+
+ if (Platform.isAndroid) {
+ // core cant do android, installing an apk goes through the plugin
+ final found = await AndroidInstaller.locate();
+ return UpdateEngine(
+ project: project,
+ build: build,
+ apiBase: apiBase,
+ installer: found.installer,
+ notInstalledReason: found.reason,
+ );
+ }
+
+ return null;
+}
diff --git a/garage_updates/lib/src/platform/driver_stub.dart b/garage_updates/lib/src/platform/driver_stub.dart
new file mode 100644
index 0000000..1021ecf
--- /dev/null
+++ b/garage_updates/lib/src/platform/driver_stub.dart
@@ -0,0 +1,10 @@
+import "../core/models.dart";
+
+// the web's half. nothing to update, so no driver
+
+Future openDriver({
+ required String project,
+ required int build,
+ required String apiBase,
+}) async =>
+ null;
diff --git a/garage_updates/lib/src/splash.dart b/garage_updates/lib/src/splash.dart
new file mode 100644
index 0000000..282f222
--- /dev/null
+++ b/garage_updates/lib/src/splash.dart
@@ -0,0 +1,186 @@
+import "dart:async";
+
+import "package:flutter/foundation.dart";
+import "package:flutter/widgets.dart";
+import "package:garage_ui/garage_ui.dart";
+
+import "branding.dart";
+
+// What's on screen before the app's own runApp. A fixed layout and nothing to
+// configure but the logo and the name: logo, name, one status line, a bar,
+// and when a required update wont go in, why and a Retry.
+
+enum SplashStage { checking, downloading, installing, starting }
+
+class SplashController extends ChangeNotifier {
+ SplashStage _stage = SplashStage.checking;
+ double? _progress;
+ String? _error;
+ Completer? _retry;
+
+ SplashStage get stage => _stage;
+
+ /// 0 to 1 while theres a number to show, null = busy
+ double? get progress => _progress;
+
+ /// set when a required update failed. the Retry button shows with it
+ String? get error => _error;
+
+ String get statusLine => switch (_stage) {
+ SplashStage.checking => "Checking for updates",
+ SplashStage.downloading => "Downloading update",
+ SplashStage.installing => "Installing",
+ SplashStage.starting => "Starting",
+ };
+
+ void show(SplashStage stage, {double? progress}) {
+ _stage = stage;
+ _progress = progress;
+ _error = null;
+ notifyListeners();
+ }
+
+ set progress(double? v) {
+ if (v == _progress) return;
+ _progress = v;
+ notifyListeners();
+ }
+
+ /// Puts the error up and waits for Retry to be pressed.
+ Future fail(String message) {
+ _error = message;
+ // a bar sweeping away under an error reads as still trying
+ _progress ??= 0;
+ final c = _retry = Completer();
+ notifyListeners();
+ return c.future;
+ }
+
+ void retry() {
+ final c = _retry;
+ _retry = null;
+ _error = null;
+ notifyListeners();
+ if (c != null && !c.isCompleted) c.complete();
+ }
+}
+
+class UpdateSplash extends StatelessWidget {
+ const UpdateSplash({required this.branding, required this.controller, super.key});
+
+ final UpdaterBranding branding;
+ final SplashController controller;
+
+ @override
+ Widget build(BuildContext context) {
+ final density = GarageTheme.of(context).density;
+ final logo = branding.buildLogo();
+
+ return Scaffold(
+ child: Center(
+ child: SizedBox(
+ width: density.fontSize * 22,
+ child: ListenableBuilder(
+ listenable: controller,
+ builder: (context, _) {
+ final error = controller.error;
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (logo != null) ...[
+ SizedBox.square(dimension: density.controlHeight * 2, child: logo),
+ const Gap.lg(),
+ ],
+ Text(branding.name).large().semiBold(),
+ const Gap.sm(),
+ Text(controller.statusLine).muted(),
+ const Gap.lg(),
+
+ // the bar has no width of its own, it takes the columns
+ SizedBox(
+ width: double.infinity,
+ child: LinearProgressIndicator(value: controller.progress),
+ ),
+ if (error != null) ...[
+ const Gap.xl(),
+ Text(error).muted(),
+ const Gap.md(),
+ Button(
+ style: const ButtonStyle.outline(),
+ onPressed: controller.retry,
+ child: const Text("Retry"),
+ ),
+ ],
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+
+/// The tiny app `launch` runs to get the splash on screen. The host app's own
+/// runApp replaces it, and [onGone] is how the updater finds out it has.
+class UpdateSplashApp extends StatefulWidget {
+ const UpdateSplashApp({
+ required this.branding,
+ required this.controller,
+ this.onGone,
+ super.key,
+ });
+
+ final UpdaterBranding branding;
+ final SplashController controller;
+ final VoidCallback? onGone;
+
+ static final defaultTheme = ThemeData(
+ colorScheme: GarageSchemes.carbon,
+ density: const Density.product(),
+ );
+
+ @override
+ State createState() => _UpdateSplashAppState();
+}
+
+class _UpdateSplashAppState extends State {
+ late final _delegate = _SplashDelegate(
+ (context) => UpdateSplash(branding: widget.branding, controller: widget.controller),
+ );
+ late final _router = RouterConfig