blun-king-cli 9.1.629 → 9.1.631
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/bin/blun.js +0 -0
- package/bin/core-bootstrap.js +0 -0
- package/bin/king.js +0 -0
- package/bin/launcher-mode.js +0 -0
- package/bin/launcher-runtime.js +0 -0
- package/bin/managed-node.js +0 -0
- package/bin/native-command-runner.js +0 -0
- package/bin/native-module-repair.js +0 -0
- package/bin/node-runtime.js +0 -0
- package/bin/node-version.js +0 -0
- package/bin/plugin-bootstrap.js +0 -0
- package/bin/private-paths.js +236 -21
- package/bin/standard-tools-bootstrap.js +0 -0
- package/bin/update-copy.js +0 -0
- package/bin/update-lease.js +0 -0
- package/bin/update-notice.js +0 -0
- package/bin/windows-private-temp.cjs +248 -0
- package/blun.mjs +25 -34
- package/package.json +1 -1
- package/worker-host.mjs +17 -26
package/bin/blun.js
CHANGED
|
File without changes
|
package/bin/core-bootstrap.js
CHANGED
|
File without changes
|
package/bin/king.js
CHANGED
|
File without changes
|
package/bin/launcher-mode.js
CHANGED
|
File without changes
|
package/bin/launcher-runtime.js
CHANGED
|
File without changes
|
package/bin/managed-node.js
CHANGED
|
File without changes
|
|
File without changes
|
|
File without changes
|
package/bin/node-runtime.js
CHANGED
|
File without changes
|
package/bin/node-version.js
CHANGED
|
File without changes
|
package/bin/plugin-bootstrap.js
CHANGED
|
File without changes
|
package/bin/private-paths.js
CHANGED
|
@@ -4,6 +4,7 @@ const { execFileSync } = require('node:child_process');
|
|
|
4
4
|
const fs = require('node:fs');
|
|
5
5
|
const path = require('node:path');
|
|
6
6
|
const { gzipSync } = require('node:zlib');
|
|
7
|
+
const { createWindowsPrivateTemp } = require('./windows-private-temp.cjs');
|
|
7
8
|
|
|
8
9
|
const PRIVATE_DIRECTORY_MODE = 0o700;
|
|
9
10
|
const PRIVATE_FILE_MODE = 0o600;
|
|
@@ -27,11 +28,14 @@ using System.Text;
|
|
|
27
28
|
|
|
28
29
|
public static class BlunPrivateAclNative
|
|
29
30
|
{
|
|
31
|
+
public static string CurrentPhase = "native-dispatch";
|
|
32
|
+
public static string CurrentTarget = null;
|
|
30
33
|
private const uint GENERIC_READ = 0x80000000;
|
|
31
34
|
private const uint GENERIC_WRITE = 0x40000000;
|
|
32
35
|
private const uint DELETE = 0x00010000;
|
|
33
36
|
private const uint READ_CONTROL = 0x00020000;
|
|
34
37
|
private const uint WRITE_DAC = 0x00040000;
|
|
38
|
+
private const uint WRITE_OWNER = 0x00080000;
|
|
35
39
|
private const uint SYNCHRONIZE = 0x00100000;
|
|
36
40
|
private const uint CREATE_NEW = 1;
|
|
37
41
|
private const uint OPEN_EXISTING = 3;
|
|
@@ -277,7 +281,6 @@ public static class BlunPrivateAclNative
|
|
|
277
281
|
HashSet<string> expected = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
278
282
|
expected.Add(user.Value);
|
|
279
283
|
expected.Add("S-1-5-18");
|
|
280
|
-
expected.Add("S-1-5-32-544");
|
|
281
284
|
return expected;
|
|
282
285
|
}
|
|
283
286
|
|
|
@@ -286,8 +289,7 @@ public static class BlunPrivateAclNative
|
|
|
286
289
|
string flags = directory ? "OICI" : "";
|
|
287
290
|
string[] trustees = new string[] {
|
|
288
291
|
new SecurityIdentifier(userSid).Value,
|
|
289
|
-
"S-1-5-18"
|
|
290
|
-
"S-1-5-32-544"
|
|
292
|
+
"S-1-5-18"
|
|
291
293
|
};
|
|
292
294
|
HashSet<string> seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
293
295
|
StringBuilder builder = new StringBuilder("D:P");
|
|
@@ -314,6 +316,7 @@ public static class BlunPrivateAclNative
|
|
|
314
316
|
|
|
315
317
|
private static void SetExactDacl(SafeFileHandle handle, string userSid, bool directory)
|
|
316
318
|
{
|
|
319
|
+
CurrentPhase = "dacl-write";
|
|
317
320
|
IntPtr descriptor = CreateExactDescriptor(userSid, directory);
|
|
318
321
|
try
|
|
319
322
|
{
|
|
@@ -376,10 +379,37 @@ public static class BlunPrivateAclNative
|
|
|
376
379
|
SafeFileHandle handle,
|
|
377
380
|
HashSet<string> expectedSids)
|
|
378
381
|
{
|
|
382
|
+
CurrentPhase = "owner-verification";
|
|
379
383
|
RawSecurityDescriptor descriptor = ReadAccessDescriptor(handle);
|
|
380
|
-
if (descriptor.Owner == null
|
|
384
|
+
if (descriptor.Owner == null) throw new UnauthorizedAccessException();
|
|
385
|
+
if (expectedSids.Contains(descriptor.Owner.Value)) return descriptor.Owner.Value;
|
|
386
|
+
// The only additional trusted owner is BUILTIN\\Administrators.
|
|
387
|
+
// WRITE_OWNER permits taking ownership as self without SeRestorePrivilege.
|
|
388
|
+
if (!String.Equals(descriptor.Owner.Value, "S-1-5-32-544", StringComparison.OrdinalIgnoreCase))
|
|
381
389
|
throw new UnauthorizedAccessException();
|
|
382
|
-
|
|
390
|
+
CurrentPhase = "owner-takeover";
|
|
391
|
+
SecurityIdentifier self = WindowsIdentity.GetCurrent().User;
|
|
392
|
+
if (self == null || !expectedSids.Contains(self.Value))
|
|
393
|
+
throw new UnauthorizedAccessException();
|
|
394
|
+
byte[] sid = new byte[self.BinaryLength];
|
|
395
|
+
self.GetBinaryForm(sid, 0);
|
|
396
|
+
IntPtr owner = Marshal.AllocHGlobal(sid.Length);
|
|
397
|
+
try
|
|
398
|
+
{
|
|
399
|
+
Marshal.Copy(sid, 0, owner, sid.Length);
|
|
400
|
+
uint result = SetSecurityInfo(handle, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION,
|
|
401
|
+
owner, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
|
402
|
+
if (result != 0) throw new Win32Exception((int)result);
|
|
403
|
+
}
|
|
404
|
+
finally
|
|
405
|
+
{
|
|
406
|
+
Marshal.FreeHGlobal(owner);
|
|
407
|
+
Array.Clear(sid, 0, sid.Length);
|
|
408
|
+
}
|
|
409
|
+
RawSecurityDescriptor actual = ReadAccessDescriptor(handle);
|
|
410
|
+
if (actual.Owner == null || !actual.Owner.Equals(self))
|
|
411
|
+
throw new UnauthorizedAccessException();
|
|
412
|
+
return self.Value;
|
|
383
413
|
}
|
|
384
414
|
|
|
385
415
|
private static void VerifyExactDacl(
|
|
@@ -388,6 +418,7 @@ public static class BlunPrivateAclNative
|
|
|
388
418
|
bool directory,
|
|
389
419
|
string expectedOwner)
|
|
390
420
|
{
|
|
421
|
+
CurrentPhase = "dacl-verification";
|
|
391
422
|
HashSet<string> expectedSids = ExpectedSids(userSid);
|
|
392
423
|
RawSecurityDescriptor descriptor = ReadAccessDescriptor(handle);
|
|
393
424
|
if (descriptor.Owner == null
|
|
@@ -424,6 +455,7 @@ public static class BlunPrivateAclNative
|
|
|
424
455
|
SafeFileHandle handle,
|
|
425
456
|
bool directory)
|
|
426
457
|
{
|
|
458
|
+
CurrentPhase = "entry-validation";
|
|
427
459
|
ByHandleFileInformation information;
|
|
428
460
|
if (!GetFileInformationByHandle(handle, out information))
|
|
429
461
|
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
@@ -532,6 +564,7 @@ public static class BlunPrivateAclNative
|
|
|
532
564
|
|
|
533
565
|
private static void VerifyHandlePath(SafeFileHandle handle, string expectedPath)
|
|
534
566
|
{
|
|
567
|
+
CurrentPhase = "path-verification";
|
|
535
568
|
StringBuilder buffer = new StringBuilder(32768);
|
|
536
569
|
uint length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Capacity, 0);
|
|
537
570
|
if (length == 0 || length >= buffer.Capacity)
|
|
@@ -545,14 +578,96 @@ public static class BlunPrivateAclNative
|
|
|
545
578
|
}
|
|
546
579
|
}
|
|
547
580
|
|
|
548
|
-
private static
|
|
581
|
+
private static ByHandleFileInformation TakeOwnerBeforeReopen(
|
|
582
|
+
string target, bool directory, string userSid)
|
|
583
|
+
{
|
|
584
|
+
CurrentTarget = target;
|
|
585
|
+
CurrentPhase = "owner-takeover";
|
|
586
|
+
uint flags = FILE_FLAG_OPEN_REPARSE_POINT;
|
|
587
|
+
if (directory) flags |= FILE_FLAG_BACKUP_SEMANTICS;
|
|
588
|
+
SafeFileHandle handle = CreateFileExisting(target,
|
|
589
|
+
READ_CONTROL | WRITE_OWNER | 0x80, 0, IntPtr.Zero, OPEN_EXISTING, flags, IntPtr.Zero);
|
|
590
|
+
if (handle.IsInvalid && Marshal.GetLastWin32Error() == 5)
|
|
591
|
+
{
|
|
592
|
+
handle.Dispose();
|
|
593
|
+
// Read-only owner inspection still yields the precise OWNER_TAKEOVER
|
|
594
|
+
// failure when an administrator-owned object lacks WRITE_OWNER.
|
|
595
|
+
handle = CreateFileExisting(target,
|
|
596
|
+
READ_CONTROL | 0x80, 0, IntPtr.Zero, OPEN_EXISTING, flags, IntPtr.Zero);
|
|
597
|
+
}
|
|
598
|
+
if (handle.IsInvalid)
|
|
599
|
+
{
|
|
600
|
+
int error = Marshal.GetLastWin32Error();
|
|
601
|
+
handle.Dispose();
|
|
602
|
+
throw new Win32Exception(error);
|
|
603
|
+
}
|
|
604
|
+
using (handle)
|
|
605
|
+
{
|
|
606
|
+
ByHandleFileInformation identity = ValidateHandle(handle, directory);
|
|
607
|
+
VerifyHandlePath(handle, target);
|
|
608
|
+
CurrentPhase = "owner-verification";
|
|
609
|
+
RawSecurityDescriptor before = ReadAccessDescriptor(handle);
|
|
610
|
+
if (before.Owner == null || before.Owner.Value != "S-1-5-32-544")
|
|
611
|
+
throw new UnauthorizedAccessException();
|
|
612
|
+
ValidateOwner(handle, ExpectedSids(userSid));
|
|
613
|
+
ValidateHandle(handle, directory);
|
|
614
|
+
VerifyHandlePath(handle, target);
|
|
615
|
+
return identity;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
private static void VerifyReopenedIdentity(
|
|
620
|
+
SafeFileHandle handle, bool directory, ByHandleFileInformation expected)
|
|
549
621
|
{
|
|
622
|
+
ByHandleFileInformation actual = ValidateHandle(handle, directory);
|
|
623
|
+
if (actual.VolumeSerialNumber != expected.VolumeSerialNumber
|
|
624
|
+
|| FileId(actual) == 0 || FileId(actual) != FileId(expected))
|
|
625
|
+
throw new UnauthorizedAccessException();
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
private static SafeFileHandle OpenExisting(string target, bool directory, bool write, string userSid)
|
|
629
|
+
{
|
|
630
|
+
CurrentTarget = target;
|
|
631
|
+
CurrentPhase = "entry-open";
|
|
550
632
|
uint access = GENERIC_READ | READ_CONTROL | WRITE_DAC | DELETE;
|
|
551
633
|
if (write) access |= GENERIC_WRITE;
|
|
552
634
|
uint flags = FILE_FLAG_OPEN_REPARSE_POINT;
|
|
553
635
|
if (directory) flags |= FILE_FLAG_BACKUP_SEMANTICS;
|
|
554
636
|
SafeFileHandle handle = CreateFileExisting(
|
|
555
|
-
target, access, 0, IntPtr.Zero, OPEN_EXISTING, flags, IntPtr.Zero);
|
|
637
|
+
target, access | WRITE_OWNER, 0, IntPtr.Zero, OPEN_EXISTING, flags, IntPtr.Zero);
|
|
638
|
+
if (handle.IsInvalid && Marshal.GetLastWin32Error() == 5)
|
|
639
|
+
{
|
|
640
|
+
handle.Dispose();
|
|
641
|
+
handle = CreateFileExisting(target, access, 0, IntPtr.Zero, OPEN_EXISTING, flags, IntPtr.Zero);
|
|
642
|
+
}
|
|
643
|
+
if (handle.IsInvalid && Marshal.GetLastWin32Error() == 5)
|
|
644
|
+
{
|
|
645
|
+
handle.Dispose();
|
|
646
|
+
ByHandleFileInformation identity = TakeOwnerBeforeReopen(target, directory, userSid);
|
|
647
|
+
// Taking ownership grants WRITE_DAC only on a newly opened handle.
|
|
648
|
+
// Harden using the minimal access; all identity/reparse checks remain.
|
|
649
|
+
handle = CreateFileExisting(target, READ_CONTROL | WRITE_DAC | 0x80,
|
|
650
|
+
0, IntPtr.Zero, OPEN_EXISTING, flags, IntPtr.Zero);
|
|
651
|
+
if (!handle.IsInvalid)
|
|
652
|
+
{
|
|
653
|
+
try
|
|
654
|
+
{
|
|
655
|
+
VerifyReopenedIdentity(handle, directory, identity);
|
|
656
|
+
VerifyHandlePath(handle, target);
|
|
657
|
+
SetExactDacl(handle, userSid, directory);
|
|
658
|
+
VerifyExactDacl(handle, userSid, directory, new SecurityIdentifier(userSid).Value);
|
|
659
|
+
}
|
|
660
|
+
catch { handle.Dispose(); throw; }
|
|
661
|
+
handle.Dispose();
|
|
662
|
+
handle = CreateFileExisting(target, access, 0, IntPtr.Zero, OPEN_EXISTING, flags, IntPtr.Zero);
|
|
663
|
+
if (!handle.IsInvalid)
|
|
664
|
+
{
|
|
665
|
+
try { VerifyReopenedIdentity(handle, directory, identity); VerifyHandlePath(handle, target); }
|
|
666
|
+
catch { handle.Dispose(); throw; }
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
if (handle.IsInvalid) CurrentPhase = "owner-takeover";
|
|
670
|
+
}
|
|
556
671
|
if (handle.IsInvalid)
|
|
557
672
|
{
|
|
558
673
|
int error = Marshal.GetLastWin32Error();
|
|
@@ -574,6 +689,8 @@ public static class BlunPrivateAclNative
|
|
|
574
689
|
string target,
|
|
575
690
|
string userSid)
|
|
576
691
|
{
|
|
692
|
+
CurrentTarget = target;
|
|
693
|
+
CurrentPhase = "directory-open";
|
|
577
694
|
string nativePath = NativePath(target);
|
|
578
695
|
if (Encoding.Unicode.GetByteCount(nativePath) > UInt16.MaxValue - 2)
|
|
579
696
|
throw new PathTooLongException();
|
|
@@ -602,7 +719,7 @@ public static class BlunPrivateAclNative
|
|
|
602
719
|
IoStatusBlock ioStatus;
|
|
603
720
|
int status = NtCreateFile(
|
|
604
721
|
out rawHandle,
|
|
605
|
-
GENERIC_READ | READ_CONTROL | WRITE_DAC | DELETE | SYNCHRONIZE,
|
|
722
|
+
GENERIC_READ | READ_CONTROL | WRITE_DAC | WRITE_OWNER | DELETE | SYNCHRONIZE,
|
|
606
723
|
ref attributes,
|
|
607
724
|
out ioStatus,
|
|
608
725
|
IntPtr.Zero,
|
|
@@ -612,6 +729,16 @@ public static class BlunPrivateAclNative
|
|
|
612
729
|
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
|
|
613
730
|
IntPtr.Zero,
|
|
614
731
|
0);
|
|
732
|
+
if (status < 0 && RtlNtStatusToDosError(status) == 5)
|
|
733
|
+
{
|
|
734
|
+
status = NtCreateFile(out rawHandle,
|
|
735
|
+
GENERIC_READ | READ_CONTROL | WRITE_DAC | DELETE | SYNCHRONIZE,
|
|
736
|
+
ref attributes, out ioStatus, IntPtr.Zero, 0, 0, FILE_OPEN_IF,
|
|
737
|
+
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
|
|
738
|
+
IntPtr.Zero, 0);
|
|
739
|
+
}
|
|
740
|
+
if (status < 0 && RtlNtStatusToDosError(status) == 5)
|
|
741
|
+
return OpenExisting(target, true, false, userSid);
|
|
615
742
|
if (status < 0)
|
|
616
743
|
throw new Win32Exception((int)RtlNtStatusToDosError(status));
|
|
617
744
|
return new SafeFileHandle(rawHandle, true);
|
|
@@ -659,7 +786,7 @@ public static class BlunPrivateAclNative
|
|
|
659
786
|
|
|
660
787
|
public static void HardenExisting(string target, string userSid, bool directory)
|
|
661
788
|
{
|
|
662
|
-
using (SafeFileHandle handle = OpenExisting(target, directory, false))
|
|
789
|
+
using (SafeFileHandle handle = OpenExisting(target, directory, false, userSid))
|
|
663
790
|
{
|
|
664
791
|
ValidateHandle(handle, directory);
|
|
665
792
|
VerifyHandlePath(handle, target);
|
|
@@ -870,7 +997,7 @@ public static class BlunPrivateAclNative
|
|
|
870
997
|
throw new UnauthorizedAccessException();
|
|
871
998
|
bool directory = (entry.Attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
|
|
872
999
|
string childPath = TreeChildPath(root, directoryPath, entry.Name);
|
|
873
|
-
SafeFileHandle childHandle = OpenExisting(childPath, directory, false);
|
|
1000
|
+
SafeFileHandle childHandle = OpenExisting(childPath, directory, false, userSid);
|
|
874
1001
|
try
|
|
875
1002
|
{
|
|
876
1003
|
HeldTreeHandle heldHandle = new HeldTreeHandle();
|
|
@@ -916,7 +1043,7 @@ public static class BlunPrivateAclNative
|
|
|
916
1043
|
List<HeldTreeHandle> heldHandles = new List<HeldTreeHandle>();
|
|
917
1044
|
try
|
|
918
1045
|
{
|
|
919
|
-
SafeFileHandle rootHandle = OpenExisting(root, true, false);
|
|
1046
|
+
SafeFileHandle rootHandle = OpenExisting(root, true, false, userSid);
|
|
920
1047
|
HeldTreeHandle heldRoot = new HeldTreeHandle();
|
|
921
1048
|
heldRoot.Handle = rootHandle;
|
|
922
1049
|
heldRoot.Path = root;
|
|
@@ -964,6 +1091,7 @@ public static class BlunPrivateAclNative
|
|
|
964
1091
|
|
|
965
1092
|
private static SafeFileHandle OpenForWrite(string target, string userSid)
|
|
966
1093
|
{
|
|
1094
|
+
CurrentTarget = target;
|
|
967
1095
|
IntPtr descriptor = CreateExactDescriptor(userSid, false);
|
|
968
1096
|
try
|
|
969
1097
|
{
|
|
@@ -1066,6 +1194,7 @@ const WINDOWS_ACL_CSHARP_GZIP = gzipSync(
|
|
|
1066
1194
|
const WINDOWS_ACL_SCRIPT = [
|
|
1067
1195
|
"$ErrorActionPreference = 'Stop'",
|
|
1068
1196
|
"$ProgressPreference = 'SilentlyContinue'",
|
|
1197
|
+
"$phase='powershell-bootstrap'",
|
|
1069
1198
|
'try {',
|
|
1070
1199
|
'Set-StrictMode -Version 3',
|
|
1071
1200
|
"$target=[Environment]::GetEnvironmentVariable('BLUN_PRIVATE_ACL_TARGET','Process')",
|
|
@@ -1073,7 +1202,7 @@ const WINDOWS_ACL_SCRIPT = [
|
|
|
1073
1202
|
"$sid=[Environment]::GetEnvironmentVariable('BLUN_PRIVATE_ACL_USER_SID','Process')",
|
|
1074
1203
|
"if ([string]::IsNullOrWhiteSpace($target) -or -not [IO.Path]::IsPathRooted($target)) { throw 'Invalid target.' }",
|
|
1075
1204
|
"if ($kind -ne 'directory' -and $kind -ne 'file' -and $kind -ne 'file-write' -and $kind -ne 'tree') { throw 'Invalid kind.' }",
|
|
1076
|
-
|
|
1205
|
+
'$bytes=[Convert]::FromBase64String($env:BLUN_PRIVATE_ACL_NATIVE_CSHARP)',
|
|
1077
1206
|
'$zipin=[IO.MemoryStream]::new($bytes)',
|
|
1078
1207
|
'$gzip=[IO.Compression.GZipStream]::new($zipin,[IO.Compression.CompressionMode]::Decompress)',
|
|
1079
1208
|
'$reader=[IO.StreamReader]::new($gzip,[Text.Encoding]::UTF8)',
|
|
@@ -1085,7 +1214,9 @@ const WINDOWS_ACL_SCRIPT = [
|
|
|
1085
1214
|
'$zipin.Dispose()',
|
|
1086
1215
|
'[Array]::Clear($bytes,0,$bytes.Length)',
|
|
1087
1216
|
'}',
|
|
1217
|
+
"$phase='native-compile'",
|
|
1088
1218
|
'$null=Add-Type -TypeDefinition $code -Language CSharp',
|
|
1219
|
+
"$phase='native-dispatch'",
|
|
1089
1220
|
"if ($kind -eq 'directory') {",
|
|
1090
1221
|
'[BlunPrivateAclNative]::EnsurePrivateDirectory($target,$sid)',
|
|
1091
1222
|
"} elseif ($kind -eq 'file') {",
|
|
@@ -1108,7 +1239,24 @@ const WINDOWS_ACL_SCRIPT = [
|
|
|
1108
1239
|
"[Console]::Out.Write('BLUN_PRIVATE_ACL_OK_V1')",
|
|
1109
1240
|
'exit 0',
|
|
1110
1241
|
'} catch {',
|
|
1111
|
-
"
|
|
1242
|
+
"$safePhase=$phase",
|
|
1243
|
+
"if ($phase -eq 'native-dispatch') { $safePhase=[BlunPrivateAclNative]::CurrentPhase }",
|
|
1244
|
+
'$nativeCode=0',
|
|
1245
|
+
"$reason='unknown'",
|
|
1246
|
+
'$failure=$_.Exception',
|
|
1247
|
+
'for ($depth=0; $depth -lt 8 -and $null -ne $failure; $depth++) {',
|
|
1248
|
+
"if ($failure -is [ComponentModel.Win32Exception]) { $nativeCode=$failure.NativeErrorCode; $reason='native-error'; break }",
|
|
1249
|
+
"if ($failure -is [UnauthorizedAccessException]) { $reason='access-denied'; break }",
|
|
1250
|
+
"if ($failure -is [IO.IOException]) { $reason='io-error'; break }",
|
|
1251
|
+
"if ($failure -is [ArgumentException]) { $reason='argument-error'; break }",
|
|
1252
|
+
'$failure=$failure.InnerException',
|
|
1253
|
+
'}',
|
|
1254
|
+
"if ($safePhase -eq 'owner-takeover') {",
|
|
1255
|
+
"$errorTarget=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([BlunPrivateAclNative]::CurrentTarget))",
|
|
1256
|
+
"[Console]::Error.Write(('BLUN_PRIVATE_ACL_ERROR_V4:{0}:{1}:{2}:{3}' -f $safePhase,$nativeCode,$reason,$errorTarget))",
|
|
1257
|
+
"} else {",
|
|
1258
|
+
"[Console]::Error.Write(('BLUN_PRIVATE_ACL_ERROR_V3:{0}:{1}:{2}' -f $safePhase,$nativeCode,$reason))",
|
|
1259
|
+
"}",
|
|
1112
1260
|
'exit 1',
|
|
1113
1261
|
'}',
|
|
1114
1262
|
].join('\n');
|
|
@@ -1163,6 +1311,49 @@ function framedPrivateContents(contents) {
|
|
|
1163
1311
|
}
|
|
1164
1312
|
}
|
|
1165
1313
|
|
|
1314
|
+
// Internal structured diagnostics only. Keep the existing public/catalog message.
|
|
1315
|
+
// Never retain raw child exceptions, stderr, environment or file contents.
|
|
1316
|
+
const WINDOWS_PRIVATE_ACL_PHASES = new Set([
|
|
1317
|
+
'powershell-bootstrap', 'native-compile', 'native-dispatch', 'directory-open',
|
|
1318
|
+
'entry-open', 'entry-validation', 'path-verification', 'owner-verification', 'owner-takeover',
|
|
1319
|
+
'dacl-write', 'dacl-verification',
|
|
1320
|
+
]);
|
|
1321
|
+
|
|
1322
|
+
function windowsPrivateAclError(phase, privatePath, operation, nativeErrorCode, reason) {
|
|
1323
|
+
const code = `BLUN_PRIVATE_ACL_${phase.replaceAll('-', '_').toUpperCase()}`;
|
|
1324
|
+
const error = new Error(`Windows private ACL hardening or verification failed. [${code}${reason && reason !== 'unknown' ? `; ${reason.toUpperCase().replaceAll('-', '_')}` : ''}]${privatePath === undefined ? '' : ` ${privatePath}`}${nativeErrorCode ? ` (${nativeErrorCode})` : ''}`);
|
|
1325
|
+
error.code = code;
|
|
1326
|
+
if (privatePath !== undefined) error.privatePath = privatePath;
|
|
1327
|
+
if (operation !== undefined) error.operation = operation;
|
|
1328
|
+
if (reason && reason !== 'unknown') error.reasonCode = reason.replaceAll('-', '_').toUpperCase();
|
|
1329
|
+
if (nativeErrorCode !== undefined && nativeErrorCode !== 0) error.nativeErrorCode = nativeErrorCode;
|
|
1330
|
+
return error;
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
function windowsPrivateAclHostError(failure, privatePath, operation, userSid) {
|
|
1334
|
+
const stderr = typeof failure?.stderr === 'string' ? failure.stderr : '';
|
|
1335
|
+
const takeover = /^BLUN_PRIVATE_ACL_ERROR_V4:owner-takeover:([0-9]{1,5}):(native-error|access-denied|io-error|argument-error|unknown):([A-Za-z0-9+/=]{1,24000})$/u.exec(stderr);
|
|
1336
|
+
if (takeover && Number(takeover[1]) <= 65535) {
|
|
1337
|
+
const target = Buffer.from(takeover[3], 'base64').toString('utf8');
|
|
1338
|
+
const prefix = privatePath.replace(/[\\/]+$/u, '') + path.sep;
|
|
1339
|
+
if ((target === privatePath || (operation === 'tree' && target.startsWith(prefix)))
|
|
1340
|
+
&& !/[\x00-\x1f"]/u.test(target)) {
|
|
1341
|
+
const error = windowsPrivateAclError('owner-takeover', target, operation, Number(takeover[1]), takeover[2]);
|
|
1342
|
+
error.nextStep = `icacls "${target}" /setowner *${userSid}`;
|
|
1343
|
+
error.requiredAccess = 'WRITE_OWNER';
|
|
1344
|
+
error.message = `[${error.code}] ${target}; WRITE_OWNER; ${error.nextStep}${error.nativeErrorCode ? ` (${error.nativeErrorCode})` : ''}`;
|
|
1345
|
+
return error;
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
const match = /^BLUN_PRIVATE_ACL_ERROR_V(2|3):([a-z-]+):([0-9]{1,5})(?::([a-z-]+))?$/u.exec(stderr);
|
|
1349
|
+
const reasons = new Set(['unknown', 'native-error', 'access-denied', 'io-error', 'argument-error']);
|
|
1350
|
+
if (match && WINDOWS_PRIVATE_ACL_PHASES.has(match[2]) && Number(match[3]) <= 65535
|
|
1351
|
+
&& (match[1] === '2' ? match[4] === undefined : reasons.has(match[4]))) {
|
|
1352
|
+
return windowsPrivateAclError(match[2], privatePath, operation, Number(match[3]), match[4]);
|
|
1353
|
+
}
|
|
1354
|
+
return windowsPrivateAclError('host-execution', privatePath, operation);
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1166
1357
|
function resolveWindowsPrivateTarget(targetPath) {
|
|
1167
1358
|
if (process.platform !== 'win32') return path.resolve(targetPath);
|
|
1168
1359
|
try {
|
|
@@ -1191,7 +1382,7 @@ function resolveWindowsPrivateTarget(targetPath) {
|
|
|
1191
1382
|
}
|
|
1192
1383
|
return absoluteTarget;
|
|
1193
1384
|
} catch {
|
|
1194
|
-
throw
|
|
1385
|
+
throw windowsPrivateAclError('target-validation');
|
|
1195
1386
|
}
|
|
1196
1387
|
}
|
|
1197
1388
|
|
|
@@ -1218,30 +1409,41 @@ function windowsAclController(options) {
|
|
|
1218
1409
|
hostEnvironment,
|
|
1219
1410
|
);
|
|
1220
1411
|
} catch {
|
|
1221
|
-
throw new Error('Cannot determine the current Windows user SID for private launcher paths.');
|
|
1412
|
+
throw Object.assign(new Error('Cannot determine the current Windows user SID for private launcher paths.'), { code: 'BLUN_PRIVATE_ACL_SID_RESOLUTION' });
|
|
1222
1413
|
}
|
|
1223
1414
|
const sids = [...new Set(String(output).match(WINDOWS_SID_PATTERN) || [])];
|
|
1224
1415
|
if (sids.length !== 1) {
|
|
1225
|
-
throw new Error('Cannot determine the current Windows user SID for private launcher paths.');
|
|
1416
|
+
throw Object.assign(new Error('Cannot determine the current Windows user SID for private launcher paths.'), { code: 'BLUN_PRIVATE_ACL_SID_RESOLUTION' });
|
|
1226
1417
|
}
|
|
1227
1418
|
userSid = sids[0].toUpperCase();
|
|
1228
1419
|
return userSid;
|
|
1229
1420
|
};
|
|
1230
1421
|
|
|
1231
1422
|
const invoke = (targetPath, kind, input) => {
|
|
1423
|
+
let temporary;
|
|
1424
|
+
let primaryFailure;
|
|
1232
1425
|
try {
|
|
1233
1426
|
const absoluteTarget = resolveWindowsPrivateTarget(targetPath);
|
|
1234
1427
|
const root = path.parse(absoluteTarget).root;
|
|
1235
1428
|
if (!path.isAbsolute(absoluteTarget)
|
|
1236
1429
|
|| root.toLowerCase() === absoluteTarget.toLowerCase()
|
|
1237
1430
|
|| !['directory', 'file', 'file-write', 'tree'].includes(kind)) {
|
|
1238
|
-
throw
|
|
1431
|
+
throw windowsPrivateAclError('target-validation');
|
|
1239
1432
|
}
|
|
1433
|
+
const sid = currentUserSid();
|
|
1434
|
+
temporary = (options.createPrivateTempImpl || createWindowsPrivateTemp)({
|
|
1435
|
+
systemDirectory, userSid: sid, resolveTarget: resolveWindowsPrivateTarget,
|
|
1436
|
+
tempRoot: options.tempRoot, privateTempRoot: options.privateTempRoot,
|
|
1437
|
+
warn: options.onWarning, execute: options.execFileSyncImpl || execFileSync,
|
|
1438
|
+
});
|
|
1240
1439
|
const env = {
|
|
1241
1440
|
...hostEnvironment,
|
|
1441
|
+
TEMP: temporary.path,
|
|
1442
|
+
TMP: temporary.path,
|
|
1242
1443
|
BLUN_PRIVATE_ACL_KIND: kind,
|
|
1243
1444
|
BLUN_PRIVATE_ACL_TARGET: absoluteTarget,
|
|
1244
|
-
BLUN_PRIVATE_ACL_USER_SID:
|
|
1445
|
+
BLUN_PRIVATE_ACL_USER_SID: sid,
|
|
1446
|
+
BLUN_PRIVATE_ACL_NATIVE_CSHARP: WINDOWS_ACL_CSHARP_GZIP,
|
|
1245
1447
|
};
|
|
1246
1448
|
let output;
|
|
1247
1449
|
try {
|
|
@@ -1253,14 +1455,27 @@ function windowsAclController(options) {
|
|
|
1253
1455
|
env,
|
|
1254
1456
|
input,
|
|
1255
1457
|
);
|
|
1256
|
-
} catch {
|
|
1257
|
-
throw
|
|
1458
|
+
} catch (failure) {
|
|
1459
|
+
throw windowsPrivateAclHostError(failure, absoluteTarget, kind, sid);
|
|
1258
1460
|
}
|
|
1259
1461
|
if (output !== WINDOWS_ACL_OK_SENTINEL) {
|
|
1260
|
-
throw
|
|
1462
|
+
throw windowsPrivateAclError('result-protocol', absoluteTarget, kind);
|
|
1261
1463
|
}
|
|
1464
|
+
} catch (error) {
|
|
1465
|
+
primaryFailure = error;
|
|
1466
|
+
throw error;
|
|
1262
1467
|
} finally {
|
|
1263
1468
|
input?.fill(0);
|
|
1469
|
+
if (temporary) {
|
|
1470
|
+
try { temporary.dispose(); } catch (cleanupFailure) {
|
|
1471
|
+
if (primaryFailure) {
|
|
1472
|
+
primaryFailure.cleanupCode = 'BLUN_PRIVATE_ACL_TEMP_CLEANUP';
|
|
1473
|
+
} else {
|
|
1474
|
+
if (typeof cleanupFailure?.code === 'string' && cleanupFailure.code.startsWith('BLUN_PRIVATE_ACL_TEMP_')) throw cleanupFailure;
|
|
1475
|
+
throw windowsPrivateAclError('temp-cleanup', temporary.path, kind);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1264
1479
|
}
|
|
1265
1480
|
};
|
|
1266
1481
|
|
|
File without changes
|
package/bin/update-copy.js
CHANGED
|
File without changes
|
package/bin/update-lease.js
CHANGED
|
File without changes
|
package/bin/update-notice.js
CHANGED
|
File without changes
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const os = require('node:os');
|
|
5
|
+
const { randomUUID } = require('node:crypto');
|
|
6
|
+
const { execFileSync } = require('node:child_process');
|
|
7
|
+
|
|
8
|
+
// Bootstrap uses framework APIs only: it must never compile before TEMP is private.
|
|
9
|
+
const BOOTSTRAP = String.raw`
|
|
10
|
+
$ErrorActionPreference='Stop'
|
|
11
|
+
$ProgressPreference='SilentlyContinue'
|
|
12
|
+
$phase='TEMP_PATH'
|
|
13
|
+
try {
|
|
14
|
+
Set-StrictMode -Version 3
|
|
15
|
+
$target=$env:BLUN_PRIVATE_TEMP_TARGET
|
|
16
|
+
$sid=[Security.Principal.SecurityIdentifier]::new($env:BLUN_PRIVATE_ACL_USER_SID)
|
|
17
|
+
$system=[Security.Principal.SecurityIdentifier]::new('S-1-5-18')
|
|
18
|
+
if ([IO.Path]::GetFullPath($target) -cne $target -or $target -notmatch '^[A-Za-z]:\\') { throw 'path' }
|
|
19
|
+
if ([IO.Directory]::Exists($target) -or [IO.File]::Exists($target)) { throw 'exists' }
|
|
20
|
+
$parent=[IO.Path]::GetDirectoryName($target)
|
|
21
|
+
if (-not [IO.Directory]::Exists($parent)) { throw 'parent' }
|
|
22
|
+
for ($ancestor=$parent; -not [string]::IsNullOrEmpty($ancestor); $ancestor=[IO.Path]::GetDirectoryName($ancestor)) {
|
|
23
|
+
if (([IO.File]::GetAttributes($ancestor) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
|
|
24
|
+
}
|
|
25
|
+
$acl=[Security.AccessControl.DirectorySecurity]::new()
|
|
26
|
+
$acl.SetOwner($sid)
|
|
27
|
+
$acl.SetAccessRuleProtection($true,$false)
|
|
28
|
+
$flags=[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'
|
|
29
|
+
$expected=@{}
|
|
30
|
+
$expected[$sid.Value]=$sid
|
|
31
|
+
$expected[$system.Value]=$system
|
|
32
|
+
foreach ($trustee in $expected.Values) {
|
|
33
|
+
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($trustee,[Security.AccessControl.FileSystemRights]::FullControl,$flags,[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow))
|
|
34
|
+
}
|
|
35
|
+
$phase='TEMP_CREATE'
|
|
36
|
+
$directory=[IO.Directory]::CreateDirectory($target,$acl)
|
|
37
|
+
if (($directory.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
|
|
38
|
+
$phase='TEMP_ACL_VERIFICATION'
|
|
39
|
+
$actual=$directory.GetAccessControl([Security.AccessControl.AccessControlSections]'Owner,Access')
|
|
40
|
+
if (-not $actual.AreAccessRulesProtected -or $actual.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'owner' }
|
|
41
|
+
$rules=$actual.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])
|
|
42
|
+
if ($rules.Count -ne $expected.Count) { throw 'acl' }
|
|
43
|
+
$seen=@{}
|
|
44
|
+
foreach ($rule in $rules) {
|
|
45
|
+
$key=$rule.IdentityReference.Value
|
|
46
|
+
if ((-not $expected.ContainsKey($key)) -or $seen.ContainsKey($key) -or $rule.IsInherited -or $rule.AccessControlType -ne 'Allow' -or $rule.FileSystemRights -ne 'FullControl' -or $rule.InheritanceFlags -ne $flags -or $rule.PropagationFlags -ne 'None') { throw 'acl' }
|
|
47
|
+
$seen[$key]=$true
|
|
48
|
+
}
|
|
49
|
+
for ($ancestor=$target; -not [string]::IsNullOrEmpty($ancestor); $ancestor=[IO.Path]::GetDirectoryName($ancestor)) {
|
|
50
|
+
if (([IO.File]::GetAttributes($ancestor) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
|
|
51
|
+
}
|
|
52
|
+
$phase='TEMP_WRITE_PROBE'
|
|
53
|
+
$probe=[IO.Path]::Combine($target,[Guid]::NewGuid().ToString('N')+'.probe')
|
|
54
|
+
$handle=[IO.File]::Open($probe,[IO.FileMode]::CreateNew,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
|
|
55
|
+
try { $handle.WriteByte(0); $handle.Flush($true) } finally { $handle.Dispose() }
|
|
56
|
+
[IO.File]::Delete($probe)
|
|
57
|
+
[Console]::Out.Write('BLUN_PRIVATE_TEMP_OK_V1')
|
|
58
|
+
exit 0
|
|
59
|
+
} catch {
|
|
60
|
+
[Console]::Error.Write(('BLUN_PRIVATE_TEMP_ERROR_V2:{0}' -f $phase))
|
|
61
|
+
exit 1
|
|
62
|
+
}`;
|
|
63
|
+
|
|
64
|
+
function fail(phase, privatePath) {
|
|
65
|
+
const error = new Error(`Windows private ACL hardening or verification failed. [BLUN_PRIVATE_ACL_${phase}]${privatePath === undefined ? '' : ` ${privatePath}`}`);
|
|
66
|
+
error.code = `BLUN_PRIVATE_ACL_${phase}`;
|
|
67
|
+
if (privatePath !== undefined) error.privatePath = privatePath;
|
|
68
|
+
return error;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function checkedDirectory(target) {
|
|
72
|
+
const root = path.win32.parse(target).root;
|
|
73
|
+
let ancestor = root;
|
|
74
|
+
for (const segment of target.slice(root.length).split('\\').filter(Boolean)) {
|
|
75
|
+
ancestor = path.win32.join(ancestor, segment);
|
|
76
|
+
const stat = fs.lstatSync(ancestor);
|
|
77
|
+
if (stat.isSymbolicLink()) throw Object.assign(fail('TEMP_PATH'), {reparse:true});
|
|
78
|
+
if (!stat.isDirectory()) throw fail('TEMP_DIRECTORY');
|
|
79
|
+
}
|
|
80
|
+
if (fs.realpathSync.native(target).toLowerCase() !== target.toLowerCase()) throw Object.assign(fail('TEMP_PATH'), {reparse:true});
|
|
81
|
+
return fs.lstatSync(target,{bigint:true});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
// Framework-only verification: no compiler is run until the private TEMP exists.
|
|
86
|
+
const VERIFY = String.raw`
|
|
87
|
+
$ErrorActionPreference='Stop'
|
|
88
|
+
try {
|
|
89
|
+
$target=$env:BLUN_PRIVATE_TEMP_TARGET
|
|
90
|
+
$sid=$env:BLUN_PRIVATE_ACL_USER_SID
|
|
91
|
+
$items=[Collections.Generic.List[string]]::new()
|
|
92
|
+
$queue=[Collections.Generic.Queue[string]]::new()
|
|
93
|
+
$queue.Enqueue($target)
|
|
94
|
+
while($queue.Count -gt 0) {
|
|
95
|
+
$p=$queue.Dequeue()
|
|
96
|
+
$item=Get-Item -Force -LiteralPath $p
|
|
97
|
+
if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){throw 'reparse'}
|
|
98
|
+
$a=Get-Acl -LiteralPath $p
|
|
99
|
+
$owner=$a.GetOwner([Security.Principal.SecurityIdentifier]).Value
|
|
100
|
+
if($owner -ne $sid){throw 'owner'}
|
|
101
|
+
if($item.PSIsContainer){
|
|
102
|
+
if(-not $a.AreAccessRulesProtected){throw 'acl'}
|
|
103
|
+
$rules=$a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])
|
|
104
|
+
if($rules.Count -ne 2){throw 'acl'}
|
|
105
|
+
$seen=@{}
|
|
106
|
+
foreach($r in $rules){
|
|
107
|
+
$s=$r.IdentityReference.Value
|
|
108
|
+
if(($s -ne $sid -and $s -ne 'S-1-5-18') -or $seen.ContainsKey($s) -or $r.IsInherited -or $r.AccessControlType -ne 'Allow' -or $r.FileSystemRights -ne 'FullControl' -or $r.InheritanceFlags -ne 'ContainerInherit,ObjectInherit' -or $r.PropagationFlags -ne 'None'){throw 'acl'}
|
|
109
|
+
$seen[$s]=$true
|
|
110
|
+
}
|
|
111
|
+
foreach($entry in [IO.Directory]::EnumerateFileSystemEntries($p)){$queue.Enqueue($entry)}
|
|
112
|
+
} else {
|
|
113
|
+
foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){
|
|
114
|
+
if(($r.IdentityReference.Value -ne $sid -and $r.IdentityReference.Value -ne 'S-1-5-18') -or $r.AccessControlType -ne 'Allow'){throw 'acl'}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
$items.Add($p)
|
|
118
|
+
if($items.Count -gt 4096){throw 'limit'}
|
|
119
|
+
}
|
|
120
|
+
[Console]::Out.Write('BLUN_PRIVATE_TEMP_VERIFIED_V2')
|
|
121
|
+
exit 0
|
|
122
|
+
} catch { [Console]::Error.Write('BLUN_PRIVATE_TEMP_VERIFY_FAILED_V2');exit 1 }
|
|
123
|
+
`;
|
|
124
|
+
const MARKER = '.blun-acl-owner-v2.json';
|
|
125
|
+
const NAME = /^blun-acl-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
126
|
+
const CLEANUP_ERRORS = new Set(['EACCES','EPERM','EBUSY','ENOTEMPTY']);
|
|
127
|
+
function pause() { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 40); }
|
|
128
|
+
function warning(target, warn) {
|
|
129
|
+
const value = {code:'BLUN_PRIVATE_ACL_TEMP_CLEANUP',privatePath:target,attempts:3,
|
|
130
|
+
nextStep:'BLUN_PRIVATE_ACL_TEMP_RECLAIM_NEXT_START'};
|
|
131
|
+
if (warn) warn(value);
|
|
132
|
+
else process.emitWarning(`[${value.code}] ${target}; ${value.nextStep}`, {code:value.code});
|
|
133
|
+
}
|
|
134
|
+
function createWindowsPrivateTemp({ systemDirectory, userSid, resolveTarget,
|
|
135
|
+
tempRoot = path.win32.join(os.userInfo().homedir, 'AppData', 'Local', 'Temp'),
|
|
136
|
+
privateTempRoot = path.win32.join(os.userInfo().homedir, '.blun', 'profile', 'default', '.acl-temp'),
|
|
137
|
+
execute = execFileSync, warn }) {
|
|
138
|
+
let target;
|
|
139
|
+
const hostEnv = {SystemRoot:path.win32.dirname(systemDirectory),WINDIR:path.win32.dirname(systemDirectory)};
|
|
140
|
+
const run = (script, candidate) => execute(path.win32.join(systemDirectory,'WindowsPowerShell','v1.0','powershell.exe'),
|
|
141
|
+
['-NoLogo','-NoProfile','-NonInteractive','-EncodedCommand',Buffer.from(script,'utf16le').toString('base64')],
|
|
142
|
+
{encoding:'utf8',env:{...hostEnv,BLUN_PRIVATE_TEMP_TARGET:candidate,BLUN_PRIVATE_ACL_USER_SID:userSid},shell:false,stdio:['ignore','pipe','pipe'],timeout:30000,maxBuffer:65536,windowsHide:true});
|
|
143
|
+
const verify = candidate => {
|
|
144
|
+
checkedDirectory(candidate);
|
|
145
|
+
try { if(run(VERIFY,candidate)!=='BLUN_PRIVATE_TEMP_VERIFIED_V2') throw fail('TEMP_ACL_VERIFICATION',candidate); }
|
|
146
|
+
catch { throw fail('TEMP_ACL_VERIFICATION',candidate); }
|
|
147
|
+
};
|
|
148
|
+
const bootstrap = candidate => {
|
|
149
|
+
const output=run(BOOTSTRAP,candidate);
|
|
150
|
+
if(output!=='BLUN_PRIVATE_TEMP_OK_V1')throw fail('TEMP_PROTOCOL',candidate);
|
|
151
|
+
return checkedDirectory(candidate);
|
|
152
|
+
};
|
|
153
|
+
const identityIs = (actual, expected) => actual.dev===expected.dev && actual.ino===expected.ino;
|
|
154
|
+
// Build a bounded no-follow plan before deleting anything. Never use recursive rm.
|
|
155
|
+
const planFor = candidate => {
|
|
156
|
+
const entries=[];
|
|
157
|
+
const visit = (p, depth) => {
|
|
158
|
+
if(depth>64 || entries.length>=4096)throw fail('TEMP_IDENTITY',p);
|
|
159
|
+
const st=fs.lstatSync(p,{bigint:true});
|
|
160
|
+
if(st.isSymbolicLink() || (!st.isDirectory() && (!st.isFile() || st.nlink!==1n)))throw fail('TEMP_IDENTITY',p);
|
|
161
|
+
const entry={path:p,stat:st};entries.push(entry);
|
|
162
|
+
if(st.isDirectory()) for(const name of fs.readdirSync(p)) visit(path.win32.join(p,name),depth+1);
|
|
163
|
+
};
|
|
164
|
+
visit(candidate,0);
|
|
165
|
+
return entries.reverse();
|
|
166
|
+
};
|
|
167
|
+
const readMarker = candidate => {
|
|
168
|
+
const p=path.win32.join(candidate,MARKER);
|
|
169
|
+
const before=fs.lstatSync(p,{bigint:true});
|
|
170
|
+
if(!before.isFile() || before.isSymbolicLink() || before.nlink!==1n || before.size>2048n)throw fail('TEMP_IDENTITY',candidate);
|
|
171
|
+
const fd=fs.openSync(p,'r');
|
|
172
|
+
try {
|
|
173
|
+
if(!identityIs(fs.fstatSync(fd,{bigint:true}),before))throw fail('TEMP_IDENTITY',candidate);
|
|
174
|
+
const value=JSON.parse(fs.readFileSync(fd,'utf8'));
|
|
175
|
+
if(!identityIs(fs.lstatSync(p,{bigint:true}),before))throw fail('TEMP_IDENTITY',candidate);
|
|
176
|
+
return value;
|
|
177
|
+
} finally {fs.closeSync(fd);}
|
|
178
|
+
};
|
|
179
|
+
const removeVerified = (candidate, identity, marker) => {
|
|
180
|
+
for(let attempt=1;attempt<=3;attempt++) {
|
|
181
|
+
// Security/identity failures are NOT cleanup warnings, even after hardening.
|
|
182
|
+
const current=checkedDirectory(candidate);
|
|
183
|
+
if(!identityIs(current,identity))throw fail('TEMP_IDENTITY',candidate);
|
|
184
|
+
verify(candidate);
|
|
185
|
+
const saved=readMarker(candidate);
|
|
186
|
+
if(saved.token!==marker.token || saved.sid!==userSid || saved.dev!==String(identity.dev) || saved.ino!==String(identity.ino))throw fail('TEMP_IDENTITY',candidate);
|
|
187
|
+
const plan=planFor(candidate);
|
|
188
|
+
// Keep the ownership marker until every compiler file has been removed.
|
|
189
|
+
const markerPath=path.win32.join(candidate,MARKER);
|
|
190
|
+
const ordered=plan.filter(e=>e.path!==candidate && e.path!==markerPath);
|
|
191
|
+
ordered.push(plan.find(e=>e.path===markerPath),plan.find(e=>e.path===candidate));
|
|
192
|
+
try {
|
|
193
|
+
for(const entry of ordered) {
|
|
194
|
+
const now=fs.lstatSync(entry.path,{bigint:true});
|
|
195
|
+
if(!identityIs(now,entry.stat) || now.isSymbolicLink() || (!now.isDirectory() && now.nlink!==1n))throw fail('TEMP_IDENTITY',entry.path);
|
|
196
|
+
if(now.isDirectory())fs.rmdirSync(entry.path);else fs.unlinkSync(entry.path);
|
|
197
|
+
}
|
|
198
|
+
return true;
|
|
199
|
+
} catch(error) {
|
|
200
|
+
if(!CLEANUP_ERRORS.has(error.code))throw error;
|
|
201
|
+
// If the final empty directory removal was blocked, restore its own marker.
|
|
202
|
+
if(!fs.existsSync(markerPath))fs.writeFileSync(markerPath,JSON.stringify(marker),{flag:'wx',mode:0o600});
|
|
203
|
+
if(attempt<3)pause();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
warning(candidate,warn);
|
|
207
|
+
return false;
|
|
208
|
+
};
|
|
209
|
+
const reclaim = parent => {
|
|
210
|
+
for(const name of fs.readdirSync(parent)) {
|
|
211
|
+
if(!NAME.test(name))continue;
|
|
212
|
+
const candidate=path.win32.join(parent,name);
|
|
213
|
+
// Unmarked directories are not ours. Do not traverse or repair foreign trees.
|
|
214
|
+
const st=fs.lstatSync(candidate,{bigint:true});
|
|
215
|
+
if(!st.isDirectory() || st.isSymbolicLink())continue;
|
|
216
|
+
const markerPath=path.win32.join(candidate,MARKER);
|
|
217
|
+
if(!fs.existsSync(markerPath))continue;
|
|
218
|
+
verify(candidate);
|
|
219
|
+
const marker=readMarker(candidate);
|
|
220
|
+
if(marker.version!==2 || marker.sid!==userSid || marker.dev!==String(st.dev) || marker.ino!==String(st.ino) || !Number.isSafeInteger(marker.pid) || marker.pid<=0 || !/^[0-9a-f-]{36}$/u.test(marker.token))throw fail('TEMP_IDENTITY',candidate);
|
|
221
|
+
// Any live process with this pid keeps its compiler area, including pid reuse.
|
|
222
|
+
try {process.kill(marker.pid,0);continue;} catch(error) {if(error.code!=='ESRCH')continue;}
|
|
223
|
+
removeVerified(candidate,st,marker);
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
try {
|
|
227
|
+
let parent=resolveTarget(tempRoot.replace(/\\+$/u,''));
|
|
228
|
+
try {checkedDirectory(parent);}
|
|
229
|
+
catch(error) {
|
|
230
|
+
if(error.code!=='ENOENT' && !(error.code==='BLUN_PRIVATE_ACL_TEMP_PATH' && error.reparse===true))throw error;
|
|
231
|
+
parent=resolveTarget(privateTempRoot.replace(/\\+$/u,''));
|
|
232
|
+
checkedDirectory(path.win32.dirname(parent));
|
|
233
|
+
try {checkedDirectory(parent);verify(parent);}
|
|
234
|
+
catch(fallbackError) {if(fallbackError.code!=='ENOENT')throw fallbackError;bootstrap(parent);}
|
|
235
|
+
}
|
|
236
|
+
reclaim(parent);
|
|
237
|
+
target=resolveTarget(path.win32.join(parent,`blun-acl-${randomUUID()}`));
|
|
238
|
+
const identity=bootstrap(target);
|
|
239
|
+
const marker={version:2,sid:userSid,pid:process.pid,dev:String(identity.dev),ino:String(identity.ino),token:randomUUID()};
|
|
240
|
+
fs.writeFileSync(path.win32.join(target,MARKER),JSON.stringify(marker),{flag:'wx',mode:0o600});
|
|
241
|
+
return {path:target,dispose(){return removeVerified(target,identity,marker);}};
|
|
242
|
+
} catch(error) {
|
|
243
|
+
if(typeof error?.code==='string' && error.code.startsWith('BLUN_PRIVATE_ACL_TEMP_'))throw error;
|
|
244
|
+
const marker=typeof error?.stderr==='string'?/^BLUN_PRIVATE_TEMP_ERROR_V2:(TEMP_PATH|TEMP_CREATE|TEMP_ACL_VERIFICATION|TEMP_WRITE_PROBE)$/u.exec(error.stderr):null;
|
|
245
|
+
throw fail(marker?marker[1]:'TEMP_DIRECTORY',target);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
module.exports = {createWindowsPrivateTemp};
|
package/blun.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// BLUN_BUILD_INPUT_SHA256:
|
|
2
|
+
// BLUN_BUILD_INPUT_SHA256:295bff16bb3a40df46f164599652a975e64b232ee91e1b245fa87962a4b61885
|
|
3
3
|
/*! wasm-webp 0.1.0
|
|
4
4
|
MIT License
|
|
5
5
|
|
|
@@ -13347,23 +13347,15 @@ var init_managed_usage = __esmMin((() => {
|
|
|
13347
13347
|
init_utils$2();
|
|
13348
13348
|
DEFAULT_BLUN_BASE_URL = "https://api.blun.ai/v1";
|
|
13349
13349
|
DEFAULT_BLUN_AUXILIARY_BASE_URL = "https://api.blun.ai/coding/v1";
|
|
13350
|
-
ACCOUNT_USAGE_WINDOWS = [
|
|
13351
|
-
|
|
13352
|
-
|
|
13353
|
-
|
|
13354
|
-
|
|
13355
|
-
|
|
13356
|
-
|
|
13357
|
-
|
|
13358
|
-
|
|
13359
|
-
"7d"
|
|
13360
|
-
],
|
|
13361
|
-
[
|
|
13362
|
-
"monat",
|
|
13363
|
-
"month",
|
|
13364
|
-
"month"
|
|
13365
|
-
]
|
|
13366
|
-
];
|
|
13350
|
+
ACCOUNT_USAGE_WINDOWS = [[
|
|
13351
|
+
"sieben_tage",
|
|
13352
|
+
"seven_days",
|
|
13353
|
+
"7d"
|
|
13354
|
+
], [
|
|
13355
|
+
"monat",
|
|
13356
|
+
"month",
|
|
13357
|
+
"month"
|
|
13358
|
+
]];
|
|
13367
13359
|
}));
|
|
13368
13360
|
function cloneOverrides(overrides) {
|
|
13369
13361
|
if (overrides === void 0) return void 0;
|
|
@@ -13864,9 +13856,11 @@ function parseManagedQuotaPayload(payload) {
|
|
|
13864
13856
|
const billingKind = nonEmptyString$6(payload["art"]);
|
|
13865
13857
|
const globalUnlimited = payload["unlimited"];
|
|
13866
13858
|
if (plan === void 0 || typeof paid !== "boolean" || !Number.isSafeInteger(creditCents) || creditCents < 0 || billingKind === void 0 || globalUnlimited !== void 0 && typeof globalUnlimited !== "boolean" || !isRecord$27(payload["stand"])) return;
|
|
13867
|
-
|
|
13859
|
+
const stand = payload["stand"];
|
|
13860
|
+
if (!hasStrictQuotaStand(stand, globalUnlimited === true)) return void 0;
|
|
13861
|
+
const presentWindows = QUOTA_WINDOWS.filter(([sourceKey]) => sourceKey in stand);
|
|
13868
13862
|
const limits = parseManagedUsagePayload(payload).limits;
|
|
13869
|
-
if (limits.length !==
|
|
13863
|
+
if (limits.length !== presentWindows.length || presentWindows.some(([, id]) => limits.filter((row) => row.id === id).length !== 1)) return;
|
|
13870
13864
|
return {
|
|
13871
13865
|
plan,
|
|
13872
13866
|
paid,
|
|
@@ -13931,7 +13925,8 @@ function nonEmptyString$6(value) {
|
|
|
13931
13925
|
return normalized.length === 0 ? void 0 : normalized;
|
|
13932
13926
|
}
|
|
13933
13927
|
function hasStrictQuotaStand(stand, globalUnlimited) {
|
|
13934
|
-
return
|
|
13928
|
+
return QUOTA_WINDOWS.every(([sourceKey]) => {
|
|
13929
|
+
if (!(sourceKey in stand)) return true;
|
|
13935
13930
|
const row = stand[sourceKey];
|
|
13936
13931
|
if (!isRecord$27(row)) return false;
|
|
13937
13932
|
const used = row["verbraucht"];
|
|
@@ -13954,18 +13949,14 @@ function hasValidResetAt(value) {
|
|
|
13954
13949
|
if (typeof value !== "string") return false;
|
|
13955
13950
|
return /(?:Z|[+-]\d{2}:\d{2})$/i.test(value) && Number.isFinite(Date.parse(value));
|
|
13956
13951
|
}
|
|
13957
|
-
var MANAGED_QUOTA_PATH,
|
|
13952
|
+
var MANAGED_QUOTA_PATH, QUOTA_WINDOWS;
|
|
13958
13953
|
var init_managed_quota$1 = __esmMin((() => {
|
|
13959
13954
|
init_constants$6();
|
|
13960
13955
|
init_api_error();
|
|
13961
13956
|
init_managed_usage();
|
|
13962
13957
|
init_utils$2();
|
|
13963
13958
|
MANAGED_QUOTA_PATH = "/api/verbrauch/mein-stand";
|
|
13964
|
-
|
|
13965
|
-
["fuenf_stunden", "five_hours"],
|
|
13966
|
-
["sieben_tage", "seven_days"],
|
|
13967
|
-
["monat", "month"]
|
|
13968
|
-
];
|
|
13959
|
+
QUOTA_WINDOWS = [["sieben_tage", "seven_days"], ["monat", "month"]];
|
|
13969
13960
|
}));
|
|
13970
13961
|
function blunCodeFeedbackUrl(baseUrl) {
|
|
13971
13962
|
return `${blunCodeAuxiliaryBaseUrl(baseUrl)}/feedback`;
|
|
@@ -529129,8 +529120,11 @@ function normalizeManagedQuotaWindows(rows) {
|
|
|
529129
529120
|
unlimited: row.unlimited === true ? true : void 0
|
|
529130
529121
|
});
|
|
529131
529122
|
}
|
|
529132
|
-
if (byId.size
|
|
529133
|
-
return WINDOW_IDS.
|
|
529123
|
+
if (byId.size === 0 && rows.some((row) => row.id !== void 0 && WINDOW_IDS.includes(row.id))) return;
|
|
529124
|
+
return WINDOW_IDS.flatMap((id) => {
|
|
529125
|
+
const window = byId.get(id);
|
|
529126
|
+
return window === void 0 ? [] : [window];
|
|
529127
|
+
});
|
|
529134
529128
|
}
|
|
529135
529129
|
function selectHighestManagedQuotaWindow(windows) {
|
|
529136
529130
|
return windows?.filter((window) => window.unlimited !== true).reduce((highest, window) => highest === void 0 || window.fraction > highest.fraction ? window : highest, void 0);
|
|
@@ -529148,11 +529142,7 @@ function nextManagedQuotaWarning(windows, highestShown) {
|
|
|
529148
529142
|
var MANAGED_QUOTA_WARNING_METADATA_KEY, WINDOW_IDS;
|
|
529149
529143
|
var init_managed_quota = __esmMin((() => {
|
|
529150
529144
|
MANAGED_QUOTA_WARNING_METADATA_KEY = "managedQuotaWarningThreshold";
|
|
529151
|
-
WINDOW_IDS = [
|
|
529152
|
-
"five_hours",
|
|
529153
|
-
"seven_days",
|
|
529154
|
-
"month"
|
|
529155
|
-
];
|
|
529145
|
+
WINDOW_IDS = ["seven_days", "month"];
|
|
529156
529146
|
}));
|
|
529157
529147
|
function managedProviderOnly(providers) {
|
|
529158
529148
|
const managed = providers[DEFAULT_OAUTH_PROVIDER_NAME];
|
|
@@ -537127,6 +537117,7 @@ function centerQuotaLine(line, width) {
|
|
|
537127
537117
|
return `${" ".repeat(leftPadding)}${line}`;
|
|
537128
537118
|
}
|
|
537129
537119
|
function formatManagedQuotaFooterLines(windows, colors, width, options = {}) {
|
|
537120
|
+
windows = windows.filter((window) => window.id !== "five_hours");
|
|
537130
537121
|
if (windows.length === 0 || width <= 0) return [];
|
|
537131
537122
|
const locale = options.locale ?? getCurrentUiLocale();
|
|
537132
537123
|
const variants = [
|
package/package.json
CHANGED
package/worker-host.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// BLUN_BUILD_INPUT_SHA256:
|
|
2
|
+
// BLUN_BUILD_INPUT_SHA256:295bff16bb3a40df46f164599652a975e64b232ee91e1b245fa87962a4b61885
|
|
3
3
|
/*! wasm-webp 0.1.0
|
|
4
4
|
MIT License
|
|
5
5
|
|
|
@@ -13011,23 +13011,15 @@ function managedContextWindowFrom(payload) {
|
|
|
13011
13011
|
const [first] = values;
|
|
13012
13012
|
return values.every((value) => value === first) ? first : void 0;
|
|
13013
13013
|
}
|
|
13014
|
-
const ACCOUNT_USAGE_WINDOWS = [
|
|
13015
|
-
|
|
13016
|
-
|
|
13017
|
-
|
|
13018
|
-
|
|
13019
|
-
|
|
13020
|
-
|
|
13021
|
-
|
|
13022
|
-
|
|
13023
|
-
"7d"
|
|
13024
|
-
],
|
|
13025
|
-
[
|
|
13026
|
-
"monat",
|
|
13027
|
-
"month",
|
|
13028
|
-
"month"
|
|
13029
|
-
]
|
|
13030
|
-
];
|
|
13014
|
+
const ACCOUNT_USAGE_WINDOWS = [[
|
|
13015
|
+
"sieben_tage",
|
|
13016
|
+
"seven_days",
|
|
13017
|
+
"7d"
|
|
13018
|
+
], [
|
|
13019
|
+
"monat",
|
|
13020
|
+
"month",
|
|
13021
|
+
"month"
|
|
13022
|
+
]];
|
|
13031
13023
|
function toAccountUsageRow(raw, id, label, accountUnlimited) {
|
|
13032
13024
|
if (!isRecord$9(raw)) return null;
|
|
13033
13025
|
const used = toInt(raw["verbraucht"]);
|
|
@@ -13738,11 +13730,7 @@ async function provisionManagedBlunCodeConfig(options) {
|
|
|
13738
13730
|
};
|
|
13739
13731
|
}
|
|
13740
13732
|
const MANAGED_QUOTA_PATH = "/api/verbrauch/mein-stand";
|
|
13741
|
-
const
|
|
13742
|
-
["fuenf_stunden", "five_hours"],
|
|
13743
|
-
["sieben_tage", "seven_days"],
|
|
13744
|
-
["monat", "month"]
|
|
13745
|
-
];
|
|
13733
|
+
const QUOTA_WINDOWS = [["sieben_tage", "seven_days"], ["monat", "month"]];
|
|
13746
13734
|
function blunManagedQuotaUrl(oauthHost) {
|
|
13747
13735
|
return `${(oauthHost ?? process.env["BLUN_OAUTH_HOST"] ?? "https://account.blun.ai").replace(/\/+$/, "")}${MANAGED_QUOTA_PATH}`;
|
|
13748
13736
|
}
|
|
@@ -13754,9 +13742,11 @@ function parseManagedQuotaPayload(payload) {
|
|
|
13754
13742
|
const billingKind = nonEmptyString$5(payload["art"]);
|
|
13755
13743
|
const globalUnlimited = payload["unlimited"];
|
|
13756
13744
|
if (plan === void 0 || typeof paid !== "boolean" || !Number.isSafeInteger(creditCents) || creditCents < 0 || billingKind === void 0 || globalUnlimited !== void 0 && typeof globalUnlimited !== "boolean" || !isRecord$9(payload["stand"])) return;
|
|
13757
|
-
|
|
13745
|
+
const stand = payload["stand"];
|
|
13746
|
+
if (!hasStrictQuotaStand(stand, globalUnlimited === true)) return void 0;
|
|
13747
|
+
const presentWindows = QUOTA_WINDOWS.filter(([sourceKey]) => sourceKey in stand);
|
|
13758
13748
|
const limits = parseManagedUsagePayload(payload).limits;
|
|
13759
|
-
if (limits.length !==
|
|
13749
|
+
if (limits.length !== presentWindows.length || presentWindows.some(([, id]) => limits.filter((row) => row.id === id).length !== 1)) return;
|
|
13760
13750
|
return {
|
|
13761
13751
|
plan,
|
|
13762
13752
|
paid,
|
|
@@ -13821,7 +13811,8 @@ function nonEmptyString$5(value) {
|
|
|
13821
13811
|
return normalized.length === 0 ? void 0 : normalized;
|
|
13822
13812
|
}
|
|
13823
13813
|
function hasStrictQuotaStand(stand, globalUnlimited) {
|
|
13824
|
-
return
|
|
13814
|
+
return QUOTA_WINDOWS.every(([sourceKey]) => {
|
|
13815
|
+
if (!(sourceKey in stand)) return true;
|
|
13825
13816
|
const row = stand[sourceKey];
|
|
13826
13817
|
if (!isRecord$9(row)) return false;
|
|
13827
13818
|
const used = row["verbraucht"];
|