ccdeck 3.82.4 → 4.0.0

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 (145) hide show
  1. package/LICENSING.md +42 -4
  2. package/README.md +183 -72
  3. package/THIRD_PARTY_NOTICES.md +243 -17
  4. package/bin/cli/tui.js +58 -4
  5. package/bin/deck.js +27 -1
  6. package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
  7. package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
  8. package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
  9. package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
  10. package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
  11. package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
  12. package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
  13. package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
  14. package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
  15. package/dist/web/assets/UsageHistoryModal-ckawZGoe.js +1 -0
  16. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  17. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  18. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  19. package/dist/web/assets/app-40gNTTfq.js +361 -0
  20. package/dist/web/assets/app-BRjYF6oD.css +1 -0
  21. package/dist/web/assets/{index-B-l-VxLm.js → index-XIY3yFiN.js} +1 -1
  22. package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
  23. package/dist/web/assets/screens-9_ivqfcF.js +12 -0
  24. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  25. package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
  26. package/dist/web/assets/use-account-BUmI-A8e.js +1 -0
  27. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  28. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  29. package/dist/web/index.html +16 -6
  30. package/package.json +13 -1
  31. package/release-notes.json +67 -0
  32. package/src/server/account-client.mjs +196 -0
  33. package/src/server/account-connect.mjs +238 -0
  34. package/src/server/account-flag.mjs +106 -0
  35. package/src/server/account-projects.mjs +1 -1
  36. package/src/server/account-service.mjs +532 -0
  37. package/src/server/account-status.mjs +293 -0
  38. package/src/server/account-store.mjs +137 -0
  39. package/src/server/account-sync.mjs +473 -0
  40. package/src/server/account-token-store.mjs +216 -0
  41. package/src/server/account-ui-fields.mjs +126 -0
  42. package/src/server/account-watch.mjs +1 -1
  43. package/src/server/browser-watch-log.mjs +1 -1
  44. package/src/server/browser-watch-store.mjs +1 -1
  45. package/src/server/ccdeck-account-routes.mjs +252 -0
  46. package/src/server/ccusage-install.mjs +2 -2
  47. package/src/server/ccusage-registry.mjs +4 -4
  48. package/src/server/ccusage-session.mjs +11 -0
  49. package/src/server/claude-accounts.mjs +1 -1
  50. package/src/server/claude-recovery.mjs +9 -4
  51. package/src/server/claude-settings-catalog.mjs +6 -6
  52. package/src/server/claude-settings.mjs +1 -1
  53. package/src/server/codex-auto.mjs +1 -1
  54. package/src/server/codex-cost-usage.mjs +7 -2
  55. package/src/server/codex-live-checkpoint.mjs +24 -9
  56. package/src/server/codex-live-engine.mjs +14 -4
  57. package/src/server/codex-live-handoff.mjs +53 -9
  58. package/src/server/codex-names.mjs +49 -0
  59. package/src/server/codex-translate.mjs +1 -1
  60. package/src/server/codex-ultrafast.d.mts +3 -0
  61. package/src/server/codex-ultrafast.mjs +5 -0
  62. package/src/server/codex-watch.mjs +25 -0
  63. package/src/server/command-panel-engine.mjs +300 -0
  64. package/src/server/command-panel-platform.mjs +99 -0
  65. package/src/server/cswap-auto-choice.mjs +1 -1
  66. package/src/server/cswap-auto-loop.mjs +1 -1
  67. package/src/server/cswap-install.mjs +21 -40
  68. package/src/server/deck-home.mjs +6 -0
  69. package/src/server/deck-prefs.mjs +53 -1
  70. package/src/server/detach.mjs +1 -1
  71. package/src/server/engine-download.mjs +277 -0
  72. package/src/server/engine-install.mjs +378 -0
  73. package/src/server/engine-package.mjs +267 -0
  74. package/src/server/event-log.mjs +7 -1
  75. package/src/server/event-pipeline.mjs +29 -1
  76. package/src/server/ghostty-handoff.mjs +81 -0
  77. package/src/server/index.mjs +143 -5
  78. package/src/server/installer.mjs +4 -1
  79. package/src/server/integrations/jira-write-guard.mjs +14 -208
  80. package/src/server/integrations/store.mjs +37 -19
  81. package/src/server/integrations/write-guard.mjs +223 -0
  82. package/src/server/intel-cpu-temperature.mjs +26 -0
  83. package/src/server/lifecycle.mjs +69 -6
  84. package/src/server/log-replay.mjs +4 -0
  85. package/src/server/login-service.mjs +7 -1
  86. package/src/server/macmon.mjs +1 -1
  87. package/src/server/npm-latest.mjs +1 -1
  88. package/src/server/org-telemetry.mjs +1 -1
  89. package/src/server/output-watch.mjs +4 -1
  90. package/src/server/panel-provenance.mjs +390 -0
  91. package/src/server/pinned-build.mjs +14 -0
  92. package/src/server/prefs-refusal.mjs +8 -1
  93. package/src/server/prefs-routes.mjs +60 -11
  94. package/src/server/pro-engine-client.mjs +339 -0
  95. package/src/server/pro-engine-install.mjs +294 -0
  96. package/src/server/pro-engine-terminal.mjs +308 -0
  97. package/src/server/project-discovery.mjs +139 -0
  98. package/src/server/provider-session-name.mjs +58 -0
  99. package/src/server/quota-closes.mjs +1 -1
  100. package/src/server/quota-history.mjs +1 -1
  101. package/src/server/reports.mjs +86 -21
  102. package/src/server/request-gates.mjs +34 -5
  103. package/src/server/restart-note.mjs +1 -1
  104. package/src/server/seed-boundary.mjs +489 -0
  105. package/src/server/session-counts.mjs +244 -0
  106. package/src/server/session-deck-names.mjs +143 -0
  107. package/src/server/session-enrichment.mjs +43 -6
  108. package/src/server/session-name-route.mjs +73 -0
  109. package/src/server/session-summary.mjs +12 -1
  110. package/src/server/session-transcript-routes.mjs +167 -0
  111. package/src/server/swap-log.mjs +1 -1
  112. package/src/server/system-metrics.mjs +57 -0
  113. package/src/server/terminal-bridge.mjs +485 -0
  114. package/src/server/terminal-folder.mjs +61 -0
  115. package/src/server/terminal-js-routes.mjs +752 -0
  116. package/src/server/terminal-routes.mjs +553 -0
  117. package/src/server/terminal-sessions.mjs +759 -0
  118. package/src/server/terminal-socket.mjs +403 -0
  119. package/src/server/terminal-target.mjs +928 -0
  120. package/src/server/thermal-metrics.mjs +13 -9
  121. package/src/server/tmux-control.mjs +1319 -0
  122. package/src/server/tmux-download.mjs +220 -0
  123. package/src/server/tmux.mjs +542 -0
  124. package/src/server/token-redact.mjs +42 -3
  125. package/src/server/tool-audit-report.mjs +44 -6
  126. package/src/server/tool-audit-routes.mjs +12 -1
  127. package/src/server/tool-audit.mjs +42 -8
  128. package/src/server/traffic-radar-monitor.mjs +1 -1
  129. package/src/server/traffic-radar-permission.mjs +1 -1
  130. package/src/server/transcript-gate.mjs +1 -1
  131. package/src/server/transcript-scan.mjs +15 -7
  132. package/src/server/transcript-turns.mjs +154 -0
  133. package/src/server/tui-network.mjs +1 -0
  134. package/src/server/tui-view.mjs +28 -0
  135. package/src/server/utf8-carry.mjs +159 -0
  136. package/src/server/uv-bootstrap.mjs +2 -2
  137. package/src/server/windows-acl.mjs +158 -0
  138. package/src/server/ws-frames.mjs +690 -0
  139. package/dist/web/assets/BrowserWatchModal-CWVooKxD.js +0 -1
  140. package/dist/web/assets/IntegrationModal-DLX43RIK.js +0 -7
  141. package/dist/web/assets/RadioPanel-Cj6PjrvQ.js +0 -1
  142. package/dist/web/assets/TrafficRadar-Bq1YcuHB.js +0 -8
  143. package/dist/web/assets/UsageHistoryModal-CMSCca5_.js +0 -1
  144. package/dist/web/assets/app-BHxsMz3-.js +0 -358
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
@@ -0,0 +1,159 @@
1
+ // Whole UTF-8 characters at the edges of a byte stream cut into frames.
2
+ //
3
+ // WHY. tmux control mode reports what a pane writes as `%output` lines, and a
4
+ // line ends where tmux's read of the pane ended, which can be inside a
5
+ // character: on tmux 3.8 and 3.4 alike, punctuation-heavy output has lines
6
+ // that stop after the first one or two bytes of a "—", "…", "’" or "”"
7
+ // (terminal-utf8-tmux.test.ts counts them). The relay sends each line as one
8
+ // binary frame, and the panel writes each frame to xterm.js on its own.
9
+ // xterm.js keeps the bytes of a character a write left unfinished and joins
10
+ // them to the next write — except when the bytes it kept end in the
11
+ // continuation byte 0x80: it counts what it kept by reading up to the first
12
+ // byte whose low six bits are zero, so it loses that byte, and with it the
13
+ // character. E2 80 | 94 never shows its "—", nor E2 80 | A6 its "…", nor
14
+ // F0 9F 80 | 80 its four-byte character.
15
+ //
16
+ // WHAT. A frame is sent without the bytes at its end that begin a character
17
+ // the frame does not finish — at most three, since no character is longer
18
+ // than four — and those bytes go out in front of the next frame. Nothing is
19
+ // ever changed, replaced or reordered: every byte goes out once, in order.
20
+ // Only bytes that more bytes could still turn into a character are held, by
21
+ // the well-formed table (Unicode, Table 3-7; E0 needs A0..BF next, ED
22
+ // 80..9F, F0 90..BF, F4 80..8F). Bytes that can never finish one — a lone
23
+ // continuation, C0, C1, F5..FF, the start of a surrogate or of an overlong
24
+ // form — are malformed already and go out as they are, in the frame they came
25
+ // in; so do held bytes as soon as the next frame shows they cannot finish.
26
+ //
27
+ // Held bytes belong to the stream they came from. When the stream breaks off,
28
+ // the caller drops them (drop()); terminal-bridge.mjs says at each break why.
29
+ //
30
+ // INSIDE ONE WRITE, the same loss. xterm.js 6.0 decodes a write longer than
31
+ // 131072 bytes (MAX_PARSEBUFFER_LENGTH in its InputHandler) in pieces of that
32
+ // size, keeping across a piece edge exactly what it keeps across two writes —
33
+ // so a character cut by a piece edge right after a 0x80 is lost the same way.
34
+ // A seed with two thousand lines of coloured history is 200 to 400 KB, one
35
+ // frame and one write: a "—" at byte 131070 of it never showed. A frame cannot
36
+ // be cut where it suits (the seed is ONE frame after `reset`), so
37
+ // padPieceEdges moves the character instead: 0xFF bytes in front of it, as
38
+ // many as it takes for the character to begin at the edge. No character
39
+ // begins or continues with 0xFF, and xterm.js's decoder skips it: it draws
40
+ // nothing and moves nothing.
41
+ //
42
+ // Pure: no I/O, no timers. A frame that ends on a character boundary, which is
43
+ // nearly every frame, is handed back as it came, without a copy; so is a frame
44
+ // no longer than one piece.
45
+
46
+ /** The length of the character a lead byte begins: 1 for ASCII, 2 to 4, or 0
47
+ * for a byte no character begins with (a continuation, C0, C1, F5..FF). */
48
+ function sequenceLength(lead) {
49
+ if (lead < 0x80) return 1;
50
+ if (lead >= 0xc2 && lead <= 0xdf) return 2;
51
+ if (lead >= 0xe0 && lead <= 0xef) return 3;
52
+ if (lead >= 0xf0 && lead <= 0xf4) return 4;
53
+ return 0;
54
+ }
55
+
56
+ /** Whether `second` may follow `lead` in a well-formed character. */
57
+ function secondFits(lead, second) {
58
+ const lo = lead === 0xe0 ? 0xa0 : lead === 0xf0 ? 0x90 : 0x80;
59
+ const hi = lead === 0xed ? 0x9f : lead === 0xf4 ? 0x8f : 0xbf;
60
+ return second >= lo && second <= hi;
61
+ }
62
+
63
+ /**
64
+ * How many bytes at the end of `bytes` begin a character that more bytes could
65
+ * still finish: 0 to 3. 0 when the end is a character boundary, and when the
66
+ * bytes there can never finish a character (they are malformed already).
67
+ */
68
+ export function unfinishedTail(bytes) {
69
+ const n = bytes.length;
70
+ // Back over continuation bytes to the byte that began the last character,
71
+ // looking no further than three: a fourth would make a whole character.
72
+ for (let k = 1; k <= 3 && k <= n; k++) {
73
+ const lead = bytes[n - k];
74
+ if ((lead & 0xc0) === 0x80) continue;
75
+ if (sequenceLength(lead) <= k) return 0;
76
+ // The continuations so far are well formed if the second one is: the
77
+ // table narrows only the second byte, and the loop has seen that the
78
+ // others are 80..BF.
79
+ if (k >= 2 && !secondFits(lead, bytes[n - k + 1])) return 0;
80
+ return k;
81
+ }
82
+ return 0;
83
+ }
84
+
85
+ const EMPTY = Buffer.alloc(0);
86
+
87
+ const asBuffer = (bytes) => (Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
88
+
89
+ /** The pieces xterm.js 6.0 decodes one long write in (MAX_PARSEBUFFER_LENGTH). */
90
+ export const XTERM_PIECE = 131072;
91
+
92
+ /** The filler: a byte no character begins or continues with, which xterm.js's
93
+ * decoder skips without drawing anything. */
94
+ export const FILLER = 0xff;
95
+
96
+ /**
97
+ * `bytes` as one write may carry them: with FILLER in front of every character
98
+ * that a multiple of `piece` would otherwise cut, so that it begins at that
99
+ * edge instead. A character here is a lead byte and the continuation bytes
100
+ * after it that it asks for, well formed or not — one write of the same bytes
101
+ * keeps them together too. At most three filler bytes an edge. Answers `bytes`
102
+ * itself, uncopied, when no edge cuts a character, and always for a write no
103
+ * longer than one piece.
104
+ */
105
+ export function padPieceEdges(bytes, piece = XTERM_PIECE) {
106
+ // A piece must hold any character whole, and the filler of the edge before.
107
+ if (!Number.isSafeInteger(piece) || piece < 8) throw new RangeError("a piece is at least 8 bytes");
108
+ const buf = asBuffer(bytes);
109
+ if (buf.length <= piece) return buf;
110
+ const parts = [];
111
+ let from = 0;
112
+ let added = 0;
113
+ // `edge` counts in the padded write; `at` is the input byte that lands on it.
114
+ for (let edge = piece; edge - added < buf.length; edge += piece) {
115
+ const at = edge - added;
116
+ if ((buf[at] & 0xc0) !== 0x80) continue;
117
+ // Back over the continuations to the byte that began this character.
118
+ for (let k = 1; k <= 3; k++) {
119
+ const lead = buf[at - k];
120
+ if ((lead & 0xc0) === 0x80) continue;
121
+ if (sequenceLength(lead) > k) {
122
+ parts.push(buf.subarray(from, at - k), Buffer.alloc(k, FILLER));
123
+ from = at - k;
124
+ added += k;
125
+ }
126
+ break;
127
+ }
128
+ }
129
+ if (!added) return buf;
130
+ parts.push(buf.subarray(from));
131
+ return Buffer.concat(parts);
132
+ }
133
+
134
+ /**
135
+ * One stream's carry: frame(bytes) answers the bytes to send for a frame —
136
+ * what was held, then the frame, less an unfinished character at its end,
137
+ * which is held instead. The answer may be empty (all of it is held): send
138
+ * nothing then. drop() forgets what is held and answers how many bytes that
139
+ * was; `held` is how many are held now (0 to 3).
140
+ */
141
+ export function utf8Carry() {
142
+ let held = EMPTY;
143
+ return {
144
+ frame(bytes) {
145
+ const buf = asBuffer(bytes);
146
+ const all = held.length ? Buffer.concat([held, buf]) : buf;
147
+ const keep = unfinishedTail(all);
148
+ // A copy of what is kept: the frame's memory is the caller's.
149
+ held = keep ? Buffer.from(all.subarray(all.length - keep)) : EMPTY;
150
+ return keep ? all.subarray(0, all.length - keep) : all;
151
+ },
152
+ drop() {
153
+ const n = held.length;
154
+ held = EMPTY;
155
+ return n;
156
+ },
157
+ get held() { return held.length; },
158
+ };
159
+ }
@@ -286,7 +286,7 @@ export async function bootstrapUv() {
286
286
  // CREATES — it cannot be handed a directory somebody else made. findUv's
287
287
  // ordering is left alone deliberately; it is not wrong on its own, and it
288
288
  // stops being reachable once nobody else can write here.
289
- await mkdir(TOOL_DIR, { recursive: true });
289
+ await mkdir(TOOL_DIR, { recursive: true, mode: 0o700 });
290
290
  staging = await mkdtemp(join(TOOL_DIR, "uv-staging-"));
291
291
  const archivePath = join(staging, asset);
292
292
  await writeFile(archivePath, archive);
@@ -295,7 +295,7 @@ export async function bootstrapUv() {
295
295
  const found = await findUv(staging);
296
296
  if (!found) return { ok: false, reason: "not_in_archive" };
297
297
 
298
- await mkdir(UV_DIR, { recursive: true });
298
+ await mkdir(UV_DIR, { recursive: true, mode: 0o700 });
299
299
  const dest = join(UV_DIR, process.platform === "win32" ? "uv.exe" : "uv");
300
300
 
301
301
  // Copy rather than rename out of staging: the staging dir is in the system
@@ -0,0 +1,158 @@
1
+ // The Windows reader the engine's trust gate asks (pro-engine-install.mjs
2
+ // trustGate): who this process runs as and whether it is elevated, and for a
3
+ // file or folder who owns it, who may write it and whether it is a reparse
4
+ // point or has a second hard link.
5
+ //
6
+ // Everything is asked of tools Windows ships, started by their absolute path
7
+ // under %SystemRoot% (never a PATH lookup), and answered in SIDs only, so no
8
+ // language or account naming changes a result. The target path reaches
9
+ // PowerShell through an environment variable and is never part of the script
10
+ // text. Every failure is a refusal: a non-zero exit, a timeout, output over the
11
+ // bound, JSON that does not parse, a field of the wrong type or a SID of an odd
12
+ // shape all throw an error that names neither a path nor a SID.
13
+ //
14
+ // Deny rules are ignored on purpose: this reports who can be GIVEN write, and
15
+ // the gate refuses on that, so a deny rule never cancels a grant here.
16
+ //
17
+ // NOT TESTED on a real Windows machine outside the CI runner: the unit tests run
18
+ // against a stand-in for the tool calls.
19
+ import { execFile } from 'node:child_process';
20
+ import { promises as fs } from 'node:fs';
21
+ import { win32 as winPath } from 'node:path';
22
+
23
+ export const ACL_TIMEOUT_MS = 10_000;
24
+ export const ACL_MAX_BYTES = 64 * 1024;
25
+ const SID = /^S-1-[0-9-]+$/;
26
+ const failed = () => new Error('The Windows file permissions could not be read.');
27
+
28
+ /** The folder Windows lives in, from the environment, as an absolute drive path. */
29
+ function systemRoot(env) {
30
+ const root = env.SystemRoot;
31
+ if (typeof root !== 'string' || !/^[A-Za-z]:[\\/]/.test(root) || root.includes('\0') || !winPath.isAbsolute(root)) throw failed();
32
+ return root.replace(/[\\/]+$/, '');
33
+ }
34
+
35
+ /** The default `run`: no shell, a timeout, bounded output, no console window.
36
+ * Resolves `{ code, stdout }`; rejects when the tool cannot start, takes too
37
+ * long or says too much. */
38
+ export function boundedRun(file, args, { env, timeoutMs, maxBytes }) {
39
+ return new Promise((resolve, reject) => {
40
+ const child = execFile(file, args, { env, timeout: timeoutMs, maxBuffer: maxBytes, windowsHide: true, shell: false, encoding: 'utf8' }, (error, stdout) => {
41
+ if (!error) return resolve({ code: 0, stdout });
42
+ if (typeof error.code === 'number') return resolve({ code: error.code, stdout: typeof stdout === 'string' ? stdout : '' });
43
+ reject(failed());
44
+ });
45
+ // Windows PowerShell waits for the end of its input when stdin is a pipe,
46
+ // even with a command to run: it gets none.
47
+ child.stdin?.end();
48
+ });
49
+ }
50
+
51
+ /** Splits one CSV line of double-quoted fields. */
52
+ function csvFields(line) {
53
+ const fields = [];
54
+ const pattern = /"((?:[^"]|"")*)"|([^,]*)/y;
55
+ let at = 0;
56
+ while (at <= line.length) {
57
+ pattern.lastIndex = at;
58
+ const match = pattern.exec(line);
59
+ if (!match) break;
60
+ fields.push(match[1] !== undefined ? match[1].replace(/""/g, '"') : match[2]);
61
+ at = pattern.lastIndex;
62
+ if (line[at] !== ',') break;
63
+ at += 1;
64
+ }
65
+ return fields;
66
+ }
67
+
68
+ // The mandatory integrity levels: Medium is 8192, High 12288, System 16384.
69
+ const HIGH_INTEGRITY = 12288;
70
+
71
+ // The rights that let someone change what the engine runs from: write data,
72
+ // append, write extended attributes and attributes, delete, delete children,
73
+ // change permissions, take ownership, and the unmapped generic write and all.
74
+ const WRITE_MASK = 0x500d0156;
75
+ // .NET calls and language statements only, no cmdlet: with the bare
76
+ // environment the child gets, finding a cmdlet can make PowerShell search
77
+ // every module on disk. The JSON is written out by hand; it holds SIDs and a
78
+ // boolean only, and every SID is checked again here. The script goes over as
79
+ // -EncodedCommand (UTF-16LE, base64), so no quoting rule of the command line
80
+ // can change it.
81
+ export const INSPECT_SCRIPT = [
82
+ "$ErrorActionPreference = 'Stop'",
83
+ '$p = $env:CCDECK_ACL_PATH',
84
+ '$attributes = [System.IO.File]::GetAttributes($p)',
85
+ 'if (($attributes -band [System.IO.FileAttributes]::Directory) -ne 0) { $acl = [System.IO.Directory]::GetAccessControl($p) } else { $acl = [System.IO.File]::GetAccessControl($p) }',
86
+ '$sid = [System.Security.Principal.SecurityIdentifier]',
87
+ '$writers = [System.Collections.Generic.List[string]]::new()',
88
+ 'foreach ($rule in $acl.GetAccessRules($true, $true, $sid)) {',
89
+ ' if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) { continue }',
90
+ ' if (([int]$rule.PropagationFlags -band 2) -ne 0) { continue }',
91
+ ` if (([int]$rule.FileSystemRights -band ${WRITE_MASK}) -eq 0) { continue }`,
92
+ ' $value = $rule.IdentityReference.Value',
93
+ ' if (-not $writers.Contains($value)) { $writers.Add($value) }',
94
+ '}',
95
+ '$owner = $acl.GetOwner($sid).Value',
96
+ '$reparse = if (($attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { \'true\' } else { \'false\' }',
97
+ '$quoted = foreach ($w in $writers) { \'"\' + $w + \'"\' }',
98
+ '[Console]::Out.Write(\'{"owner":"\' + $owner + \'","writers":[\' + ($quoted -join \',\') + \'],"reparsePoint":\' + $reparse + \'}\')',
99
+ ].join('\n');
100
+ const ENCODED_SCRIPT = Buffer.from(INSPECT_SCRIPT, 'utf16le').toString('base64');
101
+
102
+ /**
103
+ * `run(file, args, { env, timeoutMs, maxBytes })` resolves `{ code, stdout }`
104
+ * and rejects when it cannot run the tool; tests hand in their own. `env` is
105
+ * the environment the system folder is read from.
106
+ */
107
+ export function createWindowsAcl({ run = boundedRun, env = process.env } = {}) {
108
+ const ask = async (file, args, extra = {}) => {
109
+ const root = systemRoot(env);
110
+ const childEnv = { SystemRoot: root, windir: root, ...extra };
111
+ let answer;
112
+ try {
113
+ answer = await run(file(root), args, { env: childEnv, timeoutMs: ACL_TIMEOUT_MS, maxBytes: ACL_MAX_BYTES });
114
+ } catch {
115
+ throw failed();
116
+ }
117
+ if (!answer || answer.code !== 0 || typeof answer.stdout !== 'string' || answer.stdout.length > ACL_MAX_BYTES) throw failed();
118
+ return answer.stdout;
119
+ };
120
+ const whoami = (...args) => ask((root) => `${root}\\System32\\whoami.exe`, [...args, '/fo', 'csv', '/nh']);
121
+
122
+ return {
123
+ async identity() {
124
+ const userLine = (await whoami('/user')).split(/\r?\n/).find((line) => line.trim());
125
+ const user = userLine ? csvFields(userLine.trim())[1] : undefined;
126
+ if (typeof user !== 'string' || !SID.test(user)) throw failed();
127
+ let level;
128
+ for (const line of (await whoami('/groups')).split(/\r?\n/)) {
129
+ for (const field of csvFields(line.trim())) {
130
+ const match = /^S-1-16-(\d+)$/.exec(field);
131
+ if (match) { level = Number(match[1]); break; }
132
+ }
133
+ if (level !== undefined) break;
134
+ }
135
+ if (!Number.isSafeInteger(level)) throw failed();
136
+ return { user, elevated: level >= HIGH_INTEGRITY };
137
+ },
138
+
139
+ async inspect(target) {
140
+ if (typeof target !== 'string' || !target || target.includes('\0')) throw failed();
141
+ const text = await ask(
142
+ (root) => `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,
143
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-InputFormat', 'None', '-EncodedCommand', ENCODED_SCRIPT],
144
+ { CCDECK_ACL_PATH: target },
145
+ );
146
+ let info;
147
+ try { info = JSON.parse(text); } catch { throw failed(); }
148
+ if (!info || typeof info !== 'object' || Array.isArray(info)) throw failed();
149
+ const { owner, writers, reparsePoint } = info;
150
+ if (typeof owner !== 'string' || !SID.test(owner)) throw failed();
151
+ if (!Array.isArray(writers) || writers.some((w) => typeof w !== 'string' || !SID.test(w))) throw failed();
152
+ if (typeof reparsePoint !== 'boolean') throw failed();
153
+ const links = (await fs.lstat(target).catch(() => { throw failed(); })).nlink;
154
+ if (!Number.isSafeInteger(links) || links < 1) throw failed();
155
+ return { owner, writers, reparsePoint, links };
156
+ },
157
+ };
158
+ }