@bom-pi/core 0.2.1 → 0.2.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom-pi/core",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Core pairing machinery for Bom Pi: ceremonies, transports, durable stores",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -15,6 +15,7 @@
15
15
  "./ingress-receiver.ts": "./src/ingress-receiver.ts",
16
16
  "./lan-pairing.ts": "./src/lan-pairing.ts",
17
17
  "./pairing-storage.ts": "./src/pairing-storage.ts",
18
+ "./windows-native.ts": "./src/windows-native.ts",
18
19
  "./relay-boundary.ts": "./src/relay-boundary.ts",
19
20
  "./relay-mux-wire.ts": "./src/relay-mux-wire.ts",
20
21
  "./relay-remote-channel.ts": "./src/relay-remote-channel.ts",
@@ -10,12 +10,12 @@ import {
10
10
  mkdir,
11
11
  open,
12
12
  readFile,
13
- rename,
14
13
  rm,
15
14
  unlink,
16
15
  type FileHandle,
17
16
  } from "node:fs/promises";
18
17
  import { dirname, join } from "node:path";
18
+ import { assertWindowsPrivatePath, durableRename } from "./windows-native.ts";
19
19
  import {
20
20
  CLEANUP_RESERVE,
21
21
  type ConnectorSnapshot,
@@ -288,7 +288,9 @@ function parseRecord(text: string, pinned: PinnedIdentity): ConnectorSnapshot {
288
288
  return { ...snapshot, pinnedCloudPublicSpki: snapshot.pinnedCloudPublicSpki ?? null };
289
289
  }
290
290
 
291
- function assertRecordFile(stat: Stats): void {
291
+ async function assertRecordFile(stat: Stats, path: string): Promise<void> {
292
+ await assertWindowsPrivatePath(path, "file");
293
+
292
294
  if (
293
295
  !stat.isFile() ||
294
296
  !privateMode(stat, 0o600) ||
@@ -302,6 +304,8 @@ function assertRecordFile(stat: Stats): void {
302
304
  async function checkDirectory(directory: string): Promise<void> {
303
305
  const stat = await lstat(directory).catch(() => fail("missing store directory"));
304
306
 
307
+ await assertWindowsPrivatePath(directory, "directory");
308
+
305
309
  if (!stat.isDirectory() || !privateMode(stat, 0o700)) {
306
310
  fail("store directory must be private (0700) and not a symlink");
307
311
  }
@@ -327,13 +331,15 @@ async function syncDirectory(directory: string): Promise<void> {
327
331
  }
328
332
  }
329
333
 
330
- /** A lease names its holder: `pid:uuid`. A dead (or malformed) pid is a crash leftover. */
334
+ /** A lease names its holder: `pid:uuid`. A lease without a parsable holder was abandoned
335
+ * mid-creation: the writer died before finishing its own identity, so it never returned from
336
+ * the acquire and never guarded a single mutation (every mutation re-validates the lease
337
+ * inode first). Such leases are crash leftovers, not locks — reclaim them. */
331
338
  function leaseStale(content: string): boolean {
332
339
  const separator = content.indexOf(":");
333
340
 
334
341
  if (separator <= 0) {
335
- // A pre-PID lease cannot be proven abandoned; it stays explicit recovery.
336
- return false;
342
+ return true;
337
343
  }
338
344
 
339
345
  const pid = Number.parseInt(content.slice(0, separator), 10);
@@ -367,10 +373,7 @@ async function acquireLock(directory: string, lockPath: string): Promise<LockLea
367
373
  return acquireLock(directory, lockPath);
368
374
  }
369
375
 
370
- fail(
371
- "writer lock exists; explicit recovery required (a pre-PID lease from a crashed " +
372
- "writer cannot be self-reclaimed: verify no daemon runs, then remove the lock)",
373
- );
376
+ fail("writer lock exists; a live writer holds this store (explicit recovery required)");
374
377
  }
375
378
 
376
379
  throw error;
@@ -397,6 +400,8 @@ async function assertLock(directory: string, lockPath: string, lock: LockLease):
397
400
  const owned = await lock.handle.stat();
398
401
  const present = await lstat(lockPath);
399
402
 
403
+ await assertWindowsPrivatePath(lockPath, "file");
404
+
400
405
  if (
401
406
  !owned.isFile() ||
402
407
  !present.isFile() ||
@@ -615,7 +620,7 @@ export class FileConnectorStore implements ConnectorStore {
615
620
  throw error;
616
621
  });
617
622
 
618
- assertRecordFile(stat);
623
+ await assertRecordFile(stat, slot.recordPath);
619
624
 
620
625
  const text = await readFile(slot.recordPath, "utf8").catch(() =>
621
626
  fail("unreadable record"),
@@ -662,7 +667,7 @@ export class FileConnectorStore implements ConnectorStore {
662
667
  return null;
663
668
  }
664
669
 
665
- assertRecordFile(stat);
670
+ await assertRecordFile(stat, this.recordPath);
666
671
 
667
672
  const text = await readFile(this.recordPath, "utf8").catch(() => fail("unreadable record"));
668
673
 
@@ -752,7 +757,7 @@ export class FileConnectorStore implements ConnectorStore {
752
757
  fail("record disappeared under the writer; explicit recovery required");
753
758
  }
754
759
 
755
- assertRecordFile(stat);
760
+ await assertRecordFile(stat, this.recordPath);
756
761
 
757
762
  const text = await readFile(this.recordPath, "utf8").catch(() => fail("unreadable record"));
758
763
 
@@ -794,7 +799,7 @@ export class FileConnectorStore implements ConnectorStore {
794
799
  await assertLock(this.directory, this.lockPath, this.lock);
795
800
  // rename() replaces the directory entry itself: it never writes THROUGH a symlink
796
801
  // planted at the record path.
797
- await rename(temp, this.recordPath);
802
+ await durableRename(temp, this.recordPath);
798
803
  this.fault?.("beforeDirSync");
799
804
  // Past this rename the outcome is already committed on disk. A failure in the parent
800
805
  // fsync is AMBIGUOUS: it is rethrown below — never swallowed, never undone, never
@@ -2,7 +2,8 @@
2
2
  * It also hosts the owner's M4 relay activation record: a durable off-by-default switch with the
3
3
  * same single-writer, atomic, fail-closed discipline as the pairing record itself. */
4
4
  import { randomUUID } from "node:crypto";
5
- import { lstat, mkdir, open, readFile, rename, unlink, type FileHandle } from "node:fs/promises";
5
+ import { lstat, mkdir, open, readFile, rm, unlink, type FileHandle } from "node:fs/promises";
6
+ import { assertWindowsPrivatePath, durableRename } from "./windows-native.ts";
6
7
  import { join } from "node:path";
7
8
 
8
9
  const FILE = "pairing-storage.json";
@@ -83,9 +84,10 @@ function parse(text: string, limit: number): StorageSnapshot {
83
84
  async function checkDirectory(directory: string): Promise<void> {
84
85
  const stat = await lstat(directory);
85
86
 
86
- // POSIX-only privacy proof: Windows has no POSIX mode bits (Node reports 0666 for every
87
- // directory), so on win32 the check is the user-profile directory's own ACL and the mode
88
- // assertion is skipped — same ADR-13 §4 spirit as the endpoint's platform gate.
87
+ await assertWindowsPrivatePath(directory, "directory");
88
+
89
+ // Windows privacy is proved above with the native owner/DACL check, not POSIX bits.
90
+ // Keep the strict POSIX mode proof on platforms that actually implement those bits.
89
91
  const modeOk = process.platform === "win32" || (stat.mode & 0o777) === 0o700;
90
92
 
91
93
  if (!stat.isDirectory() || !modeOk) {
@@ -94,6 +96,12 @@ async function checkDirectory(directory: string): Promise<void> {
94
96
  }
95
97
 
96
98
  async function syncDirectory(directory: string): Promise<void> {
99
+ // Windows commits use MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) after file fsync.
100
+ // No directory-handle flush is attempted or claimed there.
101
+ if (process.platform === "win32") {
102
+ return;
103
+ }
104
+
97
105
  const handle = await open(directory, "r");
98
106
 
99
107
  try {
@@ -103,21 +111,66 @@ async function syncDirectory(directory: string): Promise<void> {
103
111
  }
104
112
  }
105
113
 
114
+ /** A finished lease names its holder: `pid:uuid`. A lease that is malformed, legacy
115
+ * (pre-pid build) or names a provably dead holder never guarded a completed mutation — every
116
+ * mutation requires a finished lease and re-validates the lease inode first (assertLock), and
117
+ * the app's single-instance lock rules out a second live daemon on one data directory — so
118
+ * such leases are crash leftovers and are reclaimed instead of blocking the next boot. */
119
+ function leaseHeldByLiveWriter(content: string): boolean {
120
+ const trimmed = content.trim();
121
+
122
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {
123
+ return false; // legacy bare-uuid build: the lease cannot name a live holder
124
+ }
125
+
126
+ const separator = trimmed.indexOf(":");
127
+ const pid = Number.parseInt(separator > 0 ? trimmed.slice(0, separator) : "", 10);
128
+
129
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
130
+ return false; // the writer died before finishing its own identity
131
+ }
132
+
133
+ try {
134
+ process.kill(pid, 0);
135
+
136
+ return true;
137
+ } catch (error) {
138
+ // EPERM names a live process under another user; anything else is dead or invalid.
139
+ return (error as NodeJS.ErrnoException).code !== "EPERM";
140
+ }
141
+ }
142
+
106
143
  async function acquireLock(directory: string, lockFile: string): Promise<LockLease> {
144
+ const path = join(directory, lockFile);
107
145
  let handle: FileHandle;
108
146
 
109
147
  try {
110
- handle = await open(join(directory, lockFile), "wx", 0o600);
148
+ handle = await open(path, "wx", 0o600);
111
149
  } catch (error) {
112
- if ((error as NodeJS.ErrnoException).code === "EEXIST") {
113
- fail("writer lock exists; explicit recovery required");
150
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
151
+ throw error;
114
152
  }
115
153
 
116
- throw error;
154
+ // An EEXIST lease nobody live holds is a crash leftover: reclaim it once, fail-closed.
155
+ const existing = await readFile(path, "utf8").catch(() => "");
156
+
157
+ if (!leaseHeldByLiveWriter(existing)) {
158
+ await rm(path, { force: true });
159
+
160
+ try {
161
+ handle = await open(path, "wx", 0o600);
162
+ } catch (race) {
163
+ fail(
164
+ "writer lock exists; a live writer holds this store (explicit recovery required)",
165
+ );
166
+ }
167
+ } else {
168
+ fail("writer lock exists; a live writer holds this store (explicit recovery required)");
169
+ }
117
170
  }
118
171
 
119
172
  try {
120
- const identity = randomUUID();
173
+ const identity = `${process.pid}:${randomUUID()}`;
121
174
 
122
175
  await handle.writeFile(identity);
123
176
  await handle.sync();
@@ -137,10 +190,12 @@ async function assertLock(directory: string, lockFile: string, lock: LockLease):
137
190
  const owned = await lock.handle.stat();
138
191
  const present = await lstat(join(directory, lockFile));
139
192
 
193
+ await assertWindowsPrivatePath(join(directory, lockFile), "file");
194
+
140
195
  if (
141
196
  !owned.isFile() ||
142
197
  !present.isFile() ||
143
- (present.mode & 0o777) !== 0o600 ||
198
+ (process.platform !== "win32" && (present.mode & 0o777) !== 0o600) ||
144
199
  owned.dev !== present.dev ||
145
200
  owned.ino !== present.ino ||
146
201
  owned.nlink !== 1 ||
@@ -263,7 +318,7 @@ export class RelaySwitchStore {
263
318
  fail("missing or unreadable relay switch record"),
264
319
  );
265
320
 
266
- if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) {
321
+ if (!stat.isFile() || (process.platform !== "win32" && (stat.mode & 0o777) !== 0o600)) {
267
322
  fail("relay switch record must be a private (0600) regular file");
268
323
  }
269
324
 
@@ -272,6 +327,8 @@ export class RelaySwitchStore {
272
327
  fail("relay switch record must be owned by the current user");
273
328
  }
274
329
 
330
+ await assertWindowsPrivatePath(file, "file");
331
+
275
332
  const record = parseRelaySwitch(
276
333
  await readFile(file, "utf8").catch(() => fail("unreadable relay switch record")),
277
334
  );
@@ -284,6 +341,89 @@ export class RelaySwitchStore {
284
341
  }
285
342
  }
286
343
 
344
+ /** Boot-time open that heals a crashed initializer's leftovers automatically: a lease
345
+ * nobody finished writing (reclaimed by acquireLock), or a relay record that never came
346
+ * to exist. A valid record — OFF or ON — is adopted untouched. A record that exists but
347
+ * is unusable is moved aside as evidence and reset to OFF, which is exactly what the
348
+ * fail-closed read already reported while it sat there. Owner anomalies and live writers
349
+ * still refuse: healing never crosses a security check, and never arms anything. */
350
+ static async openHealing(
351
+ directory: string,
352
+ log?: (line: string) => void,
353
+ ): Promise<RelaySwitchStore> {
354
+ await mkdir(directory, { mode: 0o700, recursive: true });
355
+ await checkDirectory(directory);
356
+
357
+ const lock = await acquireLock(directory, RELAY_LOCK);
358
+
359
+ try {
360
+ const file = join(directory, RELAY_FILE);
361
+ const stat = await lstat(file).catch((error: NodeJS.ErrnoException) => {
362
+ if (error.code === "ENOENT") {
363
+ return null;
364
+ }
365
+
366
+ throw error;
367
+ });
368
+
369
+ let record: RelaySwitchSnapshot | null = null;
370
+
371
+ if (stat !== null) {
372
+ const regular = stat.isFile();
373
+ const privateFile =
374
+ regular && (process.platform === "win32" || (stat.mode & 0o777) === 0o600);
375
+ const owned = process.getuid === undefined || stat.uid === process.getuid();
376
+
377
+ if (!owned) {
378
+ // Parity with open(): a re-owned record is never adopted — and never healed.
379
+ fail("relay switch record must be owned by the current user");
380
+ }
381
+
382
+ if (regular && privateFile) {
383
+ try {
384
+ await assertWindowsPrivatePath(file, "file");
385
+ record = parseRelaySwitch(await readFile(file, "utf8"));
386
+ } catch (error) {
387
+ if (!/corrupt/.test(String((error as Error)?.message ?? ""))) {
388
+ // Read or platform-security anomalies need eyes, not healing.
389
+ throw error;
390
+ }
391
+
392
+ record = null;
393
+ }
394
+ }
395
+ }
396
+
397
+ if (record !== null) {
398
+ return new RelaySwitchStore(directory, record, lock);
399
+ }
400
+
401
+ const store = new RelaySwitchStore(
402
+ directory,
403
+ { version: 1, relay: { enabled: false } },
404
+ lock,
405
+ );
406
+
407
+ if (stat !== null) {
408
+ await durableRename(file, join(directory, "relay-switch.corrupt.json"));
409
+ log?.(
410
+ "relay switch: prior record unusable; moved aside to " +
411
+ "relay-switch.corrupt.json and reset to OFF",
412
+ );
413
+ } else {
414
+ log?.("relay switch: no prior record (crashed initializer); created OFF");
415
+ }
416
+
417
+ await store.persist(store.record);
418
+
419
+ return store;
420
+ } catch (error) {
421
+ await releaseLock(directory, RELAY_LOCK, lock);
422
+
423
+ throw error;
424
+ }
425
+ }
426
+
287
427
  /** Release only this instance's lock; parity with PairingStorage.close. */
288
428
  async close(): Promise<void> {
289
429
  if (this.writing) {
@@ -358,7 +498,7 @@ export class RelaySwitchStore {
358
498
  await handle.close();
359
499
  handle = undefined;
360
500
  await assertLock(this.directory, RELAY_LOCK, this.lock);
361
- await rename(temp, join(this.directory, RELAY_FILE));
501
+ await durableRename(temp, join(this.directory, RELAY_FILE));
362
502
  await assertLock(this.directory, RELAY_LOCK, this.lock);
363
503
  await syncDirectory(this.directory);
364
504
  await assertLock(this.directory, RELAY_LOCK, this.lock);
@@ -464,7 +604,7 @@ export class PairingStorage {
464
604
  const file = join(directory, FILE);
465
605
  const stat = await lstat(file).catch(() => fail("missing or unreadable record"));
466
606
 
467
- if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) {
607
+ if (!stat.isFile() || (process.platform !== "win32" && (stat.mode & 0o777) !== 0o600)) {
468
608
  fail("record must be a private (0600) regular file");
469
609
  }
470
610
 
@@ -474,6 +614,8 @@ export class PairingStorage {
474
614
  fail("record must be owned by the current user");
475
615
  }
476
616
 
617
+ await assertWindowsPrivatePath(file, "file");
618
+
477
619
  const state = parse(
478
620
  await readFile(file, "utf8").catch(() => fail("unreadable record")),
479
621
  capacity,
@@ -619,10 +761,16 @@ export class PairingStorage {
619
761
  fail("record revision changed or unreadable");
620
762
  }
621
763
 
622
- if (expected === null || !stat.isFile() || (stat.mode & 0o777) !== 0o600) {
764
+ if (
765
+ expected === null ||
766
+ !stat.isFile() ||
767
+ (process.platform !== "win32" && (stat.mode & 0o777) !== 0o600)
768
+ ) {
623
769
  fail("record revision changed or unreadable");
624
770
  }
625
771
 
772
+ await assertWindowsPrivatePath(file, "file");
773
+
626
774
  const text = await readFile(file, "utf8").catch(() => fail("record revision changed"));
627
775
  const disk = parse(text, this.capacity);
628
776
 
@@ -655,7 +803,7 @@ export class PairingStorage {
655
803
  await assertLock(this.directory, LOCK, this.lock);
656
804
  await this.assertRecord(expected);
657
805
  await assertLock(this.directory, LOCK, this.lock);
658
- await rename(temp, join(this.directory, FILE));
806
+ await durableRename(temp, join(this.directory, FILE));
659
807
  this.fault?.("beforeDirSync");
660
808
  await assertLock(this.directory, LOCK, this.lock);
661
809
  await syncDirectory(this.directory);
@@ -0,0 +1,326 @@
1
+ # Trusted, transport/filesystem-only Win32 bridge. No pairing decisions or credentials in argv.
2
+ param([ValidateSet('worker', 'server')][string]$Mode, [string]$PipeName = '')
3
+ $ErrorActionPreference = 'Stop'
4
+ # A Node process launched from pwsh 7 can inherit incompatible Core-only module paths.
5
+ # Load only the trusted Windows PowerShell built-ins this bridge was compiled against.
6
+ $env:PSModulePath = "$PSHOME\Modules"
7
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
8
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
9
+ $source = @'
10
+ using System;
11
+ using System.IO;
12
+ using System.IO.Pipes;
13
+ using System.Text;
14
+ using System.Threading;
15
+ using System.Threading.Tasks;
16
+ using System.Collections.Concurrent;
17
+ using System.ComponentModel;
18
+ using System.Runtime.InteropServices;
19
+ using System.Security.AccessControl;
20
+ using System.Security.Principal;
21
+ using Microsoft.Win32.SafeHandles;
22
+
23
+ public static class BomWindowsNative {
24
+ const int RequestLimit = 4096, ResponseLimit = 65536;
25
+ static readonly object OutputLock = new object();
26
+ static readonly WindowsIdentity Identity = WindowsIdentity.GetCurrent();
27
+ static readonly SecurityIdentifier User = Identity.User;
28
+ static readonly ConcurrentDictionary<string, TaskCompletionSource<byte[]>> Replies = new ConcurrentDictionary<string, TaskCompletionSource<byte[]>>();
29
+ static readonly ConcurrentDictionary<string, CancellationTokenSource> Deadlines = new ConcurrentDictionary<string, CancellationTokenSource>();
30
+ static readonly ConcurrentDictionary<string, NamedPipeServerStream> Connections = new ConcurrentDictionary<string, NamedPipeServerStream>();
31
+ static volatile bool Stopping;
32
+ static NamedPipeServerStream Listener;
33
+ static int Active;
34
+
35
+ [StructLayout(LayoutKind.Sequential)]
36
+ struct SecurityAttributes {
37
+ public int Length;
38
+ public IntPtr Descriptor;
39
+ [MarshalAs(UnmanagedType.Bool)] public bool Inherit;
40
+ }
41
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
42
+ static extern SafePipeHandle CreateNamedPipe(string name, uint openMode, uint pipeMode, uint instances, uint outSize, uint inSize, uint timeout, ref SecurityAttributes security);
43
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
44
+ static extern bool WaitNamedPipe(string name, uint timeout);
45
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
46
+ static extern bool MoveFileEx(string source, string destination, uint flags);
47
+
48
+ static void Emit(string line) {
49
+ lock (OutputLock) { Console.WriteLine(line); Console.Out.Flush(); }
50
+ }
51
+ static string Encode(string value) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(value)); }
52
+ static string Decode(string value) {
53
+ if (value.Length > 100000) throw new InvalidOperationException("size-bound");
54
+ return Encoding.UTF8.GetString(Convert.FromBase64String(value));
55
+ }
56
+ static string ErrorCode(Exception error) {
57
+ if (error is AggregateException) error = error.GetBaseException();
58
+ if (error is OperationCanceledException || error is TimeoutException) return "timeout";
59
+ if (error is UnauthorizedAccessException) return "access-denied";
60
+ if (error is InvalidOperationException) return error.Message;
61
+ if (error is Win32Exception) return "win32-" + ((Win32Exception)error).NativeErrorCode;
62
+ return "native-io";
63
+ }
64
+ static bool TrustedFilePrincipal(string sid) {
65
+ return sid == User.Value || sid == "S-1-5-18" || sid == "S-1-5-32-544"
66
+ || sid == "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
67
+ }
68
+ static void CheckAncestors(string path) {
69
+ string current = Path.GetDirectoryName(Path.GetFullPath(path));
70
+ const FileSystemRights unsafeRights = FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership;
71
+ while (!String.IsNullOrEmpty(current)) {
72
+ if ((File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) throw new InvalidOperationException("reparse-path");
73
+ DirectorySecurity security = Directory.GetAccessControl(current, AccessControlSections.Owner | AccessControlSections.Access);
74
+ string owner = security.GetOwner(typeof(SecurityIdentifier)).Value;
75
+ // TrustedInstaller is a privileged Windows system owner (like SYSTEM), not a peer user.
76
+ bool installer = owner == "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
77
+ if (!TrustedFilePrincipal(owner) && owner != Identity.Owner.Value && !installer) throw new InvalidOperationException("unsafe-ancestor");
78
+ foreach (FileSystemAccessRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier))) {
79
+ if (rule.AccessControlType == AccessControlType.Allow && (rule.PropagationFlags & PropagationFlags.InheritOnly) == 0
80
+ && !TrustedFilePrincipal(rule.IdentityReference.Value) && (rule.FileSystemRights & unsafeRights) != 0)
81
+ throw new InvalidOperationException("unsafe-ancestor");
82
+ }
83
+ DirectoryInfo parent = Directory.GetParent(current);
84
+ current = parent == null ? null : parent.FullName;
85
+ }
86
+ }
87
+ public static void CheckPrivate(string path, bool directory) {
88
+ FileAttributes attributes = File.GetAttributes(path);
89
+ if ((attributes & FileAttributes.ReparsePoint) != 0) throw new InvalidOperationException("reparse-path");
90
+ if (((attributes & FileAttributes.Directory) != 0) != directory) throw new InvalidOperationException("path-type");
91
+ FileSystemSecurity security = directory
92
+ ? (FileSystemSecurity)Directory.GetAccessControl(path, AccessControlSections.Owner | AccessControlSections.Access)
93
+ : (FileSystemSecurity)File.GetAccessControl(path, AccessControlSections.Owner | AccessControlSections.Access);
94
+ string owner = security.GetOwner(typeof(SecurityIdentifier)).Value;
95
+ // Privileged system owners are trusted like POSIX root. Still require this account's
96
+ // actual access below; a different ordinary owner can rewrite the DACL and is refused.
97
+ if (!TrustedFilePrincipal(owner) && owner != Identity.Owner.Value) throw new InvalidOperationException("foreign-owner");
98
+ bool ownAccess = false;
99
+ foreach (FileSystemAccessRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier))) {
100
+ if ((rule.PropagationFlags & PropagationFlags.InheritOnly) != 0 || rule.AccessControlType != AccessControlType.Allow) continue;
101
+ string sid = rule.IdentityReference.Value;
102
+ if (!TrustedFilePrincipal(sid)) throw new InvalidOperationException("private-acl");
103
+ if (sid == User.Value || sid == Identity.Owner.Value) ownAccess = true;
104
+ }
105
+ if (!ownAccess) throw new InvalidOperationException("private-acl");
106
+ CheckAncestors(path);
107
+ }
108
+ static void DurableMove(string source, string destination) {
109
+ CheckPrivate(source, false);
110
+ CheckPrivate(Path.GetDirectoryName(destination), true);
111
+ if (File.Exists(destination) || Directory.Exists(destination)) CheckPrivate(destination, false);
112
+ // MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH. File bytes were flushed by Node
113
+ // first. This is the Win32 replacement contract, not a pretend directory fsync.
114
+ if (!MoveFileEx(source, destination, 0x1 | 0x8)) throw new Win32Exception(Marshal.GetLastWin32Error());
115
+ }
116
+ static void VerifyPipe(PipeStream pipe) {
117
+ PipeSecurity security = pipe.GetAccessControl();
118
+ if (security.GetOwner(typeof(SecurityIdentifier)).Value != User.Value || !security.AreAccessRulesProtected)
119
+ throw new InvalidOperationException("pipe-identity");
120
+ bool ownerAllowed = false;
121
+ foreach (PipeAccessRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier))) {
122
+ if (rule.AccessControlType != AccessControlType.Allow) continue;
123
+ if (rule.IdentityReference.Value != User.Value) throw new InvalidOperationException("pipe-acl");
124
+ if ((rule.PipeAccessRights & PipeAccessRights.FullControl) == PipeAccessRights.FullControl) ownerAllowed = true;
125
+ }
126
+ if (!ownerAllowed) throw new InvalidOperationException("pipe-acl");
127
+ }
128
+ static bool WaitForPipe(string name, int milliseconds) {
129
+ DateTime deadline = DateTime.UtcNow.AddMilliseconds(milliseconds);
130
+ while (true) {
131
+ if (WaitNamedPipe("\\\\.\\pipe\\" + name, 1)) return true;
132
+ int code = Marshal.GetLastWin32Error();
133
+ if (code == 231) return true; // ERROR_PIPE_BUSY: exists, all busy
134
+ if (code == 5) throw new UnauthorizedAccessException(); // exists, this user denied
135
+ if (code != 2) return false; // not FILE_NOT_FOUND: not ours
136
+ // A serving instance can be missing for a moment between accept and re-arm.
137
+ if (DateTime.UtcNow >= deadline) return false;
138
+ System.Threading.Thread.Sleep(10);
139
+ }
140
+ }
141
+ static void ValidateName(string name) {
142
+ if (!System.Text.RegularExpressions.Regex.IsMatch(name, "^bom-pi-admin-[a-f0-9]{64}$"))
143
+ throw new InvalidOperationException("pipe-name");
144
+ }
145
+ static NamedPipeServerStream NewPipe(string name, bool first) {
146
+ // Install the protected, owner-only DACL AT CREATION, never after accepting clients.
147
+ PipeSecurity acl = new PipeSecurity();
148
+ acl.SetOwner(User);
149
+ acl.SetAccessRuleProtection(true, false);
150
+ acl.AddAccessRule(new PipeAccessRule(new SecurityIdentifier("S-1-5-2"), PipeAccessRights.FullControl, AccessControlType.Deny));
151
+ acl.AddAccessRule(new PipeAccessRule(User, PipeAccessRights.FullControl, AccessControlType.Allow));
152
+ byte[] binary = acl.GetSecurityDescriptorBinaryForm();
153
+ IntPtr descriptor = Marshal.AllocHGlobal(binary.Length);
154
+ Marshal.Copy(binary, 0, descriptor, binary.Length);
155
+ try {
156
+ SecurityAttributes security = new SecurityAttributes();
157
+ security.Length = Marshal.SizeOf(typeof(SecurityAttributes));
158
+ security.Descriptor = descriptor;
159
+ security.Inherit = false;
160
+ uint flags = 0x3u | 0x40000000u | (first ? 0x80000u : 0u);
161
+ // PIPE_REJECT_REMOTE_CLIENTS, byte mode. First instance is exclusive, atomically.
162
+ SafePipeHandle handle = CreateNamedPipe("\\\\.\\pipe\\" + name, flags, 0x8, 255, 65537, 4096, 0, ref security);
163
+ if (handle.IsInvalid) { int code = Marshal.GetLastWin32Error(); handle.Dispose(); throw new Win32Exception(code); }
164
+ NamedPipeServerStream pipe = new NamedPipeServerStream(PipeDirection.InOut, true, false, handle);
165
+ try { VerifyPipe(pipe); return pipe; } catch { pipe.Dispose(); throw; }
166
+ } finally { Marshal.FreeHGlobal(descriptor); }
167
+ }
168
+ static async Task<byte[]> ReadLine(Stream stream, int limit, CancellationToken token) {
169
+ byte[] buffer = new byte[1024];
170
+ using (MemoryStream body = new MemoryStream()) {
171
+ while (true) {
172
+ int count = await stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
173
+ if (count == 0) throw new EndOfStreamException();
174
+ if (body.Length + count > limit) throw new InvalidOperationException("too-large");
175
+ int newline = Array.IndexOf(buffer, (byte)10, 0, count);
176
+ if (newline >= 0) {
177
+ if (newline != count - 1) throw new InvalidOperationException("malformed");
178
+ body.Write(buffer, 0, newline);
179
+ return body.ToArray();
180
+ }
181
+ body.Write(buffer, 0, count);
182
+ }
183
+ }
184
+ }
185
+ static async Task WriteLine(Stream stream, byte[] body) {
186
+ if (body.Length > ResponseLimit) throw new InvalidOperationException("too-large");
187
+ await stream.WriteAsync(body, 0, body.Length).ConfigureAwait(false);
188
+ await stream.WriteAsync(new byte[] { 10 }, 0, 1).ConfigureAwait(false);
189
+ await stream.FlushAsync().ConfigureAwait(false);
190
+ }
191
+ static async Task Handle(NamedPipeServerStream pipe, string id) {
192
+ TaskCompletionSource<byte[]> reply = new TaskCompletionSource<byte[]>(TaskCreationOptions.RunContinuationsAsynchronously);
193
+ CancellationTokenSource deadline = new CancellationTokenSource(10000);
194
+ Replies[id] = reply;
195
+ Deadlines[id] = deadline;
196
+ try {
197
+ byte[] request = await ReadLine(pipe, RequestLimit, deadline.Token).ConfigureAwait(false);
198
+ using (deadline.Token.Register(() => reply.TrySetCanceled())) {
199
+ Emit("REQUEST\t" + id + "\t" + Convert.ToBase64String(request));
200
+ byte[] response = await reply.Task.ConfigureAwait(false);
201
+ await WriteLine(pipe, response).ConfigureAwait(false);
202
+ }
203
+ } catch (InvalidOperationException error) {
204
+ string code = error.Message == "too-large" ? "too-large" : "malformed";
205
+ // Windows PowerShell 5.1 compiles C# 5, which cannot await inside catch.
206
+ try { WriteLine(pipe, Encoding.UTF8.GetBytes("{\"ok\":false,\"op\":null,\"error\":\"" + code + "\",\"message\":\"Invalid bounded request line\"}")).GetAwaiter().GetResult(); } catch { }
207
+ } catch { /* Closed, timed-out, or disconnected transport: never run another request. */ }
208
+ finally {
209
+ TaskCompletionSource<byte[]> removedReply;
210
+ CancellationTokenSource removedDeadline;
211
+ NamedPipeServerStream removedConnection;
212
+ Replies.TryRemove(id, out removedReply);
213
+ Deadlines.TryRemove(id, out removedDeadline);
214
+ Connections.TryRemove(id, out removedConnection);
215
+ deadline.Dispose();
216
+ pipe.Dispose();
217
+ Interlocked.Decrement(ref Active);
218
+ }
219
+ }
220
+ static void Stop() {
221
+ Stopping = true;
222
+ if (Listener != null) Listener.Dispose();
223
+ foreach (var connection in Connections.Values) connection.Dispose();
224
+ foreach (var reply in Replies.Values) reply.TrySetCanceled();
225
+ }
226
+ public static void Server(string name) {
227
+ ValidateName(name);
228
+ Listener = NewPipe(name, true);
229
+ Emit("READY");
230
+ Task.Factory.StartNew(() => {
231
+ try {
232
+ string line;
233
+ while ((line = Console.ReadLine()) != null) {
234
+ if (line == "CLOSE") break;
235
+ if (line.Length > 100000) break;
236
+ string[] fields = line.Split('\t');
237
+ if (fields.Length != 3) break;
238
+ if (fields[0] == "REPLY") {
239
+ TaskCompletionSource<byte[]> pending;
240
+ byte[] bytes = Convert.FromBase64String(fields[2]);
241
+ if (bytes.Length <= ResponseLimit && Replies.TryGetValue(fields[1], out pending)) pending.TrySetResult(bytes);
242
+ } else if (fields[0] == "WAIT" && fields[2] == "1200000") {
243
+ CancellationTokenSource deadline;
244
+ if (Deadlines.TryGetValue(fields[1], out deadline)) {
245
+ try { deadline.CancelAfter(1200000); } catch (ObjectDisposedException) { }
246
+ }
247
+ } else break;
248
+ }
249
+ } catch { } finally { Stop(); }
250
+ }, TaskCreationOptions.LongRunning);
251
+ try {
252
+ while (!Stopping) {
253
+ Listener.WaitForConnection();
254
+ NamedPipeServerStream connected = Listener;
255
+ if (Interlocked.Increment(ref Active) > 4) {
256
+ try { WriteLine(connected, Encoding.UTF8.GetBytes("{\"ok\":false,\"op\":null,\"error\":\"busy\",\"message\":\"Too many concurrent admin connections\"}")).GetAwaiter().GetResult(); } catch { }
257
+ connected.Dispose();
258
+ Interlocked.Decrement(ref Active);
259
+ Listener = NewPipe(name, false);
260
+ continue;
261
+ }
262
+ // Keep an owner-only instance alive before the connected instance can close.
263
+ Listener = NewPipe(name, false);
264
+ string id = Guid.NewGuid().ToString("N");
265
+ Connections[id] = connected;
266
+ Task.Run(() => Handle(connected, id));
267
+ }
268
+ } catch { if (!Stopping) throw; } finally { Stop(); }
269
+ }
270
+ static async Task<string> Client(string name, string request, int timeout) {
271
+ ValidateName(name);
272
+ // Distinguish "no daemon" (absent/denied) from "daemon too slow" (busy) so callers
273
+ // can report the honest state instead of waiting out the request deadline.
274
+ if (!WaitForPipe(name, 500)) throw new InvalidOperationException("pipe-unavailable");
275
+ byte[] bytes = Encoding.UTF8.GetBytes(request);
276
+ if (bytes.Length + 1 > RequestLimit) throw new InvalidOperationException("too-large");
277
+ using (NamedPipeClientStream pipe = new NamedPipeClientStream(".", name,
278
+ PipeAccessRights.ReadWrite | PipeAccessRights.ReadPermissions, PipeOptions.Asynchronous,
279
+ TokenImpersonationLevel.Identification, HandleInheritability.None)) {
280
+ using (CancellationTokenSource deadline = new CancellationTokenSource(timeout)) {
281
+ await pipe.ConnectAsync(timeout, deadline.Token).ConfigureAwait(false);
282
+ // Verify THIS connected handle, not a pathname that an attacker can replace.
283
+ VerifyPipe(pipe);
284
+ await pipe.WriteAsync(bytes, 0, bytes.Length, deadline.Token).ConfigureAwait(false);
285
+ await pipe.WriteAsync(new byte[] { 10 }, 0, 1, deadline.Token).ConfigureAwait(false);
286
+ byte[] response = await ReadLine(pipe, ResponseLimit + 1, deadline.Token).ConfigureAwait(false);
287
+ return Encoding.UTF8.GetString(response);
288
+ }
289
+ }
290
+ }
291
+ static async Task Command(string[] fields) {
292
+ string id = fields[1];
293
+ try {
294
+ string result = "";
295
+ if (fields[0] == "DIR" && fields.Length == 3) CheckPrivate(Decode(fields[2]), true);
296
+ else if (fields[0] == "FILE" && fields.Length == 3) CheckPrivate(Decode(fields[2]), false);
297
+ else if (fields[0] == "MOVE" && fields.Length == 4) DurableMove(Decode(fields[2]), Decode(fields[3]));
298
+ else if (fields[0] == "CLIENT" && fields.Length == 5)
299
+ result = await Client(Decode(fields[2]), Decode(fields[3]), Int32.Parse(fields[4])).ConfigureAwait(false);
300
+ else throw new InvalidOperationException("command");
301
+ Emit("OK\t" + id + "\t" + Encode(result));
302
+ } catch (Exception error) { Emit("ERROR\t" + id + "\t" + ErrorCode(error)); }
303
+ }
304
+ public static void Worker() {
305
+ Emit("READY");
306
+ string line;
307
+ while ((line = Console.ReadLine()) != null) {
308
+ if (line.Length > 100000) throw new InvalidOperationException("size-bound");
309
+ string[] fields = line.Split('\t');
310
+ if (fields.Length < 3 || !System.Text.RegularExpressions.Regex.IsMatch(fields[1], "^[a-f0-9]{32}$"))
311
+ throw new InvalidOperationException("command");
312
+ // IPC clients may wait for approval; do not block unrelated filesystem commands.
313
+ Task.Run(() => Command(fields));
314
+ }
315
+ }
316
+ }
317
+ '@
318
+ try {
319
+ Add-Type -TypeDefinition $source -ReferencedAssemblies System.dll,System.Core.dll,System.Security.dll
320
+ if ($Mode -eq 'server') { [BomWindowsNative]::Server($PipeName) }
321
+ else { [BomWindowsNative]::Worker() }
322
+ } catch {
323
+ # Startup contains only static code and the public pipe name, never a request/receipt.
324
+ [Console]::Error.WriteLine('WINDOWS_NATIVE_START_FAILED: ' + $_.Exception.GetBaseException().Message)
325
+ exit 1
326
+ }
@@ -0,0 +1,453 @@
1
+ /** Native Windows IPC/ACL and durable-replace adapter. The PowerShell bridge hosts only
2
+ * Win32 transport/filesystem primitives; the core remains the sole pairing dispatcher/writer.
3
+ * No secret, request or receipt travels in argv, environment variables or diagnostic output. */
4
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
5
+ import { randomBytes } from "node:crypto";
6
+ import { rename } from "node:fs/promises";
7
+ import { join, resolve } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const SCRIPT = fileURLToPath(new URL("./windows-native.ps1", import.meta.url));
11
+ const MAX_FRAME = 100_000;
12
+ const START_TIMEOUT = 30_000;
13
+
14
+ export class WindowsNativeError extends Error {
15
+ readonly code: string;
16
+
17
+ constructor(code: string) {
18
+ super(`Windows native operation refused (${code})`);
19
+ this.code = code;
20
+ }
21
+ }
22
+
23
+ function launch(mode: "worker" | "server", pipeName?: string): ChildProcessWithoutNullStreams {
24
+ if (process.platform !== "win32") {
25
+ throw new WindowsNativeError("not-windows");
26
+ }
27
+
28
+ const executable = join(
29
+ process.env.SystemRoot ?? "C:\\Windows",
30
+ "System32",
31
+ "WindowsPowerShell",
32
+ "v1.0",
33
+ "powershell.exe",
34
+ );
35
+
36
+ return spawn(
37
+ executable,
38
+ [
39
+ "-NoLogo",
40
+ "-NoProfile",
41
+ "-NonInteractive",
42
+ "-ExecutionPolicy",
43
+ "Bypass",
44
+ "-File",
45
+ SCRIPT,
46
+ "-Mode",
47
+ mode,
48
+ ...(pipeName ? ["-PipeName", pipeName] : []),
49
+ ],
50
+ { windowsHide: true, stdio: ["pipe", "pipe", "pipe"] },
51
+ );
52
+ }
53
+
54
+ function reference(child: ChildProcessWithoutNullStreams, active: boolean): void {
55
+ const operation = active ? "ref" : "unref";
56
+
57
+ child[operation]();
58
+
59
+ for (const stream of [child.stdin, child.stdout, child.stderr]) {
60
+ const handle = stream as unknown as { ref?: () => void; unref?: () => void };
61
+
62
+ handle[operation]?.();
63
+ }
64
+ }
65
+
66
+ /** Bounded private inherited-channel framing. Never echo malformed frames: they may contain
67
+ * receipt bytes. stderr is drained with a hard bound but is never copied into errors/logs. */
68
+ function lines(
69
+ child: ChildProcessWithoutNullStreams,
70
+ receive: (line: string) => void,
71
+ fail: (error: WindowsNativeError) => void,
72
+ ): void {
73
+ let buffered = "";
74
+ let stderrBytes = 0;
75
+
76
+ child.stdout.setEncoding("utf8");
77
+ child.stdout.on("data", (chunk: string) => {
78
+ buffered += chunk;
79
+
80
+ while (true) {
81
+ const newline = buffered.indexOf("\n");
82
+
83
+ if (newline === -1) {
84
+ break;
85
+ }
86
+
87
+ if (newline > MAX_FRAME) {
88
+ fail(new WindowsNativeError("frame-bound"));
89
+
90
+ return;
91
+ }
92
+
93
+ const line = buffered.slice(0, newline).replace(/\r$/, "");
94
+
95
+ buffered = buffered.slice(newline + 1);
96
+ receive(line);
97
+ }
98
+
99
+ if (buffered.length > MAX_FRAME) {
100
+ fail(new WindowsNativeError("frame-bound"));
101
+ }
102
+ });
103
+ child.stderr.on("data", (chunk: Buffer) => {
104
+ stderrBytes += chunk.byteLength;
105
+
106
+ if (stderrBytes > 16_384) {
107
+ fail(new WindowsNativeError("diagnostic-bound"));
108
+ }
109
+ });
110
+ child.on("error", () => fail(new WindowsNativeError("helper-start")));
111
+ child.stdin.on("error", () => fail(new WindowsNativeError("helper-channel")));
112
+ child.on("exit", () => fail(new WindowsNativeError("helper-exit")));
113
+ }
114
+
115
+ type Pending = {
116
+ resolve(value: string): void;
117
+ reject(error: WindowsNativeError): void;
118
+ timer: ReturnType<typeof setTimeout>;
119
+ };
120
+
121
+ let worker: NativeWorker | undefined;
122
+
123
+ class NativeWorker {
124
+ readonly child: ChildProcessWithoutNullStreams;
125
+ readonly ready: Promise<void>;
126
+ readonly pending = new Map<string, Pending>();
127
+ failed: WindowsNativeError | undefined;
128
+
129
+ constructor() {
130
+ this.child = launch("worker");
131
+ let resolveReady!: () => void;
132
+ let rejectReady!: (error: WindowsNativeError) => void;
133
+ let started = false;
134
+
135
+ this.ready = new Promise((resolve, reject) => {
136
+ resolveReady = resolve;
137
+ rejectReady = reject;
138
+ });
139
+
140
+ const timer = setTimeout(
141
+ () => this.fail(new WindowsNativeError("helper-deadline")),
142
+ START_TIMEOUT,
143
+ );
144
+
145
+ // Captured by the fail path; ready errors never become unhandled rejections.
146
+ void this.ready.catch(() => undefined);
147
+ this.ready.then(
148
+ () => clearTimeout(timer),
149
+ () => clearTimeout(timer),
150
+ );
151
+ lines(
152
+ this.child,
153
+ (line) => {
154
+ if (line === "READY" && !started) {
155
+ started = true;
156
+ resolveReady();
157
+ reference(this.child, false);
158
+
159
+ return;
160
+ }
161
+
162
+ const [kind, id, payload, extra] = line.split("\t");
163
+ const pending = id ? this.pending.get(id) : undefined;
164
+
165
+ if (
166
+ !started ||
167
+ !id ||
168
+ payload === undefined ||
169
+ extra !== undefined ||
170
+ (kind !== "OK" && kind !== "ERROR")
171
+ ) {
172
+ this.fail(new WindowsNativeError("helper-protocol"));
173
+
174
+ return;
175
+ }
176
+
177
+ if (!pending) {
178
+ // A deadline can expire while the native operation is still finishing. Never replay.
179
+ return;
180
+ }
181
+
182
+ this.pending.delete(id);
183
+ clearTimeout(pending.timer);
184
+
185
+ if (kind === "OK") {
186
+ pending.resolve(Buffer.from(payload, "base64").toString("utf8"));
187
+ } else {
188
+ pending.reject(
189
+ new WindowsNativeError(
190
+ /^[a-z0-9-]{1,64}$/.test(payload) ? payload : "native-io",
191
+ ),
192
+ );
193
+ }
194
+
195
+ if (this.pending.size === 0) {
196
+ reference(this.child, false);
197
+ }
198
+ },
199
+ (error) => {
200
+ rejectReady(error);
201
+ this.fail(error);
202
+ },
203
+ );
204
+ }
205
+
206
+ fail(error: WindowsNativeError): void {
207
+ if (this.failed) {
208
+ return;
209
+ }
210
+
211
+ this.failed = error;
212
+
213
+ if (worker === this) {
214
+ worker = undefined;
215
+ }
216
+
217
+ for (const pending of this.pending.values()) {
218
+ clearTimeout(pending.timer);
219
+ pending.reject(error);
220
+ }
221
+
222
+ this.pending.clear();
223
+ this.child.kill();
224
+ }
225
+
226
+ async call(operation: string, arguments_: string[], timeoutMs: number): Promise<string> {
227
+ await this.ready;
228
+
229
+ if (this.failed) {
230
+ throw this.failed;
231
+ }
232
+
233
+ if (this.pending.size >= 128) {
234
+ throw new WindowsNativeError("busy");
235
+ }
236
+
237
+ const id = randomBytes(16).toString("hex");
238
+ const frame = [operation, id, ...arguments_].join("\t");
239
+
240
+ if (frame.length > MAX_FRAME || arguments_.some((value) => /[\r\n\t]/.test(value))) {
241
+ throw new WindowsNativeError("frame-bound");
242
+ }
243
+
244
+ reference(this.child, true);
245
+
246
+ return new Promise((resolve, reject) => {
247
+ const timer = setTimeout(() => {
248
+ this.pending.delete(id);
249
+ reject(new WindowsNativeError("timeout"));
250
+
251
+ if (this.pending.size === 0) {
252
+ reference(this.child, false);
253
+ }
254
+ }, timeoutMs);
255
+
256
+ this.pending.set(id, { resolve, reject, timer });
257
+ this.child.stdin.write(`${frame}\n`);
258
+ });
259
+ }
260
+ }
261
+
262
+ const encode = (value: string): string => Buffer.from(value, "utf8").toString("base64");
263
+ const getWorker = (): NativeWorker => (worker ??= new NativeWorker());
264
+
265
+ /** Windows ACL proof, including owner and reparse-point refusal; never chmod an existing path. */
266
+ export async function assertWindowsPrivatePath(
267
+ path: string,
268
+ kind: "file" | "directory",
269
+ ): Promise<void> {
270
+ if (process.platform === "win32") {
271
+ await getWorker().call(
272
+ kind === "file" ? "FILE" : "DIR",
273
+ [encode(resolve(path))],
274
+ START_TIMEOUT,
275
+ );
276
+ }
277
+ }
278
+
279
+ /** Regular-file fsync must precede this call. Windows uses native write-through replacement. */
280
+ export async function durableRename(source: string, destination: string): Promise<void> {
281
+ if (process.platform === "win32") {
282
+ await getWorker().call(
283
+ "MOVE",
284
+ [encode(resolve(source)), encode(resolve(destination))],
285
+ START_TIMEOUT,
286
+ );
287
+ } else {
288
+ await rename(source, destination);
289
+ }
290
+ }
291
+
292
+ function pipeName(path: string): string {
293
+ const prefix = "\\\\.\\pipe\\";
294
+ const name = path.slice(prefix.length);
295
+
296
+ if (!path.startsWith(prefix) || !/^bom-pi-admin-[a-f0-9]{64}$/.test(name)) {
297
+ throw new WindowsNativeError("pipe-name");
298
+ }
299
+
300
+ return name;
301
+ }
302
+
303
+ /** The native client verifies the connected handle's owner/DACL before sending the request. */
304
+ export async function requestWindowsPipe(
305
+ path: string,
306
+ request: string,
307
+ timeoutMs: number,
308
+ ): Promise<string> {
309
+ if (Buffer.byteLength(request) + 1 > 4096) {
310
+ throw new WindowsNativeError("too-large");
311
+ }
312
+
313
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 20 * 60_000) {
314
+ throw new WindowsNativeError("timeout-bound");
315
+ }
316
+
317
+ const deadline = Date.now() + timeoutMs;
318
+ let timer: ReturnType<typeof setTimeout> | undefined;
319
+
320
+ const operation = async () => {
321
+ const bridge = getWorker();
322
+
323
+ await bridge.ready;
324
+
325
+ const remaining = deadline - Date.now();
326
+
327
+ if (remaining <= 0) {
328
+ throw new WindowsNativeError("timeout");
329
+ }
330
+
331
+ return bridge.call(
332
+ "CLIENT",
333
+ [encode(pipeName(path)), encode(request), String(remaining)],
334
+ remaining,
335
+ );
336
+ };
337
+
338
+ try {
339
+ return await Promise.race([
340
+ operation(),
341
+ new Promise<never>((_resolve, reject) => {
342
+ timer = setTimeout(() => reject(new WindowsNativeError("timeout")), timeoutMs);
343
+ }),
344
+ ]);
345
+ } finally {
346
+ clearTimeout(timer);
347
+ }
348
+ }
349
+
350
+ /** Atomically creates the first pipe instance with owner-only ACL; later instances have the
351
+ * same explicit ACL. The private inherited channel transports bytes to the ONE core handler. */
352
+ export async function startWindowsPipe(
353
+ path: string,
354
+ dispatch: (line: string, extendDeadline: () => void) => Promise<string>,
355
+ failed: () => void,
356
+ ): Promise<{ close(): Promise<void> }> {
357
+ const child = launch("server", pipeName(path));
358
+ let closed = false;
359
+ let ready = false;
360
+ let resolveReady!: () => void;
361
+ let rejectReady!: (error: WindowsNativeError) => void;
362
+ const started = new Promise<void>((resolve, reject) => {
363
+ resolveReady = resolve;
364
+ rejectReady = reject;
365
+ });
366
+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
367
+ const timer = setTimeout(() => abort(new WindowsNativeError("helper-deadline")), START_TIMEOUT);
368
+
369
+ const abort = (error: WindowsNativeError) => {
370
+ if (closed) {
371
+ return;
372
+ }
373
+
374
+ rejectReady(error);
375
+
376
+ if (ready) {
377
+ failed();
378
+ }
379
+
380
+ closed = true;
381
+ child.kill();
382
+ };
383
+
384
+ lines(
385
+ child,
386
+ (line) => {
387
+ if (line === "READY" && !ready) {
388
+ ready = true;
389
+ resolveReady();
390
+
391
+ return;
392
+ }
393
+
394
+ const [kind, id, payload, extra] = line.split("\t");
395
+
396
+ if (
397
+ !ready ||
398
+ kind !== "REQUEST" ||
399
+ !id ||
400
+ !/^[a-f0-9]{32}$/.test(id) ||
401
+ payload === undefined ||
402
+ extra !== undefined
403
+ ) {
404
+ abort(new WindowsNativeError("helper-protocol"));
405
+
406
+ return;
407
+ }
408
+
409
+ const bytes = Buffer.from(payload, "base64");
410
+
411
+ if (bytes.length + 1 > 4096) {
412
+ abort(new WindowsNativeError("frame-bound"));
413
+
414
+ return;
415
+ }
416
+
417
+ void dispatch(bytes.toString("utf8"), () =>
418
+ child.stdin.write(`WAIT\t${id}\t1200000\n`),
419
+ ).then(
420
+ (response) => {
421
+ if (!closed && child.stdin.writable) {
422
+ child.stdin.write(`REPLY\t${id}\t${encode(response)}\n`);
423
+ }
424
+ },
425
+ () => abort(new WindowsNativeError("dispatch-failed")),
426
+ );
427
+ },
428
+ abort,
429
+ );
430
+
431
+ try {
432
+ await started;
433
+ } finally {
434
+ clearTimeout(timer);
435
+ }
436
+
437
+ return {
438
+ async close() {
439
+ if (!closed) {
440
+ closed = true;
441
+ child.stdin.end("CLOSE\n");
442
+ }
443
+
444
+ const kill = setTimeout(() => child.kill(), 5000);
445
+
446
+ try {
447
+ await exited;
448
+ } finally {
449
+ clearTimeout(kill);
450
+ }
451
+ },
452
+ };
453
+ }