Repository navigation
Expand file tree
/
Copy pathSessionRuntimeInstaller.cs
More file actions
370 lines (340 loc) · 13.5 KB
/
Copy pathSessionRuntimeInstaller.cs
File metadata and controls
370 lines (340 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
using System.IO.Compression;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection.PortableExecutable;
using Microsoft.Win32;
using OpenClaw.SessionProtocol;
namespace OpenClaw.SessionHost;
/// <summary>
/// The <c>--install-runtime</c> mode: installs the packaged Node.js runtime
/// into this account's own profile.
/// </summary>
/// <remarks>
/// <para>
/// The host extracts its own copy into the invoking user's package LocalState,
/// which this account cannot read. The archive is package content and is
/// readable by both, so the agent extracts its own rather than being handed
/// files another identity owns.
/// </para>
/// <para>
/// Running extraction here means every file is created by the account that
/// will run it.
/// </para>
/// </remarks>
internal static class SessionRuntimeInstaller
{
private static readonly Guid LocalApplicationDataFolderId =
new("F1B32785-6FBA-4FCF-9D55-7B8E7F157091");
public static int Run(
string requestPath,
Func<string, string> readFile,
Action<string, string> writeFile,
Func<string>? getLocalApplicationData = null,
Func<string, bool>? tryPrependUserPath = null,
Func<string, string?>? getRuntimeVersion = null,
Func<string, string, string?>? stageNativeModules = null,
TextWriter? errorOutput = null)
{
string resultPath = SessionLaunchProtocol.ResultPathFor(requestPath);
string? requestId = null;
try
{
SessionRuntimeInstallRequest request =
SessionRuntimeProtocol.ReadRequest(readFile(requestPath));
requestId = request.RequestId;
string directory = Path.Combine(
(getLocalApplicationData ??
GetLocalApplicationData)(),
"OpenClawGatewayMSIX",
"agent-node");
string archiveRoot = Path.GetFileNameWithoutExtension(request.ArchivePath!);
string executablePath = Path.Combine(
directory,
archiveRoot,
"node.exe");
string expectedVersion = GetArchiveVersion(request.ArchivePath!);
if (!File.Exists(executablePath) ||
!string.Equals(
(getRuntimeVersion ?? ReadRuntimeVersion)(executablePath),
expectedVersion,
StringComparison.Ordinal))
{
string stagingDirectory = Path.Combine(
directory,
$"{archiveRoot}.extract-{Guid.NewGuid():N}");
try
{
Directory.CreateDirectory(directory);
ZipFile.ExtractToDirectory(request.ArchivePath!, stagingDirectory, false);
string stagedRoot = Path.Combine(stagingDirectory, archiveRoot);
string stagedExecutable = Path.Combine(stagedRoot, "node.exe");
if (!File.Exists(stagedExecutable))
{
throw new SessionLaunchException(
"The installed Node.js runtime did not contain node.exe.");
}
string targetRoot = Path.Combine(directory, archiveRoot);
if (Directory.Exists(targetRoot))
{
Directory.Delete(targetRoot, recursive: true);
}
Directory.Move(stagedRoot, targetRoot);
}
finally
{
if (Directory.Exists(stagingDirectory))
{
Directory.Delete(stagingDirectory, recursive: true);
}
}
}
if (!File.Exists(executablePath))
{
throw new SessionLaunchException(
"The installed Node.js runtime did not contain node.exe.");
}
string runtimeDirectory = Path.GetDirectoryName(executablePath)
?? throw new SessionLaunchException(
"The installed Node.js runtime has no executable directory.");
bool pathUpdated = request.UpdateUserPath &&
(tryPrependUserPath ?? TryPrependUserPath)(runtimeDirectory);
// Native dependencies are mirrored by the same account that will
// load them, for the same reason the runtime itself is.
string? nativeRootPath = (stageNativeModules ?? SessionNativeStager.Stage)(
request.ApplicationDirectory!,
(getLocalApplicationData ?? GetLocalApplicationData)());
writeFile(
resultPath,
SessionRuntimeProtocol.SerializeResult(new SessionRuntimeInstallResult
{
RequestId = requestId,
ExecutablePath = executablePath,
Version = expectedVersion,
ArchiveName = Path.GetFileName(request.ArchivePath!),
UserPathUpdated = pathUpdated,
NativeRootPath = nativeRootPath
}));
return 0;
}
catch (Exception exception) when (
exception is SessionLaunchException or IOException or
UnauthorizedAccessException or InvalidOperationException or
InvalidDataException or BadImageFormatException or
System.ComponentModel.Win32Exception)
{
TryWriteFailure(
writeFile,
resultPath,
requestId,
exception.Message,
errorOutput ?? Console.Error);
return SessionLaunchProtocol.HelperFailureExitCode;
}
}
private static string GetArchiveVersion(string archivePath)
{
string archiveName = Path.GetFileNameWithoutExtension(archivePath);
const string prefix = "node-v";
const string platformMarker = "-win-";
int platformIndex = archiveName.LastIndexOf(
platformMarker,
StringComparison.OrdinalIgnoreCase);
if (!archiveName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ||
platformIndex <= prefix.Length)
{
throw new SessionLaunchException(
$"The packaged Node.js runtime archive has an unexpected name: {archiveName}");
}
string version = archiveName[prefix.Length..platformIndex];
return Version.TryParse(version, out Version? parsed)
? parsed.ToString()
: throw new SessionLaunchException(
$"The packaged Node.js runtime archive has an invalid version: {archiveName}");
}
private static string GetLocalApplicationData()
{
int result = SHGetKnownFolderPath(
LocalApplicationDataFolderId,
flags: 0,
token: IntPtr.Zero,
out IntPtr path);
if (result < 0)
{
throw new SessionLaunchException(
$"Windows could not resolve the local application data directory " +
$"(HRESULT 0x{result:X8}).");
}
try
{
return Marshal.PtrToStringUni(path)
?? throw new SessionLaunchException(
"Windows returned an empty local application data directory.");
}
finally
{
Marshal.FreeCoTaskMem(path);
}
}
private static string? ReadRuntimeVersion(string executablePath)
{
try
{
// Refuse corrupt images before entering the loader, where Process.Start can block before its exit budget.
using FileStream image = File.Open(executablePath, FileMode.Open, FileAccess.Read, FileShare.Read);
using var executable = new PEReader(image);
if (executable.PEHeaders.PEHeader is null ||
!executable.PEHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.ExecutableImage) ||
executable.PEHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.Dll))
{
return null;
}
using Process? process = Process.Start(new ProcessStartInfo
{
FileName = executablePath,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
ArgumentList = { "--version" }
});
if (process is null || !process.WaitForExit(TimeSpan.FromSeconds(10)))
{
process?.Kill(entireProcessTree: true);
return null;
}
string output = process.StandardOutput.ReadToEnd().Trim();
return process.ExitCode == 0
? output.TrimStart('v')
: null;
}
catch (Exception exception) when (
exception is System.ComponentModel.Win32Exception or
InvalidOperationException or IOException or UnauthorizedAccessException or BadImageFormatException)
{
return null;
}
}
/// <summary>
/// Puts the runtime directory at the front of this account's persistent
/// user <c>PATH</c>.
/// </summary>
/// <remarks>
/// <para>
/// Prepended, not appended: a machine-wide Node.js installation is common,
/// and the packaged runtime is the one this installation supports.
/// </para>
/// <para>
/// This covers processes that build their environment from the registry.
/// It is not what governs the processes this package starts - those inherit
/// an environment - so it is deliberately paired with the launch-time
/// prepend rather than relied on alone.
/// </para>
/// <para>
/// Only this account's own hive is touched, never the machine's.
/// </para>
/// </remarks>
internal static bool TryPrependUserPath(string directory)
{
if (!OperatingSystem.IsWindows())
{
return false;
}
using RegistryKey? environment = Registry.CurrentUser.OpenSubKey(
"Environment", writable: true);
if (environment is null)
{
return false;
}
// GetValue expands REG_EXPAND_SZ by default, which would bake the
// current expansion of every %VAR% in the value back into the registry.
object? raw = environment.GetValue(
"Path", null, RegistryValueOptions.DoNotExpandEnvironmentNames);
string current = raw as string ?? string.Empty;
RegistryValueKind kind = raw is null
? RegistryValueKind.ExpandString
: environment.GetValueKind("Path");
string updated = BuildPath(current, directory);
if (string.Equals(updated, current, StringComparison.Ordinal))
{
return false;
}
environment.SetValue("Path", updated, kind);
return true;
}
/// <summary>
/// Builds the new value: the directory first, every unrelated entry after,
/// and any previous runtime directory dropped.
/// </summary>
/// <remarks>
/// A previous version's directory is removed rather than left in place, so
/// repeated setups across upgrades cannot accumulate stale runtimes ahead
/// of the current one.
/// </remarks>
internal static string BuildPath(string current, string directory)
{
string? previousRoot = Path.GetDirectoryName(directory);
List<string> entries = [directory];
foreach (string entry in current.Split(
Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
string trimmed = entry.Trim();
if (trimmed.Length == 0 ||
string.Equals(
trimmed.TrimEnd(Path.DirectorySeparatorChar),
directory.TrimEnd(Path.DirectorySeparatorChar),
StringComparison.OrdinalIgnoreCase) ||
IsPreviousRuntime(trimmed, previousRoot))
{
continue;
}
entries.Add(trimmed);
}
return string.Join(Path.PathSeparator, entries);
}
private static bool IsPreviousRuntime(string entry, string? runtimeRoot)
{
if (string.IsNullOrEmpty(runtimeRoot))
{
return false;
}
string parent = Path.GetDirectoryName(
entry.TrimEnd(Path.DirectorySeparatorChar)) ?? string.Empty;
return string.Equals(
parent.TrimEnd(Path.DirectorySeparatorChar),
runtimeRoot.TrimEnd(Path.DirectorySeparatorChar),
StringComparison.OrdinalIgnoreCase);
}
private static void TryWriteFailure(
Action<string, string> writeFile,
string resultPath,
string? requestId,
string message,
TextWriter errorOutput)
{
try
{
writeFile(
resultPath,
SessionRuntimeProtocol.SerializeResult(new SessionRuntimeInstallResult
{
RequestId = requestId,
Error = message
}));
}
catch (Exception exception) when (
exception is IOException or UnauthorizedAccessException)
{
Program.ReportResultWriteFailure(
errorOutput,
requestId,
message,
exception);
}
}
[DllImport("shell32.dll")]
private static extern int SHGetKnownFolderPath(
in Guid folderId,
uint flags,
IntPtr token,
out IntPtr path);
}