@adrifer/winix 0.2.3 → 0.2.4-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +423 -3
  2. package/dist/backends/windows/index.d.ts +3 -1
  3. package/dist/backends/windows/index.js +99 -7
  4. package/dist/backends/windows/lockfile.d.ts +36 -1
  5. package/dist/backends/windows/lockfile.js +168 -0
  6. package/dist/backends/windows/paths.d.ts +2 -0
  7. package/dist/backends/windows/paths.js +17 -0
  8. package/dist/backends/windows/powershell.d.ts +6 -0
  9. package/dist/backends/windows/powershell.js +51 -0
  10. package/dist/backends/windows/wsl-setup-runtime.d.ts +35 -0
  11. package/dist/backends/windows/wsl-setup-runtime.js +401 -0
  12. package/dist/backends/windows/wsl-setup.d.ts +12 -0
  13. package/dist/backends/windows/wsl-setup.js +150 -0
  14. package/dist/backends/windows/wsl.d.ts +9 -0
  15. package/dist/backends/windows/wsl.js +194 -0
  16. package/dist/cli/commands/apply.d.ts +7 -1
  17. package/dist/cli/commands/apply.js +39 -15
  18. package/dist/cli/commands/check.js +3 -0
  19. package/dist/cli/commands/init.js +5 -1
  20. package/dist/cli/commands/switch.d.ts +6 -0
  21. package/dist/cli/commands/switch.js +53 -13
  22. package/dist/cli/commands/update.d.ts +6 -1
  23. package/dist/cli/commands/update.js +41 -10
  24. package/dist/cli/index.js +40 -3
  25. package/dist/cli/windows-state.d.ts +56 -0
  26. package/dist/cli/windows-state.js +341 -0
  27. package/dist/helpers/index.d.ts +1 -1
  28. package/dist/helpers/utils.d.ts +1 -0
  29. package/dist/helpers/utils.js +8 -0
  30. package/dist/helpers/windows.d.ts +53 -7
  31. package/dist/helpers/windows.js +351 -28
  32. package/dist/index.d.ts +4 -2
  33. package/dist/runtime.d.ts +10 -0
  34. package/dist/runtime.js +9 -0
  35. package/dist/skill.js +126 -5
  36. package/dist/types/windows.d.ts +82 -1
  37. package/package.json +4 -1
  38. package/scripts/bootstrap-nixos.sh +51 -0
  39. package/scripts/bootstrap-windows.ps1 +225 -0
@@ -0,0 +1,401 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { spawnSync } from "node:child_process";
10
+ import { randomUUID } from "node:crypto";
11
+ import * as fs from "node:fs/promises";
12
+ import { join, resolve, dirname, relative, isAbsolute } from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+ function object(value) {
15
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
16
+ }
17
+ function linuxDirectory(value) {
18
+ return typeof value === "string" && value.startsWith("/") && value !== "/" &&
19
+ !/[\\\x00-\x1f\x7f]/.test(value) &&
20
+ !value.slice(1).split("/").some((part) => part === "" || part === "." || part === "..");
21
+ }
22
+ export function createWslAccountPlan(host, setup, architecture) {
23
+ const usersOptions = object(host.nixos.users);
24
+ const users = object(usersOptions.users);
25
+ const home = object(host.homeManager.home);
26
+ const candidates = Object.keys(users).filter((name) => object(users[name]).isNormalUser === true && name !== "root");
27
+ const selected = setup.user ?? (typeof home.username === "string" ? home.username : candidates.length === 1 ? candidates[0] : undefined);
28
+ if (!selected || !/^[a-z_][a-z0-9_-]*$/.test(selected) || !candidates.includes(selected)) {
29
+ throw new Error("WSL setup must select a declared normal Linux user; specify setup.user when ambiguous");
30
+ }
31
+ const account = object(users[selected]);
32
+ if (account.isSystemUser === true || account.uid === 0)
33
+ throw new Error("WSL setup cannot select a system/root account");
34
+ const userHome = account.home ?? `/home/${selected}`;
35
+ if (!linuxDirectory(userHome))
36
+ throw new Error("Invalid declared Linux home directory");
37
+ if (home.username !== undefined && (home.username !== selected || home.homeDirectory !== userHome)) {
38
+ throw new Error("Selected account and Home Manager username/home directory must agree");
39
+ }
40
+ const checkout = setup.checkout ?? `${userHome}/dotfiles`;
41
+ if (!linuxDirectory(checkout) || !checkout.startsWith(`${userHome}/`)) {
42
+ throw new Error("WSL setup checkout must be inside the declared user's home");
43
+ }
44
+ const nixpkgs = object(host.nixos.nixpkgs);
45
+ if (nixpkgs.hostPlatform !== architecture)
46
+ throw new Error(`Linux host platform must match the distro architecture (${architecture})`);
47
+ const imports = host.nixos.imports;
48
+ const wslImports = Array.isArray(imports) ? imports.filter((entry) => typeof entry === "string" && /^inputs\.[a-z0-9._-]+\.nixosModules\.wsl$/i.test(entry)) : [];
49
+ if (object(host.nixos.wsl).enable !== true || wslImports.length !== 1 || typeof object(host.nixos.system).stateVersion !== "string") {
50
+ throw new Error("Setup host must explicitly enable NixOS-WSL, import its input module, and declare system.stateVersion");
51
+ }
52
+ const { packages: _packages, ...bootstrapUser } = account;
53
+ const groupNames = [...(Array.isArray(account.extraGroups) ? account.extraGroups : []),
54
+ ...(typeof account.group === "string" ? [account.group] : [])];
55
+ if (groupNames.some((name) => typeof name !== "string" || !/^[a-z_][a-z0-9_-]*$/.test(name)))
56
+ throw new Error("Unsupported account group name");
57
+ const declaredGroups = object(usersOptions.groups);
58
+ const groups = Object.fromEntries(groupNames.map((name) => {
59
+ const { members: _members, ...group } = object(declaredGroups[name]);
60
+ return [name, group];
61
+ }));
62
+ const shell = object(account.shell).expr;
63
+ const shellProgram = typeof shell === "string" ? /^pkgs\.(zsh|fish)$/.exec(shell)?.[1] : undefined;
64
+ return {
65
+ plan: { user: selected, home: userHome, checkout, host: setup.host },
66
+ accountHost: {
67
+ name: host.name, homeManager: {}, darwin: {}, windows: {},
68
+ nixos: {
69
+ imports: wslImports, nixpkgs,
70
+ nix: { settings: { "experimental-features": ["nix-command", "flakes"] } },
71
+ system: { stateVersion: object(host.nixos.system).stateVersion },
72
+ wsl: { enable: true, defaultUser: selected },
73
+ users: { users: { [selected]: bootstrapUser }, groups },
74
+ ...(shellProgram ? { programs: { [shellProgram]: { enable: true } } } : {}),
75
+ },
76
+ },
77
+ };
78
+ }
79
+ export async function prepareWslAccount(configDirectory, accountDirectory, setup, embeddedSdk) {
80
+ const configName = [];
81
+ for (const name of ["winix.config.ts", "winix.config.js", "winix.config.mjs"]) {
82
+ if (await exists(join(configDirectory, name)))
83
+ configName.push(name);
84
+ }
85
+ if (configName.length !== 1)
86
+ throw new Error("WSL setup configDirectory must contain exactly one Winix config file");
87
+ const sdk = embeddedSdk ?? await import(__rewriteRelativeImportExtension(nativeRun(process.execPath, [
88
+ "--input-type=module", "--eval", 'console.log(import.meta.resolve("@adrifer/winix"))',
89
+ ], { cwd: configDirectory })));
90
+ const workspace = (await import(__rewriteRelativeImportExtension(pathToFileURL(join(configDirectory, configName[0])).href))).default;
91
+ if (!workspace || !Array.isArray(workspace.hosts))
92
+ throw new Error("Invalid Winix workspace");
93
+ const targets = workspace.hosts.filter((host) => host.name === setup.host && host.platform.__id === "nixos");
94
+ if (targets.length !== 1)
95
+ throw new Error(`WSL setup target "${setup.host}" must identify one NixOS host`);
96
+ const [evaluated] = sdk.evaluate({ ...workspace, hosts: targets });
97
+ const architecture = process.arch === "x64" ? "x86_64-linux" : process.arch === "arm64" ? "aarch64-linux" : "";
98
+ const { plan, accountHost } = createWslAccountPlan(evaluated, setup, architecture);
99
+ const output = sdk.generateNix(workspace, [accountHost]);
100
+ await fs.mkdir(join(accountDirectory, "hosts"), { recursive: true });
101
+ await fs.writeFile(join(accountDirectory, "flake.nix"), output["flake.nix"]);
102
+ for (const [name, content] of Object.entries(output.hosts))
103
+ await fs.writeFile(join(accountDirectory, "hosts", name), content);
104
+ await fs.copyFile(join(configDirectory, "flake.lock"), join(accountDirectory, "flake.lock"));
105
+ return plan;
106
+ }
107
+ function nativeRun(command, args, options = {}) {
108
+ const env = {
109
+ ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "Never",
110
+ WINIX_WSL_SETUP_REQUEST: "", WINIX_WSL_SETUP_PREPARE: "", ...options.env,
111
+ };
112
+ const argv = options.user ? [
113
+ "-u", options.user, "--", "env", `HOME=${options.home}`, `PATH=${process.env.PATH}`,
114
+ command, ...args,
115
+ ] : args;
116
+ const result = spawnSync(options.user ? "runuser" : command, argv, {
117
+ cwd: options.cwd, env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024,
118
+ });
119
+ if (result.error)
120
+ throw result.error;
121
+ if (result.status !== 0)
122
+ throw Object.assign(new Error(`${command} failed (${result.status}): ${result.stderr}\n${result.stdout}`), { status: result.status });
123
+ return result.stdout.trim();
124
+ }
125
+ async function exists(path) {
126
+ try {
127
+ await fs.lstat(path);
128
+ return true;
129
+ }
130
+ catch (error) {
131
+ if (error.code === "ENOENT")
132
+ return false;
133
+ throw error;
134
+ }
135
+ }
136
+ async function safeDirectory(path) {
137
+ let current = resolve(path);
138
+ for (;;) {
139
+ if (await exists(current)) {
140
+ const stat = await fs.lstat(current);
141
+ if (stat.isSymbolicLink() || !stat.isDirectory())
142
+ throw new Error(`Unsafe setup directory: ${current}`);
143
+ }
144
+ const parent = dirname(current);
145
+ if (parent === current)
146
+ break;
147
+ current = parent;
148
+ }
149
+ }
150
+ async function atomicJson(path, value) {
151
+ const temporary = `${path}.${randomUUID()}.tmp`;
152
+ await fs.writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
153
+ await fs.rename(temporary, path);
154
+ }
155
+ export async function runWslSetup(request, options = {}) {
156
+ if (process.platform !== "linux" || !(options.isRoot ?? (() => process.getuid?.() === 0))()) {
157
+ throw new Error("WSL setup coordinator requires Linux root; repository/npm commands run unprivileged");
158
+ }
159
+ const run = options.run ?? nativeRun;
160
+ const executable = options.executable ?? process.execPath;
161
+ const stateDirectory = options.stateDirectory ?? "/var/lib/winix/wsl-setup";
162
+ await safeDirectory(stateDirectory);
163
+ await fs.mkdir(stateDirectory, { recursive: true, mode: 0o711 });
164
+ const directoryStat = await fs.stat(stateDirectory);
165
+ if (directoryStat.uid !== process.getuid?.() || (directoryStat.mode & 0o022))
166
+ throw new Error("Unsafe WSL setup state ownership/permissions");
167
+ const lockPath = join(stateDirectory, "run.lock");
168
+ let lock;
169
+ try {
170
+ lock = await fs.open(lockPath, "wx", 0o600);
171
+ }
172
+ catch (error) {
173
+ if (error.code === "EEXIST")
174
+ throw new Error("WSL setup is running or was interrupted. Inspect run.lock before manually recovering it.");
175
+ throw error;
176
+ }
177
+ try {
178
+ await lock.writeFile(String(process.pid));
179
+ const statePath = join(stateDirectory, "state.json");
180
+ if (await exists(statePath)) {
181
+ const stat = await fs.lstat(statePath);
182
+ if (!stat.isFile() || stat.uid !== directoryStat.uid || (stat.mode & 0o022))
183
+ throw new Error("Unsafe WSL setup state file");
184
+ }
185
+ const state = await exists(statePath) ? JSON.parse(await fs.readFile(statePath, "utf8")) : {
186
+ version: 1, fingerprint: request.fingerprint, revision: request.revision, step: "initial",
187
+ };
188
+ if (!state || state.version !== 1 || state.fingerprint !== request.fingerprint ||
189
+ !["initial", "prepared", "placed", "account", "activated"].includes(state.step) ||
190
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(state.revision)) {
191
+ throw new Error("Conflicting/corrupt WSL setup state; refusing to overwrite");
192
+ }
193
+ await atomicJson(statePath, state);
194
+ const runtimePath = join(stateDirectory, "runtime.mjs");
195
+ if (!options.standalone) {
196
+ if (!process.env.WINIX_WSL_SETUP_RUNTIME && !options.run)
197
+ throw new Error("Missing WSL setup runtime payload");
198
+ const runtimeTemporary = `${runtimePath}.${randomUUID()}.tmp`;
199
+ await fs.writeFile(runtimeTemporary, Buffer.from(process.env.WINIX_WSL_SETUP_RUNTIME ?? "", "base64"), { flag: "wx", mode: 0o444 });
200
+ await fs.rename(runtimeTemporary, runtimePath);
201
+ }
202
+ const work = join(stateDirectory, "work");
203
+ const repository = join(work, "repository");
204
+ const accountDirectory = join(work, "account");
205
+ const save = async (step) => { state.step = step; await atomicJson(statePath, state); };
206
+ const passwd = (user) => {
207
+ let output;
208
+ try {
209
+ output = run("getent", ["passwd", user]);
210
+ }
211
+ catch (error) {
212
+ if (error.status === 2)
213
+ return undefined;
214
+ throw error;
215
+ }
216
+ const fields = output.split(":");
217
+ if (fields[0] !== user || !/^[1-9]\d*$/.test(fields[2]) || !/^\d+$/.test(fields[3]) || !fields[5]?.startsWith("/")) {
218
+ throw new Error(`Invalid/non-root account expected: ${user}`);
219
+ }
220
+ return { uid: fields[2], gid: fields[3], home: fields[5] };
221
+ };
222
+ const verify = (checkout, user, home) => {
223
+ const git = (args) => run("git", args, { cwd: checkout, user, home });
224
+ if (git(["remote", "get-url", "origin"]) !== request.setup.repository ||
225
+ git(["rev-parse", "HEAD"]) !== state.revision)
226
+ throw new Error("Checkout identity/revision changed; refusing reset");
227
+ if (git(["status", "--porcelain", "--untracked-files=normal"]))
228
+ throw new Error("WSL setup checkout is dirty; refusing reset");
229
+ };
230
+ const prepare = (config, user, home) => {
231
+ const prepared = run(executable, options.standalone ? [] : ["--experimental-transform-types", "--no-warnings", runtimePath], {
232
+ user, home, cwd: config,
233
+ env: { WINIX_WSL_SETUP_PREPARE: JSON.stringify({ config, accountDirectory, setup: request.setup }) },
234
+ });
235
+ const plans = prepared.split(/\r?\n/).filter((line) => line.startsWith("WINIX_PLAN:"));
236
+ if (plans.length !== 1)
237
+ throw new Error("Linux configuration did not produce exactly one setup plan");
238
+ return JSON.parse(plans[0].slice("WINIX_PLAN:".length));
239
+ };
240
+ if (state.step === "initial") {
241
+ console.log("WSL setup: preparing the locked repository as the image's nixos user");
242
+ const initial = passwd("nixos");
243
+ if (!initial)
244
+ throw new Error("Fresh NixOS-WSL image must provide its initial nixos account");
245
+ await fs.mkdir(accountDirectory, { recursive: true });
246
+ run("chown", ["-R", "--no-dereference", `${initial.uid}:${initial.gid}`, "--", work]);
247
+ const asInitial = { user: "nixos", home: initial.home };
248
+ await safeDirectory(repository);
249
+ if (!await exists(repository) || (await fs.readdir(repository)).length === 0) {
250
+ run("git", ["init", `--object-format=${state.revision.length === 64 ? "sha256" : "sha1"}`, "--", repository], asInitial);
251
+ }
252
+ await safeDirectory(join(repository, ".git"));
253
+ if (!await exists(join(repository, ".git")))
254
+ throw new Error("Unrecognized staging checkout; refusing adoption");
255
+ const git = (args) => run("git", args, { ...asInitial, cwd: repository });
256
+ const remotes = git(["remote"]).split(/\r?\n/).filter(Boolean);
257
+ if (!remotes.includes("origin"))
258
+ git(["remote", "add", "origin", request.setup.repository]);
259
+ if (git(["remote", "get-url", "origin"]) !== request.setup.repository)
260
+ throw new Error("Conflicting staging repository");
261
+ if (git(["status", "--porcelain", "--untracked-files=normal"]))
262
+ throw new Error("Staging checkout is dirty; refusing reset");
263
+ let existingHead;
264
+ try {
265
+ existingHead = git(["rev-parse", "--verify", "HEAD"]);
266
+ }
267
+ catch (error) {
268
+ if (error.status !== 128)
269
+ throw error;
270
+ }
271
+ if (existingHead && existingHead !== state.revision)
272
+ throw new Error("Staging revision changed; refusing reset");
273
+ git(["fetch", "--depth=1", "--no-tags", "origin", state.revision]);
274
+ git(["checkout", "--detach", state.revision]);
275
+ verify(repository, "nixos", initial.home);
276
+ const config = await fs.realpath(join(repository, request.setup.configDirectory));
277
+ const inside = relative(await fs.realpath(repository), config);
278
+ if (inside.startsWith("..") || isAbsolute(inside))
279
+ throw new Error("configDirectory escapes the checkout");
280
+ for (const name of options.standalone ? ["flake.lock"] : ["package-lock.json", "package.json", "flake.lock"]) {
281
+ if (!await exists(join(config, name)))
282
+ throw new Error(`WSL setup requires committed ${name} in configDirectory`);
283
+ }
284
+ if (!options.standalone)
285
+ run("npm", ["ci", "--no-audit", "--no-fund"], { ...asInitial, cwd: config });
286
+ verify(repository, "nixos", initial.home);
287
+ state.plan = prepare(config, "nixos", initial.home);
288
+ await save("prepared");
289
+ }
290
+ const plan = state.plan;
291
+ if (!plan || typeof plan.user !== "string" || !/^[a-z_][a-z0-9_-]*$/.test(plan.user) || plan.user === "root" ||
292
+ plan.host !== request.setup.host || !linuxDirectory(plan.home) || !linuxDirectory(plan.checkout) ||
293
+ !plan.checkout.startsWith(`${plan.home}/`) ||
294
+ (request.setup.user !== undefined && request.setup.user !== plan.user) ||
295
+ (request.setup.checkout !== undefined && request.setup.checkout !== plan.checkout)) {
296
+ throw new Error("Invalid recorded WSL account/checkout plan");
297
+ }
298
+ if (state.step === "prepared") {
299
+ await safeDirectory(plan.checkout);
300
+ if (await exists(plan.checkout)) {
301
+ if (await exists(repository))
302
+ throw new Error("WSL setup checkout already exists; refusing adoption/overwrite");
303
+ // A crash between rename and recording the next stage is resumable.
304
+ const initial = passwd("nixos");
305
+ if (!initial)
306
+ throw new Error("Cannot verify the interrupted checkout move without the initial account");
307
+ await safeDirectory(join(plan.checkout, ".git"));
308
+ verify(plan.checkout, "nixos", initial.home);
309
+ }
310
+ else {
311
+ await fs.mkdir(dirname(plan.checkout), { recursive: true });
312
+ await fs.rename(repository, plan.checkout);
313
+ }
314
+ await save("placed");
315
+ }
316
+ if (state.step === "placed") {
317
+ await safeDirectory(join(plan.checkout, ".git"));
318
+ const initial = passwd("nixos");
319
+ const owner = initial ?? passwd(plan.user);
320
+ if (!owner)
321
+ throw new Error("Cannot verify checkout ownership before account activation");
322
+ if (!initial)
323
+ run("chown", ["-R", "--no-dereference", `${owner.uid}:${owner.gid}`, "--", plan.checkout]);
324
+ const ownerName = initial ? "nixos" : plan.user;
325
+ verify(plan.checkout, ownerName, owner.home);
326
+ await safeDirectory(accountDirectory);
327
+ run("chown", ["-R", "--no-dereference", `${owner.uid}:${owner.gid}`, "--", accountDirectory]);
328
+ // Re-evaluate after moving: account file paths can depend on import.meta.url.
329
+ const placedPlan = prepare(join(plan.checkout, request.setup.configDirectory), ownerName, owner.home);
330
+ if (!placedPlan || ["user", "home", "checkout", "host"].some((key) => placedPlan[key] !== plan[key])) {
331
+ throw new Error("Linux account plan changed after placing the checkout; refusing activation");
332
+ }
333
+ verify(plan.checkout, ownerName, owner.home);
334
+ console.log("WSL setup: activating the declarative account-only NixOS configuration");
335
+ run("nixos-rebuild", ["switch", "--flake", `path:${accountDirectory}#${plan.host}`, "--no-write-lock-file"]);
336
+ await save("account");
337
+ }
338
+ const account = passwd(plan.user);
339
+ if (!account || account.home !== plan.home)
340
+ throw new Error("Activated Linux account/home does not match the setup plan");
341
+ await safeDirectory(plan.checkout);
342
+ run("chown", ["-R", "--no-dereference", `${account.uid}:${account.gid}`, "--", plan.checkout]);
343
+ for (let parent = dirname(plan.checkout);; parent = dirname(parent)) {
344
+ run("chown", [`${account.uid}:${account.gid}`, "--", parent]);
345
+ if (parent === plan.home)
346
+ break;
347
+ }
348
+ const asUser = { user: plan.user, home: plan.home, cwd: join(plan.checkout, request.setup.configDirectory) };
349
+ verify(plan.checkout, plan.user, plan.home);
350
+ if (state.step === "account") {
351
+ console.log("WSL setup: generating and activating the full Linux host");
352
+ if (options.standalone)
353
+ run(executable, ["apply", "--host", plan.host], asUser);
354
+ else
355
+ run("npm", ["exec", "--offline", "--", "winix", "apply", "--host", plan.host], asUser);
356
+ const flake = `path:${join(asUser.cwd, ".winix", "out")}`;
357
+ const defaultUser = run("nix", ["eval", "--raw", "--no-write-lock-file", `${flake}#nixosConfigurations.${JSON.stringify(plan.host)}.config.wsl.defaultUser`], asUser);
358
+ if (defaultUser !== plan.user)
359
+ throw new Error("Full Linux host must select the setup account as wsl.defaultUser");
360
+ run("nixos-rebuild", ["switch", "--flake", `${flake}#${plan.host}`, "--no-write-lock-file"]);
361
+ await save("activated");
362
+ }
363
+ const wslConfig = await (options.readWslConfig ?? (() => fs.readFile("/etc/wsl.conf", "utf8")))();
364
+ let userSection = false;
365
+ const matchesDefault = wslConfig.split(/\r?\n/).some((line) => {
366
+ const section = /^\s*\[([^\]]+)\]\s*$/.exec(line);
367
+ if (section) {
368
+ userSection = section[1] === "user";
369
+ return false;
370
+ }
371
+ return userSection && new RegExp(`^\\s*default\\s*=\\s*${plan.user}\\s*$`).test(line);
372
+ });
373
+ if (!matchesDefault) {
374
+ throw new Error("Linux activation did not configure the expected WSL default user");
375
+ }
376
+ verify(plan.checkout, plan.user, plan.home);
377
+ const completeTemporary = join(stateDirectory, `complete.${randomUUID()}.tmp`);
378
+ await fs.writeFile(completeTemporary, `${request.fingerprint}\n${plan.user}\n${plan.checkout}\n`, { flag: "wx", mode: 0o600 });
379
+ await fs.rename(completeTemporary, join(stateDirectory, "complete"));
380
+ console.log("WSL setup complete. Restart WSL manually if needed for its default-user setting; no shutdown was performed.");
381
+ }
382
+ finally {
383
+ await lock.close();
384
+ await fs.unlink(lockPath);
385
+ }
386
+ }
387
+ export async function dispatchWslSetup(embeddedSdk) {
388
+ if (process.env.WINIX_WSL_SETUP_PREPARE) {
389
+ const { config, accountDirectory, setup } = JSON.parse(process.env.WINIX_WSL_SETUP_PREPARE);
390
+ console.log("WINIX_PLAN:" + JSON.stringify(await prepareWslAccount(config, accountDirectory, setup, embeddedSdk)));
391
+ }
392
+ else if (process.env.WINIX_WSL_SETUP_REQUEST) {
393
+ await runWslSetup(JSON.parse(Buffer.from(process.env.WINIX_WSL_SETUP_REQUEST, "base64").toString("utf8")), {
394
+ standalone: embeddedSdk !== undefined,
395
+ executable: embeddedSdk ? process.env.WINIX_STANDALONE_EXECUTABLE : undefined,
396
+ });
397
+ }
398
+ else {
399
+ throw new Error("Missing WSL setup request");
400
+ }
401
+ }
@@ -0,0 +1,12 @@
1
+ import type { WinWslSetup } from "../../types/index.js";
2
+ export interface WindowsLockWslRepository {
3
+ repository: string;
4
+ ref: string;
5
+ revision: string;
6
+ resolvedAt: string;
7
+ }
8
+ export type WindowsWslRepositoryResolver = (repository: string, ref: string) => string;
9
+ export declare function wslRepositoryKey(setup: WinWslSetup): string;
10
+ export declare function validWslRepository(value: unknown): value is WindowsLockWslRepository;
11
+ export declare const resolveWslRepository: WindowsWslRepositoryResolver;
12
+ export declare function wslSetupPrelude(setup: WinWslSetup, pin: WindowsLockWslRepository): string[];
@@ -0,0 +1,150 @@
1
+ import { createHash } from "node:crypto";
2
+ import { execFileSync } from "node:child_process";
3
+ import { readFileSync } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import { normalizeWslSetup } from "../../helpers/windows.js";
6
+ import { powerShellLiteral as ps } from "../../helpers/utils.js";
7
+ import { standaloneRuntime } from "../../runtime.js";
8
+ export function wslRepositoryKey(setup) {
9
+ return createHash("sha256").update(JSON.stringify([setup.repository, setup.ref ?? "HEAD"])).digest("hex");
10
+ }
11
+ export function validWslRepository(value) {
12
+ if (!value || typeof value !== "object")
13
+ return false;
14
+ const pin = value;
15
+ if (typeof pin.repository !== "string" || typeof pin.ref !== "string" ||
16
+ typeof pin.revision !== "string" || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(pin.revision) ||
17
+ typeof pin.resolvedAt !== "string")
18
+ return false;
19
+ try {
20
+ normalizeWslSetup({ repository: pin.repository, ref: pin.ref, configDirectory: ".", host: "validate" });
21
+ return true;
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ export const resolveWslRepository = (repository, ref) => {
28
+ normalizeWslSetup({ repository, ref, configDirectory: ".", host: "validate" });
29
+ if (/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(ref))
30
+ return ref;
31
+ const refsToLookup = ref.startsWith("refs/") ? [ref, `${ref}^{}`] :
32
+ ref === "HEAD" ? ["HEAD"] : [`refs/heads/${ref}`, `refs/tags/${ref}`, `refs/tags/${ref}^{}`];
33
+ const output = execFileSync("git", [
34
+ "ls-remote", "--exit-code", "--", repository, ...refsToLookup,
35
+ ], {
36
+ encoding: "utf8", timeout: 45000, stdio: ["ignore", "pipe", "pipe"],
37
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "Never" },
38
+ });
39
+ const refs = new Map();
40
+ for (const line of output.trim().split(/\r?\n/)) {
41
+ const [sha, name] = line.split(/\s+/);
42
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sha) || !name)
43
+ throw new Error("Invalid Git revision lookup output");
44
+ refs.set(name, sha);
45
+ }
46
+ for (const [name, sha] of [...refs])
47
+ if (name.endsWith("^{}")) {
48
+ refs.delete(name);
49
+ refs.set(name.slice(0, -3), sha);
50
+ }
51
+ const revisions = new Set(refs.values());
52
+ if (revisions.size !== 1)
53
+ throw new Error(`Ambiguous Git ref "${ref}"; use a full ref or immutable commit`);
54
+ return [...revisions][0];
55
+ };
56
+ export function wslSetupPrelude(setup, pin) {
57
+ setup = normalizeWslSetup(setup);
58
+ if (!validWslRepository(pin) || pin.repository !== setup.repository || pin.ref !== setup.ref) {
59
+ throw new Error("Missing/mismatched WSL repository pin. Run winix update --windows wsl-setup.");
60
+ }
61
+ const fingerprint = createHash("sha256").update(JSON.stringify(setup)).digest("hex");
62
+ const request = Buffer.from(JSON.stringify({ setup, revision: pin.revision, fingerprint })).toString("base64");
63
+ const standalone = standaloneRuntime();
64
+ let launch;
65
+ if (standalone) {
66
+ const cases = ["x64", "arm64"].map((architecture) => {
67
+ const asset = standalone.linuxAssets[architecture];
68
+ if (!asset || !/^[a-f0-9]{64}$/.test(asset.sha256) || asset.name !== `winix-linux-${architecture}`) {
69
+ throw new Error("This standalone build lacks Linux release checksums; use the official Windows release binary for WSL provisioning.");
70
+ }
71
+ return ` ${architecture === "x64" ? "x86_64" : "aarch64"}) asset='${asset.name}'; checksum='${asset.sha256}'; linker='${architecture === "x64" ? "ld-linux-x86-64.so.2" : "ld-linux-aarch64.so.1"}' ;;`;
72
+ });
73
+ launch = [
74
+ 'case "$(uname -m)" in', ...cases,
75
+ " *) echo 'Unsupported Linux architecture for standalone WSL setup' >&2; exit 2 ;;", "esac",
76
+ "temporary=$(mktemp -d)",
77
+ "trap 'rm -rf -- \"$temporary\"' EXIT",
78
+ `nix shell --no-write-lock-file github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f#curl --command curl --fail --location --proto '=https' --proto-redir '=https' --output "$temporary/winix" "https://github.com/adrifer/winix/releases/download/v${standalone.version}/$asset"`,
79
+ "printf '%s %s\\n' \"$checksum\" \"$temporary/winix\" | sha256sum --check --status || { echo 'Standalone Linux executable checksum mismatch' >&2; exit 2; }",
80
+ `directory=/var/lib/winix/runtime/${standalone.version}`,
81
+ 'for parent in /var/lib/winix /var/lib/winix/runtime "$directory"; do',
82
+ ' [[ ! -L "$parent" ]] || { echo "Unsafe standalone runtime directory: $parent" >&2; exit 2; }',
83
+ ' mkdir -p -- "$parent"; [[ $(stat -c %u "$parent") == 0 ]] && (( (8#$(stat -c %a "$parent") & 0022) == 0 )) || { echo "Unsafe runtime directory permissions: $parent" >&2; exit 2; }; chmod 755 -- "$parent"',
84
+ "done",
85
+ '[[ ! -L "$directory/winix" && ! -L "$directory/winix.bin" ]] || { echo "Unsafe standalone runtime path" >&2; exit 2; }',
86
+ 'destination=$(mktemp "$directory/winix.XXXXXX")',
87
+ 'trap \'rm -f -- "$destination"; rm -rf -- "$temporary"\' EXIT',
88
+ 'install -T -m 755 -- "$temporary/winix" "$destination"',
89
+ 'nix build --no-write-lock-file --out-link "$directory/libc" github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f#glibc.out',
90
+ 'nix build --no-write-lock-file --out-link "$directory/compiler" github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f#stdenv.cc.cc.lib',
91
+ 'mv -fT -- "$destination" "$directory/winix.bin"',
92
+ 'destination=$(mktemp "$directory/launch.XXXXXX")',
93
+ 'printf \'#!/usr/bin/env bash\\nset -euo pipefail\\nexport WINIX_STANDALONE_EXECUTABLE=%q\\nexec %q --argv0 %q --library-path %q %q "$@"\\n\' "$directory/winix" "$directory/libc/lib/$linker" "$directory/winix.bin" "$directory/libc/lib:$directory/compiler/lib" "$directory/winix.bin" > "$destination"',
94
+ 'chmod 755 -- "$destination"; mv -fT -- "$destination" "$directory/winix"',
95
+ 'nix shell --no-write-lock-file github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f#git --command "$directory/winix"',
96
+ ];
97
+ }
98
+ else {
99
+ const extension = import.meta.url.endsWith(".ts") ? "ts" : "js";
100
+ const source = readFileSync(new URL(`./wsl-setup-runtime.${extension}`, import.meta.url), "utf8");
101
+ const runtime = extension === "ts"
102
+ ? createRequire(import.meta.url)("node:module").stripTypeScriptTypes(source, { mode: "transform" })
103
+ : source;
104
+ launch = [
105
+ `export WINIX_WSL_SETUP_RUNTIME='${Buffer.from(runtime + "\nawait dispatchWslSetup();\n").toString("base64")}'`,
106
+ "exec nix shell --no-write-lock-file github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f#git github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f#nodejs_24 --command node --input-type=module --eval \"$(printf '%s' \"$WINIX_WSL_SETUP_RUNTIME\" | base64 --decode)\"",
107
+ ];
108
+ }
109
+ const probe = [
110
+ "set -euo pipefail",
111
+ "state=/var/lib/winix/wsl-setup",
112
+ "[[ ! -L \"$state\" && ! -L \"$state/complete\" ]] || { echo 'Unsafe WSL setup completion record' >&2; exit 2; }",
113
+ "if [[ ! -f \"$state/complete\" ]]; then exit 3; fi",
114
+ "mapfile -t completed < \"$state/complete\"",
115
+ `[[ "\${completed[0]:-}" == '${fingerprint}' ]] || { echo 'WSL setup settings changed; existing setup is never overwritten automatically' >&2; exit 2; }`,
116
+ "[[ ${#completed[@]} == 3 ]] || { echo 'Invalid WSL setup completion record' >&2; exit 2; }",
117
+ "getent passwd \"${completed[1]}\" >/dev/null || { echo 'WSL setup user is missing' >&2; exit 2; }",
118
+ "[[ -d \"${completed[2]}/.git\" ]] || { echo 'WSL setup checkout is missing' >&2; exit 2; }",
119
+ "awk -v expected=\"${completed[1]}\" ' /^[ \\t]*\\[/ { user = ($0 ~ /^[ \\t]*\\[user\\][ \\t]*$/) } user && $0 ~ \"^[ \\t]*default[ \\t]*=[ \\t]*\" expected \"[ \\t]*$\" { found=1 } END { exit !found }' /etc/wsl.conf || { echo 'WSL default user no longer matches setup' >&2; exit 2; }",
120
+ ].join("\n");
121
+ const activate = [
122
+ probe.replace("if [[ ! -f \"$state/complete\" ]]; then exit 3; fi", "if [[ -f \"$state/complete\" ]]; then") + "\nexit 0\nfi",
123
+ `export WINIX_WSL_SETUP_REQUEST='${request}'`,
124
+ 'export NIX_CONFIG="${NIX_CONFIG:+$NIX_CONFIG$\'\\n\'}extra-experimental-features = nix-command flakes"',
125
+ ...launch,
126
+ ].join("\n");
127
+ return [
128
+ "function Invoke-WinixWslSetup([bool]$TestOnly) {",
129
+ ` $script = if ($TestOnly) { ${ps(probe + "\n")} } else { ${ps(activate + "\n")} }`,
130
+ " $start = [Diagnostics.ProcessStartInfo]::new('wsl.exe')",
131
+ " $start.UseShellExecute = $false",
132
+ " $start.RedirectStandardInput = $true; $start.RedirectStandardOutput = $true; $start.RedirectStandardError = $true",
133
+ " $start.StandardInputEncoding = [Text.UTF8Encoding]::new($false)",
134
+ " $start.StandardOutputEncoding = $start.StandardInputEncoding; $start.StandardErrorEncoding = $start.StandardInputEncoding",
135
+ " foreach ($argument in @('--distribution', $name, '--user', 'root', '--exec', 'bash', '-s')) { $start.ArgumentList.Add($argument) }",
136
+ " $process = [Diagnostics.Process]::new(); $process.StartInfo = $start",
137
+ " try {",
138
+ " if (-not $process.Start()) { throw 'Could not start WSL setup' }",
139
+ " $stdout = $process.StandardOutput.ReadToEndAsync(); $stderr = $process.StandardError.ReadToEndAsync()",
140
+ " $process.StandardInput.Write($script); $process.StandardInput.Close()",
141
+ " $process.WaitForExit()",
142
+ " $output = $stdout.GetAwaiter().GetResult(); $errors = $stderr.GetAwaiter().GetResult()",
143
+ " if ($TestOnly -and $process.ExitCode -eq 3) { return $false }",
144
+ " if ($process.ExitCode -ne 0) { throw \"WSL setup failed ($($process.ExitCode)): $output $errors\" }",
145
+ " if (-not $TestOnly) { if ($output) { Write-Host $output }; if ($errors) { Write-Host $errors } }",
146
+ " return $true",
147
+ " } finally { $process.Dispose() }",
148
+ "}",
149
+ ];
150
+ }
@@ -0,0 +1,9 @@
1
+ import type { WinDscProperties, WinWslDistro } from "../../types/index.js";
2
+ import type { WindowsLockWslImage } from "./lockfile.js";
3
+ import { type WindowsLockWslRepository } from "./wsl-setup.js";
4
+ export type WslArchitecture = "x64" | "arm64";
5
+ export type WindowsWslImageResolver = (architecture: WslArchitecture) => Omit<WindowsLockWslImage, "resolvedAt">;
6
+ export declare function validWslImage(value: unknown): value is WindowsLockWslImage;
7
+ export declare const resolveNixosWslImage: WindowsWslImageResolver;
8
+ export declare function optionalFeatureProperties(names: string[], enabled: boolean): WinDscProperties;
9
+ export declare function wslDistroProperties(distro: WinWslDistro, pins: Record<string, WindowsLockWslImage>, repositories?: Record<string, WindowsLockWslRepository>): WinDscProperties;