feat(garage_updates): an auto updater for garage apps

Asks Garage for the newest release of a project, downloads it with resume,
checks the sha256, installs it beside the old one and restarts into it.
Splash on garage_ui, a native stub and a first time installer for windows,
bundle swap on mac, the system installer on android. No-op on web.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KHotisA4hV2xmuZsHTksFX
This commit is contained in:
ImBenji
2026-10-12 06:37:02 +01:00
co-authored by Claude Opus 5.5
parent 444933b004
commit d3b232f0ee
56 changed files with 9031 additions and 0 deletions
@@ -0,0 +1,164 @@
import "dart:io";
import "package:garage_updates/core.dart";
// A pretend windows install in a temp folder. The "stub" is a shell script
// with the stubs name: it writes down the arguments it was given, and for
// --garage-apply does the bookkeeping the real one would.
const _stubScript = r'''#!/bin/sh
dir="$(cd "$(dirname "$0")" && pwd)"
printf '%s\n' "$@" >> "$dir/stub-args.txt"
echo "--" >> "$dir/stub-args.txt"
if [ "$1" = "--garage-apply" ]; then
if [ -f "$dir/stub-exit" ]; then
exit "$(cat "$dir/stub-exit")"
fi
if [ ! -f "$dir/stub-lazy" ]; then
mkdir -p "$dir/app-$3"
cp "$2" "$dir/app-$3/unpacked-from.zip"
printf '{ "exe": "garage_stash.exe", "current": %s, "previous": 12, "failed_starts": 0, "blocked": [] }' "$3" > "$dir/garage_updates.json"
fi
fi
exit 0
''';
class FakeWindowsInstall {
FakeWindowsInstall._(this.tmp);
final Directory tmp;
Directory get root => Directory("${tmp.path}/Garage Stash");
Directory get versionFolder => Directory("${root.path}/app-12");
File get stub => File("${root.path}/garage_stash.exe");
File get exe => File("${versionFolder.path}/garage_stash.exe");
File get stateFile => File("${root.path}/garage_updates.json");
File get argsFile => File("${root.path}/stub-args.txt");
static FakeWindowsInstall create({String? state}) {
final f = FakeWindowsInstall._(Directory.systemTemp.createTempSync("gu_win_"));
f.versionFolder.createSync(recursive: true);
f.exe.writeAsStringSync("the real app, build 12");
File("${f.versionFolder.path}/stash-agent.exe").writeAsStringSync("the agent");
f.stub.writeAsStringSync(_stubScript);
Process.runSync("/bin/chmod", ["+x", f.stub.path]);
f.stateFile.writeAsStringSync(
state ?? '{ "exe": "garage_stash.exe", "current": 12, "previous": 9, "failed_starts": 1, "blocked": [11] }',
);
return f;
}
/// what LOCALAPPDATA is for an installer made by [installer]
Directory get local => Directory("${tmp.path}/Local");
File get userStateFile => File("${local.path}/Garage Stash/garage_updates.json");
/// `readOnly` is an install in Program Files. Nothing is chmodded, the
/// installer is just told it cant write, and [plainLaunch] behaves the same
WindowsInstaller installer({bool readOnly = false}) => WindowsInstaller(
root: root,
stub: stub,
runningFolderBuild: 12,
environment: {"LOCALAPPDATA": local.path},
rootWritable: () => !readOnly,
);
/// The stub being started with no flags, as far as the counting goes: the
/// same sums garage_stub.cpp does, in root when it can write there and in
/// the users own file when it cant. Returns the build it would start.
int plainLaunch({bool readOnly = false}) {
final state = StateFile(stateFile);
final s = state.read()!;
bool there(int? build) => build != null && Directory("${root.path}/app-$build").existsSync();
if (!readOnly) {
if (s.failedStarts >= 3 && there(s.previous)) {
if (!s.blocked.contains(s.current)) s.blocked.add(s.current!);
s.current = s.previous;
s.previous = null;
s.failedStarts = 0;
}
s.failedStarts++;
state.write(s);
return s.current!;
}
final mine = UserStateFile(userStateFile);
final u = mine.read() ?? UserState();
u.settleFor(s.current);
if (u.runInstead != null) {
if (u.runInstead != s.current && there(u.runInstead)) return u.runInstead!;
u.runInstead = null;
u.failedStarts = 0;
}
var run = s.current!;
if (u.failedStarts >= 3 && there(s.previous) && s.previous != s.current && !u.blocked.contains(s.previous)) {
if (!u.blocked.contains(s.current)) u.blocked.add(s.current!);
u.runInstead = s.previous;
u.failedStarts = 0;
run = s.previous!;
}
if (run == s.current) u.failedStarts++;
mine.write(u);
return run;
}
/// every run of the stub, as the list of arguments it got
List<List<String>> get runs {
if (!argsFile.existsSync()) return [];
final out = <List<String>>[];
var cur = <String>[];
for (final line in argsFile.readAsLinesSync()) {
if (line == "--") {
out.add(cur);
cur = <String>[];
} else {
cur.add(line);
}
}
return out;
}
void dispose() {
// a test may have made the root read only
Process.runSync("/bin/chmod", ["-R", "u+w", tmp.path]);
tmp.deleteSync(recursive: true);
}
}
/// A pretend mac app. `Foo.app/Contents/{Info.plist, MacOS/Foo}` with a
/// marker file so a test can tell which build is sitting where.
Directory makeApp(Directory parent, {String name = "Foo.app", String id = "net.imbenji.foo", required String marker}) {
final app = Directory("${parent.path}/$name");
Directory("${app.path}/Contents/MacOS").createSync(recursive: true);
Directory("${app.path}/Contents/Resources").createSync(recursive: true);
File("${app.path}/Contents/Info.plist").writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>Foo</string>
<key>CFBundleIdentifier</key>
<string>$id</string>
</dict>
</plist>
''');
File("${app.path}/Contents/MacOS/Foo").writeAsStringSync("#!/bin/sh\necho $marker\n");
File("${app.path}/Contents/Resources/marker.txt").writeAsStringSync(marker);
return app;
}
String markerOf(Directory app) => File("${app.path}/Contents/Resources/marker.txt").readAsStringSync();
/// zips [app] the way a release would be, with the .app at the top
File zipApp(Directory app, File to) {
final res = Process.runSync("/usr/bin/ditto", ["-c", "-k", "--keepParent", app.path, to.path]);
if (res.exitCode != 0) throw StateError("ditto couldnt zip ${app.path}: ${res.stderr}");
return to;
}
@@ -0,0 +1,154 @@
import "dart:async";
import "dart:convert";
import "dart:io";
import "dart:typed_data";
import "package:crypto/crypto.dart";
import "package:garage_updates/core.dart";
/// A file server on loopback that can be told to misbehave.
class FakeServer {
FakeServer._(this._server, this.data);
final HttpServer _server;
Uint8List data;
/// "GET /blob bytes=100-" for every request, in order
final List<String> log = [];
/// send a plain 200 with the whole file whatever Range says
bool ignoreRange = false;
/// how many of the next downloads to cut dead, and after how many bytes
int cutsLeft = 0;
int cutAfter = 0;
/// the json `/v1/updates/<pid>` answers with, and the status it uses
Object? updateBody;
int updateStatus = 200;
/// a /blob request without this sig gets a 403, like an expired presign
String? wantSig;
int _sig = 0;
String get base => "http://127.0.0.1:${_server.port}";
static Future<FakeServer> start(List<int> data) async {
final s = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final fake = FakeServer._(s, Uint8List.fromList(data));
s.listen(fake._handle);
return fake;
}
Future<void> close() => _server.close(force: true);
String get sha => sha256.convert(data).toString();
UpdateRelease release({int build = 13, String path = "/blob", String format = "zip", String? sha256}) {
return UpdateRelease(
label: "v$build",
build: build,
notes: "notes for $build",
asset: UpdateAsset(
url: "$base$path",
filename: "app.$format",
format: format,
size: data.length,
sha256: sha256 ?? sha,
),
);
}
Future<void> _handle(HttpRequest req) async {
final range = req.headers.value(HttpHeaders.rangeHeader);
log.add("${req.method} ${req.uri.path}${range == null ? "" : " $range"}");
if (req.uri.path.startsWith("/v1/updates/")) {
req.response.statusCode = updateStatus;
req.response.headers.contentType = ContentType.json;
final body = updateBody;
req.response.write(body is String ? body : jsonEncode(body));
await req.response.close();
return;
}
if (req.uri.path == "/hosted") {
// a fresh "presigned" url every time, the old ones stop working
wantSig = "s${++_sig}";
req.response.statusCode = HttpStatus.found;
req.response.headers.set(HttpHeaders.locationHeader, "/blob?sig=$wantSig");
await req.response.close();
return;
}
if (req.uri.path == "/gone") {
req.response.statusCode = HttpStatus.notFound;
await req.response.close();
return;
}
if (wantSig != null && req.uri.queryParameters["sig"] != wantSig) {
req.response.statusCode = HttpStatus.forbidden;
await req.response.close();
return;
}
var start = 0;
var status = "200 OK";
final extra = <String>[];
if (range != null && !ignoreRange) {
start = int.parse(RegExp(r"bytes=(\d+)-").firstMatch(range)!.group(1)!);
if (start >= data.length) {
req.response.statusCode = HttpStatus.requestedRangeNotSatisfiable;
await req.response.close();
return;
}
status = "206 Partial Content";
extra.add("Content-Range: bytes $start-${data.length - 1}/${data.length}");
}
final body = Uint8List.sublistView(data, start);
// written by hand on the raw socket so it can be dropped mid body
final socket = await req.response.detachSocket(writeHeaders: false);
socket.write("HTTP/1.1 $status\r\n"
"Content-Length: ${body.length}\r\n"
"${extra.map((h) => "$h\r\n").join()}"
"Connection: close\r\n\r\n");
if (cutsLeft > 0) {
cutsLeft--;
socket.add(Uint8List.sublistView(body, 0, cutAfter.clamp(0, body.length)));
await socket.flush();
socket.destroy();
return;
}
socket.add(body);
await socket.flush();
await socket.close();
}
}
/// some bytes that arent all the same
List<int> noise(int length, {int seed = 7}) {
var x = seed;
return List<int>.generate(length, (_) {
x = (x * 1103515245 + 12345) & 0x7fffffff;
return x & 0xff;
});
}
/// runs [body] and hands back everything it printed
Future<List<String>> printsOf(Future<void> Function() body) async {
final lines = <String>[];
await runZonedPrints(body, lines);
return lines;
}
Future<void> runZonedPrints(Future<void> Function() body, List<String> into) {
return runZoned(
body,
zoneSpecification: ZoneSpecification(print: (self, parent, zone, line) => into.add(line)),
);
}