blun-king-cli 9.1.631 → 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,
@@ -125,8 +125,8 @@ const MARKER = '.blun-acl-owner-v2.json';
125
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
126
  const CLEANUP_ERRORS = new Set(['EACCES','EPERM','EBUSY','ENOTEMPTY']);
127
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,
128
+ function warning(target, warn, attempts = 3) {
129
+ const value = {code:'BLUN_PRIVATE_ACL_TEMP_CLEANUP',privatePath:target,attempts,
130
130
  nextStep:'BLUN_PRIVATE_ACL_TEMP_RECLAIM_NEXT_START'};
131
131
  if (warn) warn(value);
132
132
  else process.emitWarning(`[${value.code}] ${target}; ${value.nextStep}`, {code:value.code});
@@ -171,11 +171,27 @@ function createWindowsPrivateTemp({ systemDirectory, userSid, resolveTarget,
171
171
  const fd=fs.openSync(p,'r');
172
172
  try {
173
173
  if(!identityIs(fs.fstatSync(fd,{bigint:true}),before))throw fail('TEMP_IDENTITY',candidate);
174
- const value=JSON.parse(fs.readFileSync(fd,'utf8'));
174
+ let value;
175
+ try { value=JSON.parse(fs.readFileSync(fd,'utf8')); }
176
+ catch(error) { if(error instanceof SyntaxError)return null;throw error; }
175
177
  if(!identityIs(fs.lstatSync(p,{bigint:true}),before))throw fail('TEMP_IDENTITY',candidate);
176
178
  return value;
177
179
  } finally {fs.closeSync(fd);}
178
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
+ };
179
195
  const removeVerified = (candidate, identity, marker) => {
180
196
  for(let attempt=1;attempt<=3;attempt++) {
181
197
  // Security/identity failures are NOT cleanup warnings, even after hardening.
@@ -183,7 +199,7 @@ function createWindowsPrivateTemp({ systemDirectory, userSid, resolveTarget,
183
199
  if(!identityIs(current,identity))throw fail('TEMP_IDENTITY',candidate);
184
200
  verify(candidate);
185
201
  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);
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);
187
203
  const plan=planFor(candidate);
188
204
  // Keep the ownership marker until every compiler file has been removed.
189
205
  const markerPath=path.win32.join(candidate,MARKER);
@@ -199,7 +215,7 @@ function createWindowsPrivateTemp({ systemDirectory, userSid, resolveTarget,
199
215
  } catch(error) {
200
216
  if(!CLEANUP_ERRORS.has(error.code))throw error;
201
217
  // 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});
218
+ if(!fs.existsSync(markerPath))writeMarker(candidate,marker);
203
219
  if(attempt<3)pause();
204
220
  }
205
221
  }
@@ -215,11 +231,20 @@ function createWindowsPrivateTemp({ systemDirectory, userSid, resolveTarget,
215
231
  if(!st.isDirectory() || st.isSymbolicLink())continue;
216
232
  const markerPath=path.win32.join(candidate,MARKER);
217
233
  if(!fs.existsSync(markerPath))continue;
218
- verify(candidate);
219
234
  const marker=readMarker(candidate);
235
+ if(marker===null)continue;
220
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);
221
237
  // Any live process with this pid keeps its compiler area, including pid reuse.
222
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
+ }
223
248
  removeVerified(candidate,st,marker);
224
249
  }
225
250
  };
@@ -229,15 +254,24 @@ function createWindowsPrivateTemp({ systemDirectory, userSid, resolveTarget,
229
254
  catch(error) {
230
255
  if(error.code!=='ENOENT' && !(error.code==='BLUN_PRIVATE_ACL_TEMP_PATH' && error.reparse===true))throw error;
231
256
  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);}
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);
235
269
  }
236
270
  reclaim(parent);
237
271
  target=resolveTarget(path.win32.join(parent,`blun-acl-${randomUUID()}`));
238
272
  const identity=bootstrap(target);
239
273
  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});
274
+ writeMarker(target,marker);
241
275
  return {path:target,dispose(){return removeVerified(target,identity,marker);}};
242
276
  } catch(error) {
243
277
  if(typeof error?.code==='string' && error.code.startsWith('BLUN_PRIVATE_ACL_TEMP_'))throw error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blun-king-cli",
3
- "version": "9.1.631",
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": {