blun-king-cli 9.1.630 → 9.1.633

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.
@@ -1283,6 +1283,187 @@ function queueExplicitUpdate(blunDir, release, stdout, stderr, locale) {
1283
1283
  return { kind: 'queued', version: release.version };
1284
1284
  }
1285
1285
 
1286
+ async function readSnoozeStateAsync(io, blunDir, now = Date.now()) {
1287
+ try {
1288
+ const filePath = statePath(blunDir);
1289
+ if (!fs.existsSync(filePath)) return false;
1290
+ await io.securePrivateFile(filePath);
1291
+ const stat = fs.lstatSync(filePath);
1292
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1_024) return false;
1293
+ const record = exactDataRecord(JSON.parse(fs.readFileSync(filePath, 'utf8')), [
1294
+ 'snoozedUntil',
1295
+ 'version',
1296
+ ]);
1297
+ if (!record
1298
+ || record.version !== 1
1299
+ || !Number.isSafeInteger(record.snoozedUntil)
1300
+ || record.snoozedUntil <= now
1301
+ || record.snoozedUntil > now + SNOOZE_MS) {
1302
+ return false;
1303
+ }
1304
+ return true;
1305
+ } catch {
1306
+ return false;
1307
+ }
1308
+ }
1309
+
1310
+ async function writeSnoozeStateAsync(io, blunDir, now = Date.now()) {
1311
+ await io.ensurePrivateDirectory(blunDir);
1312
+ const filePath = statePath(blunDir);
1313
+ const temporaryPath = path.join(
1314
+ blunDir,
1315
+ `.${STATE_FILE}.${process.pid}.${randomUUID()}.tmp`,
1316
+ );
1317
+ try {
1318
+ await io.writePrivateFile(temporaryPath, `${JSON.stringify({
1319
+ version: 1,
1320
+ snoozedUntil: now + SNOOZE_MS,
1321
+ })}\n`);
1322
+ const handle = fs.openSync(temporaryPath, 'r+');
1323
+ try {
1324
+ fs.fsyncSync(handle);
1325
+ } finally {
1326
+ fs.closeSync(handle);
1327
+ }
1328
+ fs.renameSync(temporaryPath, filePath);
1329
+ await io.securePrivateFile(filePath);
1330
+ } catch (error) {
1331
+ fs.rmSync(temporaryPath, { force: true });
1332
+ throw error;
1333
+ }
1334
+ }
1335
+
1336
+ async function readSkippedVersionAsync(io, blunDir) {
1337
+ try {
1338
+ const filePath = skippedVersionPath(blunDir);
1339
+ if (!fs.existsSync(filePath)) return undefined;
1340
+ await io.securePrivateFile(filePath);
1341
+ const stat = fs.lstatSync(filePath);
1342
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1_024) return undefined;
1343
+ const record = exactDataRecord(JSON.parse(fs.readFileSync(filePath, 'utf8')), [
1344
+ 'skippedVersion',
1345
+ 'version',
1346
+ ]);
1347
+ if (!record || record.version !== 1 || !parseSemver(record.skippedVersion)) {
1348
+ return undefined;
1349
+ }
1350
+ return record.skippedVersion;
1351
+ } catch {
1352
+ return undefined;
1353
+ }
1354
+ }
1355
+
1356
+ async function writeSkippedVersionAsync(io, blunDir, skippedVersion) {
1357
+ if (!parseSemver(skippedVersion)) throw new Error('INVALID_UPDATE_VERSION');
1358
+ await io.ensurePrivateDirectory(blunDir);
1359
+ const filePath = skippedVersionPath(blunDir);
1360
+ const temporaryPath = path.join(
1361
+ blunDir,
1362
+ `.${UPDATE_SKIP_FILE}.${process.pid}.${randomUUID()}.tmp`,
1363
+ );
1364
+ try {
1365
+ await io.writePrivateFile(temporaryPath, `${JSON.stringify({
1366
+ version: 1,
1367
+ skippedVersion,
1368
+ })}\n`);
1369
+ const handle = fs.openSync(temporaryPath, 'r+');
1370
+ try {
1371
+ fs.fsyncSync(handle);
1372
+ } finally {
1373
+ fs.closeSync(handle);
1374
+ }
1375
+ fs.renameSync(temporaryPath, filePath);
1376
+ await io.securePrivateFile(filePath);
1377
+ } catch (error) {
1378
+ fs.rmSync(temporaryPath, { force: true });
1379
+ throw error;
1380
+ }
1381
+ }
1382
+
1383
+ async function readPendingUpdateAsync(io, blunDir) {
1384
+ try {
1385
+ const filePath = pendingUpdatePath(blunDir);
1386
+ if (!fs.existsSync(filePath)) return undefined;
1387
+ await io.securePrivateFile(filePath);
1388
+ const stat = fs.lstatSync(filePath);
1389
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1_024) return undefined;
1390
+ const record = exactDataRecord(JSON.parse(fs.readFileSync(filePath, 'utf8')), [
1391
+ 'targetVersion',
1392
+ 'version',
1393
+ ]);
1394
+ if (!record || record.version !== 1 || !parseSemver(record.targetVersion)) return undefined;
1395
+ return record.targetVersion;
1396
+ } catch {
1397
+ return undefined;
1398
+ }
1399
+ }
1400
+
1401
+ async function writePendingUpdateAsync(io, blunDir, targetVersion) {
1402
+ if (!parseSemver(targetVersion)) throw new Error('INVALID_UPDATE_VERSION');
1403
+ await io.ensurePrivateDirectory(blunDir);
1404
+ const filePath = pendingUpdatePath(blunDir);
1405
+ const temporaryPath = path.join(
1406
+ blunDir,
1407
+ `.${PENDING_UPDATE_FILE}.${process.pid}.${randomUUID()}.tmp`,
1408
+ );
1409
+ try {
1410
+ await io.writePrivateFile(temporaryPath, `${JSON.stringify({
1411
+ version: 1,
1412
+ targetVersion,
1413
+ })}\n`);
1414
+ const handle = fs.openSync(temporaryPath, 'r+');
1415
+ try {
1416
+ fs.fsyncSync(handle);
1417
+ } finally {
1418
+ fs.closeSync(handle);
1419
+ }
1420
+ fs.renameSync(temporaryPath, filePath);
1421
+ await io.securePrivateFile(filePath);
1422
+ } catch (error) {
1423
+ fs.rmSync(temporaryPath, { force: true });
1424
+ throw error;
1425
+ }
1426
+ }
1427
+
1428
+ async function writeCoreInstallSuccessAsync(io, blunDir, fromVersion, version, now = Date.now()) {
1429
+ if (!parseSemver(fromVersion) || !parseSemver(version)) {
1430
+ throw new Error('INVALID_UPDATE_VERSION');
1431
+ }
1432
+ const updateDirectory = path.join(blunDir, UPDATE_DIRECTORY);
1433
+ await io.ensurePrivateDirectory(blunDir);
1434
+ await io.ensurePrivateDirectory(updateDirectory);
1435
+ const filePath = path.join(updateDirectory, CORE_INSTALL_STATE_FILE);
1436
+ const temporaryPath = path.join(
1437
+ updateDirectory,
1438
+ `.${CORE_INSTALL_STATE_FILE}.${process.pid}.${randomUUID()}.tmp`,
1439
+ );
1440
+ try {
1441
+ await io.writePrivateFile(temporaryPath, `${JSON.stringify({
1442
+ active: null,
1443
+ lastFailure: null,
1444
+ lastSuccess: {
1445
+ version,
1446
+ fromVersion,
1447
+ installedAt: new Date(now).toISOString(),
1448
+ notifiedAt: null,
1449
+ },
1450
+ })}\n`);
1451
+ const handle = fs.openSync(temporaryPath, 'r+');
1452
+ try {
1453
+ fs.fsyncSync(handle);
1454
+ } finally {
1455
+ fs.closeSync(handle);
1456
+ }
1457
+ fs.renameSync(temporaryPath, filePath);
1458
+ await io.securePrivateFile(filePath);
1459
+ } catch (error) {
1460
+ fs.rmSync(temporaryPath, { force: true });
1461
+ throw error;
1462
+ }
1463
+ }
1464
+
1465
+ const STARTUP_STATE_SYNC = {readSnoozeState,writeSnoozeState,readSkippedVersion,writeSkippedVersion,readPendingUpdate,writePendingUpdate,writeCoreInstallSuccess};
1466
+ const STARTUP_STATE_ASYNC = {readSnoozeState:readSnoozeStateAsync,writeSnoozeState:writeSnoozeStateAsync,readSkippedVersion:readSkippedVersionAsync,writeSkippedVersion:writeSkippedVersionAsync,readPendingUpdate:readPendingUpdateAsync,writePendingUpdate:writePendingUpdateAsync,writeCoreInstallSuccess:writeCoreInstallSuccessAsync};
1286
1467
  async function runUpdateFlow(options, explicitUpdate) {
1287
1468
  const {
1288
1469
  currentVersion,
@@ -1293,6 +1474,8 @@ async function runUpdateFlow(options, explicitUpdate) {
1293
1474
  stderr,
1294
1475
  blunDir,
1295
1476
  } = options;
1477
+ const state = Object.fromEntries(Object.entries(STARTUP_STATE_SYNC).map(([name, fn]) =>
1478
+ [name, options.startupSecurity ? (...args) => STARTUP_STATE_ASYNC[name](options.startupSecurity, ...args) : fn]));
1296
1479
  const locale = resolveUpdateLocale(options);
1297
1480
  if (!explicitUpdate && !isInteractiveUpdateStart({ argv, env, stdin, stdout })) {
1298
1481
  return { kind: 'continue', reason: 'not_interactive' };
@@ -1303,13 +1486,13 @@ async function runUpdateFlow(options, explicitUpdate) {
1303
1486
  : { kind: 'continue', reason: 'invalid_current_version' };
1304
1487
  }
1305
1488
 
1306
- let pendingVersion = readPendingUpdate(blunDir);
1489
+ let pendingVersion = await state.readPendingUpdate(blunDir);
1307
1490
  if (pendingVersion !== undefined && compareSemver(currentVersion, pendingVersion) >= 0) {
1308
1491
  clearPendingUpdate(blunDir);
1309
1492
  pendingVersion = undefined;
1310
1493
  }
1311
1494
  const now = (options.now || Date.now)();
1312
- if (!explicitUpdate && pendingVersion === undefined && readSnoozeState(blunDir, now)) {
1495
+ if (!explicitUpdate && pendingVersion === undefined && await state.readSnoozeState(blunDir, now)) {
1313
1496
  return { kind: 'continue', reason: 'snoozed' };
1314
1497
  }
1315
1498
 
@@ -1346,7 +1529,7 @@ async function runUpdateFlow(options, explicitUpdate) {
1346
1529
  try {
1347
1530
  if (!explicitUpdate
1348
1531
  && pendingVersion === undefined
1349
- && readSnoozeState(blunDir, (options.now || Date.now)())) {
1532
+ && await state.readSnoozeState(blunDir, (options.now || Date.now)())) {
1350
1533
  return { kind: 'continue', reason: 'snoozed' };
1351
1534
  }
1352
1535
  let sources;
@@ -1378,12 +1561,13 @@ async function runUpdateFlow(options, explicitUpdate) {
1378
1561
  ? explicitFailure(stderr, 'lease_unavailable', undefined, locale)
1379
1562
  : { kind: 'continue', reason: 'lease_unavailable' };
1380
1563
  }
1381
- if (!explicitUpdate && !queuedForRelease && readSkippedVersion(blunDir) === release.version) {
1564
+ if (!explicitUpdate && !queuedForRelease && await state.readSkippedVersion(blunDir) === release.version) {
1382
1565
  return { kind: 'continue', reason: 'skipped_version' };
1383
1566
  }
1384
1567
  if (explicitUpdate || queuedForRelease) {
1385
1568
  try {
1386
- ensurePrivateDirectory(blunDir);
1569
+ if (options.startupSecurity) await options.startupSecurity.ensurePrivateDirectory(blunDir);
1570
+ else ensurePrivateDirectory(blunDir);
1387
1571
  } catch {
1388
1572
  return explicitFailure(stderr, 'private_home_unavailable', undefined, locale);
1389
1573
  }
@@ -1443,14 +1627,14 @@ async function runUpdateFlow(options, explicitUpdate) {
1443
1627
  }
1444
1628
  if (action === 'skip-version') {
1445
1629
  try {
1446
- writeSkippedVersion(blunDir, release.version);
1630
+ await state.writeSkippedVersion(blunDir, release.version);
1447
1631
  } catch {
1448
1632
  // A failed preference write must not block the existing console.
1449
1633
  }
1450
1634
  return { kind: 'continue', reason: 'skipped_version' };
1451
1635
  }
1452
1636
  try {
1453
- writeSnoozeState(blunDir, (options.now || Date.now)());
1637
+ await state.writeSnoozeState(blunDir, (options.now || Date.now)());
1454
1638
  } catch {
1455
1639
  // A failed preference write must not block the existing console.
1456
1640
  }
@@ -1489,7 +1673,7 @@ async function runUpdateFlow(options, explicitUpdate) {
1489
1673
  updateProgress(4, updateText(locale, 'installVerified'));
1490
1674
  clearPendingUpdate(blunDir);
1491
1675
  try {
1492
- writeCoreInstallSuccess(
1676
+ await state.writeCoreInstallSuccess(
1493
1677
  blunDir,
1494
1678
  currentVersion,
1495
1679
  release.version,
@@ -0,0 +1,282 @@
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, attempts = 3) {
129
+ const value = {code:'BLUN_PRIVATE_ACL_TEMP_CLEANUP',privatePath:target,attempts,
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
+ let value;
175
+ try { value=JSON.parse(fs.readFileSync(fd,'utf8')); }
176
+ catch(error) { if(error instanceof SyntaxError)return null;throw error; }
177
+ if(!identityIs(fs.lstatSync(p,{bigint:true}),before))throw fail('TEMP_IDENTITY',candidate);
178
+ return value;
179
+ } finally {fs.closeSync(fd);}
180
+ };
181
+ // Publish only a complete marker. A crash before rename leaves an unmarked tree.
182
+ const writeMarker = (candidate, marker) => {
183
+ const markerPath=path.win32.join(candidate,MARKER);
184
+ const temporary=path.win32.join(candidate,`${MARKER}.${randomUUID()}.tmp`);
185
+ let created=false;
186
+ try {
187
+ fs.writeFileSync(temporary,JSON.stringify(marker),{flag:'wx',mode:0o600});
188
+ created=true;
189
+ fs.renameSync(temporary,markerPath);
190
+ created=false;
191
+ } finally {
192
+ if(created)fs.unlinkSync(temporary);
193
+ }
194
+ };
195
+ const removeVerified = (candidate, identity, marker) => {
196
+ for(let attempt=1;attempt<=3;attempt++) {
197
+ // Security/identity failures are NOT cleanup warnings, even after hardening.
198
+ const current=checkedDirectory(candidate);
199
+ if(!identityIs(current,identity))throw fail('TEMP_IDENTITY',candidate);
200
+ verify(candidate);
201
+ const saved=readMarker(candidate);
202
+ if(!saved || saved.token!==marker.token || saved.sid!==userSid || saved.dev!==String(identity.dev) || saved.ino!==String(identity.ino))throw fail('TEMP_IDENTITY',candidate);
203
+ const plan=planFor(candidate);
204
+ // Keep the ownership marker until every compiler file has been removed.
205
+ const markerPath=path.win32.join(candidate,MARKER);
206
+ const ordered=plan.filter(e=>e.path!==candidate && e.path!==markerPath);
207
+ ordered.push(plan.find(e=>e.path===markerPath),plan.find(e=>e.path===candidate));
208
+ try {
209
+ for(const entry of ordered) {
210
+ const now=fs.lstatSync(entry.path,{bigint:true});
211
+ if(!identityIs(now,entry.stat) || now.isSymbolicLink() || (!now.isDirectory() && now.nlink!==1n))throw fail('TEMP_IDENTITY',entry.path);
212
+ if(now.isDirectory())fs.rmdirSync(entry.path);else fs.unlinkSync(entry.path);
213
+ }
214
+ return true;
215
+ } catch(error) {
216
+ if(!CLEANUP_ERRORS.has(error.code))throw error;
217
+ // If the final empty directory removal was blocked, restore its own marker.
218
+ if(!fs.existsSync(markerPath))writeMarker(candidate,marker);
219
+ if(attempt<3)pause();
220
+ }
221
+ }
222
+ warning(candidate,warn);
223
+ return false;
224
+ };
225
+ const reclaim = parent => {
226
+ for(const name of fs.readdirSync(parent)) {
227
+ if(!NAME.test(name))continue;
228
+ const candidate=path.win32.join(parent,name);
229
+ // Unmarked directories are not ours. Do not traverse or repair foreign trees.
230
+ const st=fs.lstatSync(candidate,{bigint:true});
231
+ if(!st.isDirectory() || st.isSymbolicLink())continue;
232
+ const markerPath=path.win32.join(candidate,MARKER);
233
+ if(!fs.existsSync(markerPath))continue;
234
+ const marker=readMarker(candidate);
235
+ if(marker===null)continue;
236
+ 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);
237
+ // Any live process with this pid keeps its compiler area, including pid reuse.
238
+ try {process.kill(marker.pid,0);continue;} catch(error) {if(error.code!=='ESRCH')continue;}
239
+ // Reparse/hardlink/identity failures remain fatal, not stale-ACL warnings.
240
+ checkedDirectory(candidate);
241
+ planFor(candidate);
242
+ try {verify(candidate);}
243
+ catch(error) {
244
+ if(error.code!=='BLUN_PRIVATE_ACL_TEMP_ACL_VERIFICATION')throw error;
245
+ warning(candidate,warn,0);
246
+ continue;
247
+ }
248
+ removeVerified(candidate,st,marker);
249
+ }
250
+ };
251
+ try {
252
+ let parent=resolveTarget(tempRoot.replace(/\\+$/u,''));
253
+ try {checkedDirectory(parent);}
254
+ catch(error) {
255
+ if(error.code!=='ENOENT' && !(error.code==='BLUN_PRIVATE_ACL_TEMP_PATH' && error.reparse===true))throw error;
256
+ parent=resolveTarget(privateTempRoot.replace(/\\+$/u,''));
257
+ // Walk from an existing no-follow anchor. Each missing ancestor is created
258
+ // with its private ACL at creation time, never mkdir + later hardening.
259
+ const ensureFallback = candidate => {
260
+ try {checkedDirectory(candidate);return false;}
261
+ catch(fallbackError) {if(fallbackError.code!=='ENOENT')throw fallbackError;}
262
+ const ancestor=path.win32.dirname(candidate);
263
+ if(ancestor===candidate)throw fail('TEMP_PATH',candidate);
264
+ ensureFallback(ancestor);
265
+ bootstrap(candidate);
266
+ return true;
267
+ };
268
+ if(!ensureFallback(parent))verify(parent);
269
+ }
270
+ reclaim(parent);
271
+ target=resolveTarget(path.win32.join(parent,`blun-acl-${randomUUID()}`));
272
+ const identity=bootstrap(target);
273
+ const marker={version:2,sid:userSid,pid:process.pid,dev:String(identity.dev),ino:String(identity.ino),token:randomUUID()};
274
+ writeMarker(target,marker);
275
+ return {path:target,dispose(){return removeVerified(target,identity,marker);}};
276
+ } catch(error) {
277
+ if(typeof error?.code==='string' && error.code.startsWith('BLUN_PRIVATE_ACL_TEMP_'))throw error;
278
+ 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;
279
+ throw fail(marker?marker[1]:'TEMP_DIRECTORY',target);
280
+ }
281
+ }
282
+ module.exports = {createWindowsPrivateTemp};
package/blun.mjs CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blun-king-cli",
3
- "version": "9.1.630",
3
+ "version": "9.1.633",
4
4
  "description": "BLUN CLI - your own AI agent with a Telegram channel. Get it done. With BLUN.",
5
5
  "license": "MIT",
6
6
  "bin": {