Skip to content

Commit f4bfce4

Browse files
committed
Update: add Windows updater launch fallback when RunAs fails
1 parent 7c8ee23 commit f4bfce4

1 file changed

Lines changed: 52 additions & 13 deletions

File tree

app/lib/services/update_service.dart

Lines changed: 52 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,8 @@ class UpdateService {
121121
if (started) {
122122
exit(0);
123123
}
124-
throw StateError('update launch cancelled or failed');
124+
throw StateError(
125+
'update launch cancelled or failed (PowerShell not started)');
125126
}
126127
if (Platform.isLinux) {
127128
final started = await _launchLinuxTerminal(command, relaunchPath);
@@ -374,18 +375,56 @@ class UpdateService {
374375
final encoded = base64.encode(_utf16LeBytes(wrapped.toString()));
375376
final argList =
376377
'-NoExit -NoProfile -ExecutionPolicy Bypass -EncodedCommand $encoded';
377-
final launcher = await Process.run(
378-
'powershell',
379-
[
380-
'-NoProfile',
381-
'-ExecutionPolicy',
382-
'Bypass',
383-
'-Command',
384-
r"$ErrorActionPreference='Stop'; Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList $args[0] -PassThru | Out-Null",
385-
argList,
386-
],
387-
);
388-
return launcher.exitCode == 0;
378+
try {
379+
final launcher = await Process.run(
380+
'powershell',
381+
[
382+
'-NoProfile',
383+
'-ExecutionPolicy',
384+
'Bypass',
385+
'-Command',
386+
r"$ErrorActionPreference='Stop'; Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList $args[0] -PassThru | Out-Null",
387+
argList,
388+
],
389+
);
390+
if (launcher.exitCode == 0) return true;
391+
} catch (_) {
392+
// Fall through to non-elevated launcher.
393+
}
394+
// Fallback: some environments block RunAs invocation from sandboxed process.
395+
// The update script can still run as current user and handles best-effort install.
396+
return _launchWindowsDirect(command, relaunchPath);
397+
}
398+
399+
Future<bool> _launchWindowsDirect(String command, String? relaunchPath) async {
400+
final wrapped = StringBuffer()
401+
..writeln(r'$ErrorActionPreference = "Stop"')
402+
..writeln(command)
403+
..writeln(r'$exitCode = $LASTEXITCODE')
404+
..writeln(r'if ($exitCode -eq $null) { $exitCode = 0 }');
405+
if (relaunchPath != null && relaunchPath.trim().isNotEmpty) {
406+
final escaped = relaunchPath.replaceAll("'", "''");
407+
wrapped.writeln(
408+
"if (\$exitCode -eq 0) { Start-Process -FilePath '$escaped' }");
409+
}
410+
wrapped.writeln(r'exit $exitCode');
411+
try {
412+
await Process.start(
413+
'powershell',
414+
[
415+
'-NoExit',
416+
'-NoProfile',
417+
'-ExecutionPolicy',
418+
'Bypass',
419+
'-Command',
420+
wrapped.toString(),
421+
],
422+
mode: ProcessStartMode.detached,
423+
);
424+
return true;
425+
} catch (_) {
426+
return false;
427+
}
389428
}
390429

391430
Uint8List _utf16LeBytes(String value) {

0 commit comments

Comments
 (0)