@durableintel/nenya 0.0.0-stage → 1.2.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.
@@ -0,0 +1,395 @@
1
+ // Windows rules for the setup line that the app can't keep itself, because they act before the app
2
+ // exists (ported from the a21 installer, deploy/client/npm/installer/lib/install.mjs, BA-24, BA-40,
3
+ // BA-76 and NPX-BESIDE-SYSTEM-WIDE):
4
+ //
5
+ // - BA-40: an elevated run whose desktop is signed in as another account (a standard account that
6
+ // typed an administrator's password at Windows' prompt) would install into that administrator's
7
+ // profile, so it stops before anything is fetched or written.
8
+ // - BA-76: an elevated run as the person (an administrator terminal of their own) installs for them
9
+ // as usual, but everything an elevated process creates is owned by the Administrators group; what
10
+ // this run made in the person's profile is given back to them with `icacls /setowner`. The app
11
+ // itself never runs elevated: it starts again as the person (apps/desktop/src/main/core/elevation.ts).
12
+ // - NPX-BESIDE: a Nenya installed for everyone (Program Files) beside the person's own is said once,
13
+ // with why it is not to be removed from there (its uninstaller removes every account's Nenya).
14
+ //
15
+ // Every Windows tool is reached by its System32 path through the injected `system.run` (asked for
16
+ // its `output`: { status, stdout }); nothing here throws.
17
+ import { existsSync, lstatSync, realpathSync } from "node:fs";
18
+ import path from "node:path";
19
+
20
+ const win = path.win32;
21
+
22
+ /** System32 from the environment (SystemRoot, else windir), else C:\Windows\System32. */
23
+ export function system32(env) {
24
+ return win.join(
25
+ env.SystemRoot || env.SYSTEMROOT || env.windir || "C:\\Windows",
26
+ "System32",
27
+ );
28
+ }
29
+
30
+ /** One CSV row of whoami or tasklist output, its fields unquoted. */
31
+ export function csvFields(line) {
32
+ return line.trim().replace(/^"|"$/g, "").split('","');
33
+ }
34
+
35
+ function run(system, env, tool, args, timeout = 10_000) {
36
+ const done = system.run(win.join(system32(env), tool), args, {
37
+ timeout,
38
+ output: true,
39
+ });
40
+ return {
41
+ status: done?.status ?? null,
42
+ stdout: String(done?.stdout ?? ""),
43
+ timedOut: done?.timedOut === true,
44
+ };
45
+ }
46
+
47
+ /** The SIDs in this process's token (`whoami /groups`), or null when Windows doesn't answer. */
48
+ function groupSids({ env, system }) {
49
+ const groups = run(system, env, "whoami.exe", [
50
+ "/groups",
51
+ "/fo",
52
+ "csv",
53
+ "/nh",
54
+ ]);
55
+ return groups.status === 0
56
+ ? new Set(groups.stdout.split(/\r?\n/).flatMap(csvFields))
57
+ : null;
58
+ }
59
+
60
+ /**
61
+ * Whether this run holds an elevated token (an administrator terminal): true for a High or System
62
+ * mandatory level, false for any other level, and null when `whoami /groups` fails or names no
63
+ * mandatory level at all. The setup line refuses on null (ELEVATION_UNKNOWN_LINE): an elevated run
64
+ * must never pass for a plain one.
65
+ */
66
+ export function windowsElevated({ env, system }) {
67
+ const sids = groupSids({ env, system });
68
+ if (sids === null || ![...sids].some((sid) => /^S-1-16-\d+$/.test(sid)))
69
+ return null;
70
+ return sids.has("S-1-16-12288") || sids.has("S-1-16-16384");
71
+ }
72
+
73
+ export const ELEVATION_UNKNOWN_LINE =
74
+ "Nothing was installed: Windows didn't say whether this terminal runs as an administrator (whoami /groups failed). This command works in a new terminal opened without Run as administrator.";
75
+
76
+ /** This process's session number (`tasklist`), or null. */
77
+ function sessionOf({ env, system, pid }) {
78
+ const tasks = run(system, env, "tasklist.exe", [
79
+ "/fi",
80
+ `PID eq ${pid}`,
81
+ "/fo",
82
+ "csv",
83
+ "/nh",
84
+ ]);
85
+ const row =
86
+ tasks.status === 0
87
+ ? tasks.stdout
88
+ .split(/\r?\n/)
89
+ .map(csvFields)
90
+ .find((fields) => fields[1] === String(pid))
91
+ : undefined;
92
+ return row && /^\d+$/.test(row[3] ?? "") ? Number(row[3]) : null;
93
+ }
94
+
95
+ /**
96
+ * BA-40, for an elevated run: true when this session's desktop (its Explorer) belongs to another
97
+ * account than the one this runs as, or when that can't be told (another account's Explorer reads
98
+ * as "N/A" to an administrator; Windows didn't answer). No desktop in the session (SSH, a service):
99
+ * false. Not elevated: never asked.
100
+ */
101
+ export function windowsDesktopIsOtherAccount({
102
+ env,
103
+ system,
104
+ pid = process.pid,
105
+ }) {
106
+ const self = run(system, env, "whoami.exe", []);
107
+ const me = self.status === 0 ? self.stdout.trim().toLowerCase() : "";
108
+ const session = sessionOf({ env, system, pid });
109
+ if (me === "" || session === null) return true;
110
+ const shells = run(
111
+ system,
112
+ env,
113
+ "tasklist.exe",
114
+ [
115
+ "/fi",
116
+ "IMAGENAME eq explorer.exe",
117
+ "/fi",
118
+ `SESSION eq ${session}`,
119
+ "/v",
120
+ "/fo",
121
+ "csv",
122
+ "/nh",
123
+ ],
124
+ 15_000,
125
+ );
126
+ if (shells.status !== 0) return true;
127
+ // tasklist /v: "Image Name","PID","Session Name","Session#","Mem Usage","Status","User Name",...
128
+ const desktops = shells.stdout
129
+ .split(/\r?\n/)
130
+ .map(csvFields)
131
+ .filter((fields) => fields[0]?.toLowerCase() === "explorer.exe");
132
+ if (desktops.length === 0) return false;
133
+ // a readable owner is domain\name ("N/A", in any language, has no backslash)
134
+ const owners = desktops
135
+ .map((fields) => (fields[6] ?? "").toLowerCase())
136
+ .filter((name) => name.includes("\\"));
137
+ return !owners.includes(me);
138
+ }
139
+
140
+ export const OTHER_ACCOUNT_LINE =
141
+ "Nothing was installed: this terminal runs as an administrator, not as you. This command works in a terminal opened without Run as administrator.";
142
+
143
+ /** The SID of the account this runs as (`whoami /user`), or null. */
144
+ export function personSid({ env, system }) {
145
+ const user = run(system, env, "whoami.exe", ["/user", "/fo", "csv", "/nh"]);
146
+ const sid =
147
+ user.status === 0
148
+ ? csvFields(user.stdout.split(/\r?\n/)[0] ?? "")[1]
149
+ : undefined;
150
+ return sid && /^S-1-\d+(-\d+)+$/.test(sid) ? sid : null;
151
+ }
152
+
153
+ /** A drive and at least one folder below it (C:\Users\ana), never a drive root. */
154
+ const FOLDER_ON_DRIVE = /^[A-Za-z]:\\[^\\]+/;
155
+
156
+ const clean = (place) =>
157
+ place ? win.normalize(place).replace(/\\+$/, "") : "";
158
+
159
+ /** `file` strictly inside `root`, any letter case. */
160
+ export function insideFolder(root, file) {
161
+ const rel = win.relative(root.toLowerCase(), file.toLowerCase());
162
+ return rel !== "" && !rel.startsWith("..") && !win.isAbsolute(rel);
163
+ }
164
+
165
+ /**
166
+ * What an elevated setup run made in the person's profile, for windowsGiveToPerson: Squirrel's
167
+ * install folder (%LOCALAPPDATA%\<squirrelId>) and its log folder (SquirrelTemp); in the npm cache
168
+ * only what this run's npx wrote, its _npx, _cacache and _logs folders (each whole), npm's
169
+ * update-notifier stamp (_update-notifier-last-checked, a file) and the cache folder alone; and the
170
+ * shortcuts Squirrel made at install (Desktop and Start menu <company>\Nenya.lnk), with their Start
171
+ * menu folder alone.
172
+ */
173
+ export function elevatedRunPlaces({
174
+ env,
175
+ home,
176
+ squirrelId,
177
+ company = "qwntl",
178
+ title = "Nenya",
179
+ }) {
180
+ const profile = env.USERPROFILE || home;
181
+ const local = env.LOCALAPPDATA || win.join(profile, "AppData", "Local");
182
+ const roaming = env.APPDATA || win.join(profile, "AppData", "Roaming");
183
+ const programs = win.join(
184
+ roaming,
185
+ "Microsoft",
186
+ "Windows",
187
+ "Start Menu",
188
+ "Programs",
189
+ company,
190
+ );
191
+ const cache =
192
+ env.npm_config_cache ||
193
+ env.NPM_CONFIG_CACHE ||
194
+ win.join(local, "npm-cache");
195
+ const desktops = [win.join(profile, "Desktop")];
196
+ if (env.OneDrive) desktops.push(win.join(env.OneDrive, "Desktop"));
197
+ return [
198
+ { place: win.join(local, squirrelId), tree: true },
199
+ { place: win.join(local, "SquirrelTemp"), tree: true },
200
+ { place: cache, tree: false },
201
+ { place: win.join(cache, "_npx"), tree: true },
202
+ { place: win.join(cache, "_cacache"), tree: true },
203
+ // npm writes its debug logs to <cache>\_logs (logs-dir) and the update check's stamp beside
204
+ // _cacache (lib/cli/update-notifier.js: <cache>\_cacache\..\_update-notifier-last-checked)
205
+ { place: win.join(cache, "_logs"), tree: true },
206
+ { place: win.join(cache, "_update-notifier-last-checked"), file: true },
207
+ { place: programs, tree: false },
208
+ { place: win.join(programs, `${title}.lnk`), file: true },
209
+ ...desktops.map((desktop) => ({
210
+ place: win.join(desktop, `${title}.lnk`),
211
+ file: true,
212
+ })),
213
+ ];
214
+ }
215
+
216
+ /** How long icacls may take: a whole tree, and a folder or file alone. */
217
+ export const GIVE_TIME_LIMIT_MS = { tree: 300_000, single: 30_000 };
218
+
219
+ /**
220
+ * Why `where` (strictly inside `profile`, both normalised) can't be reached without a link: each
221
+ * step down from the profile must be there and not be a link (junctions read as links). Null when
222
+ * none is.
223
+ */
224
+ function linkOnPath(profile, where, lstat) {
225
+ let at = profile;
226
+ for (const step of where.slice(profile.length + 1).split("\\")) {
227
+ at = win.join(at, step);
228
+ let info;
229
+ try {
230
+ info = lstat(at);
231
+ } catch {
232
+ return `${at} isn't there`;
233
+ }
234
+ if (info.isSymbolicLink()) return `${at} is a link`;
235
+ }
236
+ return null;
237
+ }
238
+
239
+ const samePlace = (a, b) => a.toLowerCase() === b.toLowerCase();
240
+
241
+ /**
242
+ * BA-76: each place to the person (`icacls <place> /setowner *<SID>`), never through a link and
243
+ * never outside the profile. The profile must be a folder on a drive that is where it says it is
244
+ * (its real path, fs.realpathSync.native, is its own). A place must be, by its text, strictly inside
245
+ * it; every step down to it must be there and not be a link or junction; its real path must be
246
+ * itself (so no link anywhere on the way, the profile's own included) and inside the real profile;
247
+ * and it must be a folder, or for `file` a file with one link. A tree goes whole (/T) with links
248
+ * inside acted on as themselves (/L), never followed; a folder alone without /T. Each icacls run
249
+ * has its time limit (GIVE_TIME_LIMIT_MS).
250
+ *
251
+ * Returns { given, refused, unfinished }: the places icacls took, the places left alone because a
252
+ * link is on the way ({ place, why }), and the places icacls didn't finish ({ place, why }: its
253
+ * time limit, or its exit status). A place that isn't there, or isn't the kind expected, is
254
+ * skipped without a word: this run made nothing there.
255
+ */
256
+ export function windowsGiveToPerson({
257
+ places,
258
+ env,
259
+ system,
260
+ lstat = lstatSync,
261
+ realpath = realpathSync.native,
262
+ limits = GIVE_TIME_LIMIT_MS,
263
+ }) {
264
+ const result = { given: [], refused: [], unfinished: [] };
265
+ const profile = clean(env.USERPROFILE);
266
+ if (!FOLDER_ON_DRIVE.test(profile)) return result;
267
+ let realProfile;
268
+ try {
269
+ realProfile = clean(realpath(profile));
270
+ } catch {
271
+ return result;
272
+ }
273
+ if (!samePlace(realProfile, profile)) {
274
+ result.refused.push({
275
+ place: profile,
276
+ why: `the profile folder is reached through a link (it is ${realProfile})`,
277
+ });
278
+ return result;
279
+ }
280
+ const sid = personSid({ env, system });
281
+ if (sid === null) return result;
282
+ const seen = new Set();
283
+ for (const { place, tree = false, file = false } of places) {
284
+ const where = clean(place);
285
+ if (!where || !FOLDER_ON_DRIVE.test(where) || !insideFolder(profile, where))
286
+ continue;
287
+ if (seen.has(where.toLowerCase())) continue;
288
+ seen.add(where.toLowerCase());
289
+ let info;
290
+ try {
291
+ info = lstat(where);
292
+ } catch {
293
+ continue;
294
+ }
295
+ const link = linkOnPath(profile, where, lstat);
296
+ if (link) {
297
+ result.refused.push({ place: where, why: link });
298
+ continue;
299
+ }
300
+ let real;
301
+ try {
302
+ real = clean(realpath(where));
303
+ } catch {
304
+ continue;
305
+ }
306
+ if (!samePlace(real, where) || !insideFolder(realProfile, real)) {
307
+ result.refused.push({
308
+ place: where,
309
+ why: `it is really ${real}, through a link`,
310
+ });
311
+ continue;
312
+ }
313
+ if (file ? !info.isFile() || info.nlink !== 1 : !info.isDirectory())
314
+ continue;
315
+ const how = tree ? ["/T", "/C", "/L", "/Q"] : ["/L", "/C", "/Q"];
316
+ const limit = tree ? limits.tree : limits.single;
317
+ const done = run(
318
+ system,
319
+ env,
320
+ "icacls.exe",
321
+ [where, "/setowner", `*${sid}`, ...how],
322
+ limit,
323
+ );
324
+ if (done.status === 0) result.given.push(where);
325
+ else
326
+ result.unfinished.push({
327
+ place: where,
328
+ why: done.timedOut
329
+ ? `it took longer than ${Math.round(limit / 60_000)} minutes and was stopped`
330
+ : `icacls stopped with ${done.status === null ? "no exit status" : `exit status ${done.status}`}`,
331
+ });
332
+ }
333
+ return result;
334
+ }
335
+
336
+ /** The lines an elevated run says about what it couldn't give back (windowsGiveToPerson's result). */
337
+ export function giveBackLines({ refused, unfinished }) {
338
+ return [
339
+ ...refused.map(
340
+ ({ place, why }) =>
341
+ `${place} was left as it is (${why}); it may still belong to the Administrators group.`,
342
+ ),
343
+ ...unfinished.map(
344
+ ({ place, why }) =>
345
+ `${place} wasn't given back to you (${why}); part of it may still belong to the Administrators group.`,
346
+ ),
347
+ ];
348
+ }
349
+
350
+ /**
351
+ * NPX-BESIDE: the folder of a Nenya installed for everyone (Nenya-Setup.exe /ALLUSERS of 0.11 and
352
+ * a21: Nenya.nsi's HKLM\Software\qwntl\Nenya names it, 64-bit view; else %ProgramW6432%\Nenya), or
353
+ * null. A folder counts only when, normalised, it is on a drive inside %ProgramW6432% or
354
+ * %ProgramFiles% and holds Nenya.exe: a key naming a share, a rootless path or a person's folder is
355
+ * never reached or printed.
356
+ */
357
+ export function windowsSystemWideCopy({ env, system, exists = existsSync }) {
358
+ const shown = run(
359
+ system,
360
+ env,
361
+ "reg.exe",
362
+ ["query", "HKLM\\Software\\qwntl\\Nenya", "/ve", "/reg:64"],
363
+ 30_000,
364
+ );
365
+ const named =
366
+ shown.status === 0
367
+ ? /REG_SZ\s+(.+?)\s*$/m.exec(shown.stdout)?.[1].replace(/^"|"$/g, "")
368
+ : undefined;
369
+ const roots = [
370
+ env.ProgramW6432 || env.PROGRAMW6432,
371
+ env.ProgramFiles || env.PROGRAMFILES,
372
+ ]
373
+ .map(clean)
374
+ .filter((root) => FOLDER_ON_DRIVE.test(root));
375
+ for (const folder of [named, roots[0] ? win.join(roots[0], "Nenya") : null]) {
376
+ if (!folder) continue;
377
+ const where = clean(folder);
378
+ if (
379
+ !/^[A-Za-z]:\\/.test(where) ||
380
+ !roots.some((root) => insideFolder(root, where))
381
+ )
382
+ continue;
383
+ if (exists(win.join(where, "Nenya.exe"))) return where;
384
+ }
385
+ return null;
386
+ }
387
+
388
+ /**
389
+ * The one line for a Nenya installed for everyone beside the person's own. It names no removal: that
390
+ * copy's uninstaller (Settings > Apps runs it) first removes every account's own Nenya from its
391
+ * ledger (`--everyone`), and this install's ledger and data are the same %LOCALAPPDATA%\Nenya.
392
+ */
393
+ export function systemWideCopyLine(folder) {
394
+ return `Another copy of Nenya is installed for everyone on this computer, in ${folder}; this one is yours. Removing that copy, with its uninstaller or from Settings > Apps, also removes this Nenya's data and its connections to your agents.`;
395
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@durableintel/nenya",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.1",
4
+ "description": "Installs Nenya for this account: npx -y @qwntllabs/nenya@latest setup --invite CODE",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "bin": {
8
+ "nenya": "bin/nenya.cjs"
9
+ },
10
+ "files": [
11
+ "bin/nenya.cjs",
12
+ "bin/start.cjs",
13
+ "bin/nenya.js",
14
+ "lib/",
15
+ "release-keys.pub"
16
+ ],
17
+ "engines": {
18
+ "node": ">=20.0.0"
19
+ },
20
+ "scripts": {
21
+ "lint": "eslint .",
22
+ "test": "node --test \"test/*.test.mjs\""
23
+ },
24
+ "devDependencies": {
25
+ "globals": "17.13.0"
26
+ }
27
+ }
@@ -0,0 +1,8 @@
1
+ -----BEGIN PUBLIC KEY-----
2
+ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0xF6LmBoBC7+whLR3UkO1kOmRFZ6
3
+ LhTEOGKzoeeZ+0w97G5SIzcqrO8Ng2r+3+yfTmedwK2oLn+izejyRg2DfQ==
4
+ -----END PUBLIC KEY-----
5
+ -----BEGIN PUBLIC KEY-----
6
+ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIPoCasO6E8BHBhvXm7kqFjjwtgEA
7
+ n3N/tXO9ICxjBUT6l9wQOitL1N6xdLsj5zvfrygZXkKbwSflKFyXhw83vQ==
8
+ -----END PUBLIC KEY-----