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.
@@ -42,7 +42,7 @@ function renamePrivateStaging(source, target, options = {}) {
42
42
  const impl = options.fsImpl || fs;
43
43
  if ((options.platform || process.platform) !== 'win32') return impl.renameSync(source, target);
44
44
  if (canonical(path.dirname(target)) !== canonical(path.dirname(source))
45
- || !/^(?:telegram|agent-spine-[a-f0-9]{64})$/.test(path.basename(target))) throw new Error('Invalid private staging target');
45
+ || !/^(?:telegram(?:-[a-f0-9]{64}(?:-[a-f0-9-]{36})?)?|agent-spine-[a-f0-9]{64})$/.test(path.basename(target))) throw new Error('Invalid private staging target');
46
46
  const identity = stagingState(source, impl);
47
47
  if (!identity) throw new Error('Private staging is missing');
48
48
  return withWindowsFsRetry(() => impl.renameSync(source, target), {
@@ -269,7 +269,104 @@ function seedStandardDesignSkill({ packageRoot, blunDir }) {
269
269
  return { installed, updated: !installed, destinationPath };
270
270
  }
271
271
 
272
+ async function writeMcpDocumentAsync(configPath, document, io) {
273
+ const temporaryPath = path.join(
274
+ path.dirname(configPath),
275
+ `.${path.basename(configPath)}.${process.pid}.${randomUUID()}.tmp`,
276
+ );
277
+ try {
278
+ await io.writePrivateFile(temporaryPath, `${JSON.stringify(document, null, 2)}\n`);
279
+ fs.renameSync(temporaryPath, configPath);
280
+ } catch (error) {
281
+ fs.rmSync(temporaryPath, { force: true });
282
+ throw error;
283
+ }
284
+ }
285
+
286
+ async function seedStandardToolsAsync({
287
+ io,
288
+ packageRoot,
289
+ blunDir,
290
+ names,
291
+ platform = process.platform,
292
+ env = process.env,
293
+ }) {
294
+ const catalogue = readCatalogue(packageRoot);
295
+ if (!Array.isArray(names) || names.length === 0) {
296
+ throw new Error('Mindestens ein Standard-Tool muss ausdruecklich ausgewaehlt werden.');
297
+ }
298
+ const selectedNames = [...new Set(names)];
299
+ for (const name of selectedNames) {
300
+ const tool = catalogue.tools[name];
301
+ if (!isObject(tool) || tool.owner !== 'user-mcp') {
302
+ throw new Error(`Unbekanntes Standard-Tool: ${name}`);
303
+ }
304
+ if (Array.isArray(tool.platforms) && !tool.platforms.includes(platform)) {
305
+ throw new Error(`Standard-Tool ist auf dieser Plattform nicht verfuegbar: ${name}`);
306
+ }
307
+ }
308
+ const configPath = path.join(blunDir, 'mcp.json');
309
+ await io.ensurePrivateDirectory(blunDir);
310
+ if (fs.existsSync(configPath)) await io.securePrivateFile(configPath);
311
+ const document = readMcpDocument(configPath);
312
+ const servers = { ...document.mcpServers };
313
+ const added = [];
314
+ const updated = [];
315
+
316
+ for (const name of selectedNames) {
317
+ const tool = catalogue.tools[name];
318
+ const expected = bundledToolConfig(name, tool, {
319
+ packageRoot,
320
+ blunDir,
321
+ platform,
322
+ env,
323
+ });
324
+ if (Object.hasOwn(servers, name)) {
325
+ if (migrateBundledTool(name, servers[name], expected)) updated.push(name);
326
+ continue;
327
+ }
328
+ if (hasEquivalentServer(servers, name, tool)) continue;
329
+ servers[name] = expected;
330
+ added.push(name);
331
+ }
332
+
333
+ if (added.length > 0 || updated.length > 0) {
334
+ await writeMcpDocumentAsync(configPath, { ...document, mcpServers: servers }, io);
335
+ }
336
+ return { added, updated, configPath };
337
+ }
338
+
339
+ async function seedStandardDesignSkillAsync({ packageRoot, blunDir, io }) {
340
+ const sourcePath = path.join(
341
+ packageRoot,
342
+ 'standard-skills',
343
+ 'blun-app-design-system',
344
+ );
345
+ const sourceStat = fs.lstatSync(sourcePath);
346
+ if (!sourceStat.isDirectory() || sourceStat.isSymbolicLink()) {
347
+ throw new Error(`Ungueltiger BLUN-Standard-Skill: ${sourcePath}`);
348
+ }
349
+
350
+ const skillsDir = path.join(blunDir, 'skills');
351
+ await io.ensurePrivateDirectory(skillsDir);
352
+ const destinationPath = path.join(skillsDir, 'blun-app-design-system');
353
+ const installed = !fs.existsSync(destinationPath);
354
+ if (!installed) {
355
+ const destinationStat = fs.lstatSync(destinationPath);
356
+ if (!destinationStat.isDirectory() || destinationStat.isSymbolicLink()) {
357
+ throw new Error(`Ungueltiges Ziel fuer BLUN-Standard-Skill: ${destinationPath}`);
358
+ }
359
+ } else {
360
+ await io.ensurePrivateDirectory(destinationPath);
361
+ }
362
+
363
+ await io.copyPayload(sourcePath,destinationPath,{replace:true});
364
+ return { installed, updated: !installed, destinationPath };
365
+ }
366
+
272
367
  module.exports = {
368
+ seedStandardToolsAsync,
369
+ seedStandardDesignSkillAsync,
273
370
  availableStandardToolNames,
274
371
  readCatalogue,
275
372
  seedStandardDesignSkill,
@@ -0,0 +1,306 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { spawn } = require('node:child_process');
5
+ const os = require('node:os');
6
+ const { randomUUID } = require('node:crypto');
7
+ const { createInterface } = require('node:readline');
8
+
9
+ // One asynchronous host and one native compilation for the complete preparation.
10
+ // No startup tree propagation, no persistent "verified" cache, no unverified timeout pass.
11
+ const SCRIPT = String.raw`
12
+ [Console]::InputEncoding=[Text.UTF8Encoding]::new($false)
13
+ [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
14
+
15
+ $ErrorActionPreference='Stop'
16
+ $ProgressPreference='SilentlyContinue'
17
+ $phase='TEMP_PATH'
18
+ try {
19
+ Set-StrictMode -Version 3
20
+ $target=$env:BLUN_PRIVATE_TEMP_TARGET
21
+ $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User
22
+ $system=[Security.Principal.SecurityIdentifier]::new('S-1-5-18')
23
+ if ([IO.Path]::GetFullPath($target) -cne $target -or $target -notmatch '^[A-Za-z]:\\') { throw 'path' }
24
+ if ([IO.Directory]::Exists($target) -or [IO.File]::Exists($target)) { throw 'exists' }
25
+ $parent=[IO.Path]::GetDirectoryName($target)
26
+ if (-not [IO.Directory]::Exists($parent)) { throw 'parent' }
27
+ for ($ancestor=$parent; -not [string]::IsNullOrEmpty($ancestor); $ancestor=[IO.Path]::GetDirectoryName($ancestor)) {
28
+ if (([IO.File]::GetAttributes($ancestor) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
29
+ }
30
+ $acl=[Security.AccessControl.DirectorySecurity]::new()
31
+ $acl.SetOwner($sid)
32
+ $acl.SetAccessRuleProtection($true,$false)
33
+ $flags=[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'
34
+ $expected=@{}
35
+ $expected[$sid.Value]=$sid
36
+ $expected[$system.Value]=$system
37
+ foreach ($trustee in $expected.Values) {
38
+ $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($trustee,[Security.AccessControl.FileSystemRights]::FullControl,$flags,[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow))
39
+ }
40
+ $phase='TEMP_CREATE'
41
+ $directory=[IO.Directory]::CreateDirectory($target,$acl)
42
+ if (($directory.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
43
+ $phase='TEMP_ACL_VERIFICATION'
44
+ $actual=$directory.GetAccessControl([Security.AccessControl.AccessControlSections]'Owner,Access')
45
+ if (-not $actual.AreAccessRulesProtected -or $actual.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'owner' }
46
+ $rules=$actual.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])
47
+ if ($rules.Count -ne $expected.Count) { throw 'acl' }
48
+ $seen=@{}
49
+ foreach ($rule in $rules) {
50
+ $key=$rule.IdentityReference.Value
51
+ 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' }
52
+ $seen[$key]=$true
53
+ }
54
+ for ($ancestor=$target; -not [string]::IsNullOrEmpty($ancestor); $ancestor=[IO.Path]::GetDirectoryName($ancestor)) {
55
+ if (([IO.File]::GetAttributes($ancestor) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
56
+ }
57
+ $phase='TEMP_WRITE_PROBE'
58
+ $probe=[IO.Path]::Combine($target,[Guid]::NewGuid().ToString('N')+'.probe')
59
+ $handle=[IO.File]::Open($probe,[IO.FileMode]::CreateNew,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
60
+ try { $handle.WriteByte(0); $handle.Flush($true) } finally { $handle.Dispose() }
61
+ [IO.File]::Delete($probe)
62
+ $env:TEMP=$target
63
+ $env:TMP=$target
64
+ [Console]::Out.WriteLine('{"ready":true}')
65
+ if ([Console]::ReadLine() -cne 'BLUN_STARTUP_TEMP_ACK_V1') { throw 'ack' }
66
+ } catch {
67
+ [Console]::Error.Write(('BLUN_PRIVATE_TEMP_ERROR_V2:{0}' -f $phase))
68
+ exit 1
69
+ }
70
+ $ErrorActionPreference='Stop'
71
+ $ProgressPreference='SilentlyContinue'
72
+ try {
73
+ $bytes=[Convert]::FromBase64String($env:BLUN_STARTUP_NATIVE)
74
+ $mem=[IO.MemoryStream]::new($bytes)
75
+ $zip=[IO.Compression.GZipStream]::new($mem,[IO.Compression.CompressionMode]::Decompress)
76
+ $reader=[IO.StreamReader]::new($zip,[Text.Encoding]::UTF8)
77
+ try { $null=Add-Type -TypeDefinition $reader.ReadToEnd() -Language CSharp } finally { $reader.Dispose();$zip.Dispose();$mem.Dispose();[Array]::Clear($bytes,0,$bytes.Length) }
78
+ $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value
79
+ while ($null -ne ($line=[Console]::ReadLine())) {
80
+ $request=$line | ConvertFrom-Json
81
+ $frame=$null
82
+ try {
83
+ [BlunPrivateAclNative]::Warnings.Clear()
84
+ [BlunPrivateAclNative]::Repaired.Clear()
85
+ [BlunPrivateAclNative]::OutsideProfile.Clear()
86
+ [BlunPrivateAclNative]::StartupOwnerSid=$null
87
+ switch ($request.kind) {
88
+ 'directory' { [BlunPrivateAclNative]::InspectStartupDirectory($request.target,$sid) }
89
+ 'temp-verify' { [BlunPrivateAclNative]::InspectStartupDirectory($request.target,$sid,$false);if ([BlunPrivateAclNative]::Warnings.Count -ne 0) { throw 'temp-acl' } }
90
+ 'file' { [BlunPrivateAclNative]::HardenExisting($request.target,$sid,$false) }
91
+ 'file-write' {
92
+ $frame=[Convert]::FromBase64String($request.frame)
93
+ [BlunPrivateAclNative]::WritePrivateFile($request.target,$sid,$frame)
94
+ }
95
+ default { throw 'Invalid startup operation' }
96
+ }
97
+ $result=@{ id=$request.id;ok=$true;directoryDaclWrites=[BlunPrivateAclNative]::DirectoryDaclWrites;warnings=@([BlunPrivateAclNative]::Warnings);repaired=@([BlunPrivateAclNative]::Repaired);outsideProfile=@([BlunPrivateAclNative]::OutsideProfile) }
98
+ } catch {
99
+ $nativeCode=0;$reason='unknown';$failure=$_.Exception
100
+ for($depth=0;$depth -lt 8 -and $null -ne $failure;$depth++) {
101
+ if($failure -is [ComponentModel.Win32Exception]){$nativeCode=$failure.NativeErrorCode;$reason='native-error';break}
102
+ if($failure -is [UnauthorizedAccessException]){$reason='access-denied';break}
103
+ if($failure -is [IO.IOException]){$reason='io-error';break}
104
+ if($failure -is [ArgumentException]){$reason='argument-error';break}
105
+ $failure=$failure.InnerException
106
+ }
107
+ $result=@{ id=$request.id;ok=$false;phase=[BlunPrivateAclNative]::CurrentPhase;target=[BlunPrivateAclNative]::CurrentTarget;nativeErrorCode=$nativeCode;reason=$reason;sid=$sid;ownerSid=[BlunPrivateAclNative]::StartupOwnerSid }
108
+ } finally { if ($null -ne $frame) { [Array]::Clear($frame,0,$frame.Length) } }
109
+ [Console]::Out.WriteLine(($result | ConvertTo-Json -Compress -Depth 5))
110
+ }
111
+ } catch { [Console]::Error.Write('BLUN_STARTUP_HOST_FAILED');exit 1 }
112
+ `;
113
+ function createStartupSecurity(options) {
114
+ const windows = (options.platform || process.platform) === 'win32';
115
+ const counters = { powershell: 0, requests: 0, rootDaclWrites: 0 };
116
+ let child, lines, pending, timer, activeSince, fatal, serial = 0, closed = false, ready, resolveReady, rejectReady, tempIdentity;
117
+ const tempPath=path.join(options.tempRoot || os.tmpdir(), `blun-startup-${process.pid}-${randomUUID()}`);
118
+ let remainingMs=options.budgetMs ?? 10000;
119
+ const warned = new Set();
120
+ let budgetWarned=false;
121
+ const warning=(code,target)=>(options.onWarning || (w=>process.emitWarning(w.message,{code:w.code})))(error(code,target));
122
+ function fail(error) {
123
+ fatal ||= error;
124
+ rejectReady?.(fatal);
125
+ if (pending) { const p=pending;pending=undefined;p.reject(fatal); }
126
+ child?.kill();
127
+ }
128
+ function error(code, target) { return Object.assign(new Error(`[${code}]${target ? ' '+target : ''}`),{code,privatePath:target}); }
129
+ function start() {
130
+ if (child) return;
131
+
132
+ ready=new Promise((resolve,reject)=>{resolveReady=resolve;rejectReady=reject});
133
+ const systemRoot = path.win32.dirname(options.systemDirectory);
134
+ child = (options.spawnImpl || spawn)(path.win32.join(options.systemDirectory,'WindowsPowerShell','v1.0','powershell.exe'),
135
+ ['-NoLogo','-NoProfile','-NonInteractive','-EncodedCommand',Buffer.from(SCRIPT,'utf16le').toString('base64')],
136
+ { shell:false,windowsHide:true,stdio:['pipe','pipe','pipe'],env:{SystemRoot:systemRoot,WINDIR:systemRoot,BLUN_STARTUP_NATIVE:options.nativeCode,BLUN_PRIVATE_TEMP_TARGET:tempPath,USERPROFILE:process.env.USERPROFILE} });
137
+ counters.powershell++;
138
+
139
+ child.once('error',()=>fail(error('BLUN_STARTUP_SECURITY_HOST')));
140
+ child.once('exit',(code)=>{ if (!closed || pending || code) fail(error('BLUN_STARTUP_SECURITY_HOST')); });
141
+ child.stdin.on('error',()=>fail(error('BLUN_STARTUP_SECURITY_HOST')));
142
+ child.stderr.on('data',()=>{ /* Never expose native/raw secret-bearing diagnostics. */ });
143
+ lines=createInterface({input:child.stdout});
144
+ lines.on('line',line=>{
145
+ if (Buffer.byteLength(line)>65536) return fail(error('BLUN_STARTUP_SECURITY_PROTOCOL'));
146
+ let value;try {value=JSON.parse(line)}catch {return fail(error('BLUN_STARTUP_SECURITY_PROTOCOL'))}
147
+ if (value.ready===true && !tempIdentity && Object.keys(value).length===1) {
148
+ try {tempIdentity=checkedTemp();child.stdin.write('BLUN_STARTUP_TEMP_ACK_V1\n');resolveReady();}catch(e){fail(e)}
149
+ return;
150
+ }
151
+ if (!pending || value.id!==pending.id || typeof value.ok!=='boolean' || (value.ok && (!Array.isArray(value.warnings) || !Number.isSafeInteger(value.directoryDaclWrites) || value.directoryDaclWrites<0))) return fail(error('BLUN_STARTUP_SECURITY_PROTOCOL'));
152
+ clearTimeout(timer);remainingMs-=Date.now()-activeSince;
153
+ if (!budgetWarned && (options.budgetMs ?? 10000)-remainingMs >= (options.warnMs ?? 4500)) {budgetWarned=true;warning("BLUN_STARTUP_SECURITY_SLOW",pending.target);}
154
+ const p=pending;pending=undefined;
155
+ if (value.ok) counters.rootDaclWrites=value.directoryDaclWrites;
156
+ if (!value.ok) {
157
+ let e=error('BLUN_STARTUP_SECURITY_REJECTED',p.target);
158
+ if(options.allowedPhases.has(value.phase) && typeof value.target==='string'
159
+ && path.resolve(value.target).toLowerCase()===path.resolve(p.target).toLowerCase()
160
+ && Number.isInteger(value.nativeErrorCode) && value.nativeErrorCode>=0 && value.nativeErrorCode<=65535
161
+ && ['unknown','native-error','access-denied','io-error','argument-error'].includes(value.reason)) {
162
+ e=options.nativeError(value.phase,p.target,p.kind,value.nativeErrorCode,value.reason);
163
+ if(value.phase==='owner-verification' && p.kind==='directory' && value.reason==='access-denied') {
164
+ const owner=value.ownerSid==='S-1-5-18'?'SYSTEM':value.ownerSid==='S-1-5-32-544'?'Administratoren':'einem anderen Benutzer';
165
+ e.nextStep=`takeown /f "${p.target}"`;
166
+ e.message=`[${e.code}] Der Ordner "${p.target}" gehört ${owner}, nicht dem aktuellen Benutzer. Es wurde nichts geändert. In einem erhöhten Terminal ${e.nextStep} ausführen ODER den Ordner umbenennen und neu starten.`;
167
+ }
168
+ if(value.phase==='owner-takeover' && /^S-[0-9]+-[0-9]+(?:-[0-9]+)+$/.test(value.sid)) {
169
+ e.requiredAccess='WRITE_OWNER';e.nextStep=`icacls "${p.target}" /setowner *${value.sid}`;
170
+ e.message=`[${e.code}] ${p.target}; WRITE_OWNER; ${e.nextStep}`;
171
+ }
172
+ }
173
+ fatal=e;p.reject(e);child.kill();return;
174
+ }
175
+ if (!Array.isArray(value.repaired)) {p.reject(error('BLUN_STARTUP_SECURITY_PROTOCOL'));return fail(error('BLUN_STARTUP_SECURITY_PROTOCOL'));}
176
+ if (value.outsideProfile !== undefined && !Array.isArray(value.outsideProfile)) {p.reject(error('BLUN_STARTUP_SECURITY_PROTOCOL'));return fail(error('BLUN_STARTUP_SECURITY_PROTOCOL'));}
177
+ for (const outside of value.outsideProfile || []) {
178
+ if (typeof outside!=='string' || path.resolve(outside).toLowerCase()!==path.resolve(p.target).toLowerCase() || p.kind!=='directory') {p.reject(error('BLUN_STARTUP_SECURITY_PROTOCOL'));return fail(error('BLUN_STARTUP_SECURITY_PROTOCOL'));}
179
+ const key=path.resolve(outside).toLowerCase();
180
+ if(!warned.has(key)) {
181
+ warned.add(key);
182
+ const w=error('BLUN_STARTUP_ROOT_ACL_NOT_REPAIRED_OUTSIDE_PROFILE',outside);
183
+ w.message+=`; Außerhalb von %USERPROFILE%\\.blun wird die Ordner-DACL nicht repariert. Der Start wird bei Benutzerbesitz fortgesetzt.`;
184
+ (options.onWarning || (w=>process.emitWarning(w.message,{code:w.code})))(w);
185
+ }
186
+ }
187
+ for (const repaired of value.repaired) {
188
+ if (typeof repaired!=='string' || path.resolve(repaired).toLowerCase()!==path.resolve(p.target).toLowerCase() || p.kind!=='directory') {p.reject(error('BLUN_STARTUP_SECURITY_PROTOCOL'));return fail(error('BLUN_STARTUP_SECURITY_PROTOCOL'));}
189
+ const key=path.resolve(repaired).toLowerCase();
190
+ if(!warned.has(key)){warned.add(key);warning('BLUN_STARTUP_ROOT_ACL_REPAIRED',repaired);}
191
+ }
192
+ for (const warning of value.warnings) {
193
+ if (typeof warning!=='string' || path.resolve(warning).toLowerCase()!==path.resolve(p.target).toLowerCase() || p.kind!=='directory') {p.reject(error('BLUN_STARTUP_SECURITY_PROTOCOL'));return fail(error('BLUN_STARTUP_SECURITY_PROTOCOL'));}
194
+ const key=path.resolve(warning).toLowerCase();
195
+ if (!warned.has(key)) {warned.add(key);(options.onWarning || (w=>process.emitWarning(w.message,{code:w.code})))(error('BLUN_STARTUP_ROOT_ACL_WARNING',warning));}
196
+ }
197
+ p.resolve();
198
+ });
199
+ }
200
+ async function request(target,kind,contents) {
201
+ if (closed) throw error('BLUN_STARTUP_SECURITY_CLOSED');
202
+ if (fatal) throw fatal;
203
+ target=options.resolveTarget(target);
204
+ if (path.resolve(target)===path.parse(target).root) throw error('BLUN_PRIVATE_ACL_TARGET_VALIDATION',target);
205
+ if (!windows) {return options.posix[kind==='directory'?'ensurePrivateDirectory':kind==='file'?'securePrivateFile':'writePrivateFile'](target,contents);}
206
+ if (pending) throw error('BLUN_STARTUP_SECURITY_CONCURRENT');
207
+ activeSince=Date.now();
208
+ start();
209
+ timer=setTimeout(()=>fail(error('BLUN_STARTUP_SECURITY_TIMEOUT_UNVERIFIED',target)),Math.max(1,remainingMs));
210
+ if (remainingMs<=0) {fail(error('BLUN_STARTUP_SECURITY_TIMEOUT_UNVERIFIED',target));throw fatal;}
211
+ await ready;
212
+ if(fatal) throw fatal;
213
+ const message={id:++serial,kind,target};let frame,payload;
214
+ try {
215
+ if (kind==='file-write') {payload=Buffer.from(contents);frame=Buffer.alloc(8+payload.length);frame.writeBigUInt64LE(BigInt(payload.length));payload.copy(frame,8);message.frame=frame.toString('base64');}
216
+ counters.requests++;
217
+ await new Promise((resolve,reject)=>{pending={id:message.id,kind,target,resolve,reject};child.stdin.write(JSON.stringify(message)+'\n');});
218
+ } finally {frame?.fill(0);payload?.fill(0);message.frame=undefined;}
219
+ }
220
+ function checkedTemp() {
221
+ const stat=fs.lstatSync(tempPath,{bigint:true});
222
+ if (!stat.isDirectory() || stat.isSymbolicLink()
223
+ || path.resolve(fs.realpathSync(tempPath)).toLowerCase()!==path.resolve(tempPath).toLowerCase()
224
+ || (tempIdentity && (stat.dev!==tempIdentity.dev || stat.ino!==tempIdentity.ino))) throw error('BLUN_STARTUP_TEMP_IDENTITY');
225
+ return stat;
226
+ }
227
+ function cleanupTemp() {
228
+ checkedTemp();
229
+ const plan=[];
230
+ function visit(current,depth=0) {
231
+ if(plan.length>=4096 || depth>64) throw error('BLUN_STARTUP_TEMP_LIMIT');
232
+ const stat=fs.lstatSync(current,{bigint:true});
233
+ if(stat.isSymbolicLink() || (!stat.isDirectory() && (!stat.isFile() || stat.nlink!==1n))) throw error('BLUN_STARTUP_TEMP_IDENTITY');
234
+ plan.push({current,stat});
235
+ if(stat.isDirectory()) for(const name of fs.readdirSync(current)) visit(path.join(current,name),depth+1);
236
+ }
237
+ visit(tempPath);
238
+ for(const {current,stat} of plan.reverse()) {
239
+ checkedTemp();
240
+ const now=fs.lstatSync(current,{bigint:true});
241
+ if(now.dev!==stat.dev || now.ino!==stat.ino || now.isSymbolicLink() || (!now.isDirectory() && now.nlink!==1n)) throw error('BLUN_STARTUP_TEMP_IDENTITY');
242
+ if(now.isDirectory()) fs.rmdirSync(current);else fs.unlinkSync(current);
243
+ }
244
+ }
245
+ const api={
246
+ counters,
247
+ ensurePrivateDirectory:target=>request(target,'directory'),
248
+ securePrivateFile:target=>request(target,'file'),
249
+ writePrivateFile:(target,content)=>request(target,'file-write',content),
250
+ async copyPayload(source,target,{replace=false}={}) {
251
+ let count=0;
252
+ async function visit(s,t,depth=0) {
253
+ if(++count>4096 || depth>64) throw error('BLUN_STARTUP_PAYLOAD_LIMIT',t);
254
+ const before=fs.lstatSync(s);
255
+ if(before.isSymbolicLink()) throw error('BLUN_STARTUP_PAYLOAD_LINK',s);
256
+ if(before.isDirectory()) {
257
+ await api.ensurePrivateDirectory(t);
258
+ for(const name of fs.readdirSync(s)) await visit(path.join(s,name),path.join(t,name),depth+1);
259
+ } else if(before.isFile() && before.nlink===1) {
260
+ const data=fs.readFileSync(s),after=fs.lstatSync(s);
261
+ if(before.dev!==after.dev || before.ino!==after.ino || after.isSymbolicLink() || after.nlink!==1) throw error('BLUN_STARTUP_PAYLOAD_IDENTITY',s);
262
+ if(replace && fs.existsSync(t)) {
263
+ await api.securePrivateFile(t);
264
+ if(fs.readFileSync(t).equals(data)) return;
265
+ const temporary=path.join(path.dirname(t),`.${path.basename(t)}-${process.pid}-${randomUUID()}.tmp`);
266
+ try {await api.writePrivateFile(temporary,data);fs.renameSync(temporary,t);}
267
+ finally {if(fs.existsSync(temporary))fs.unlinkSync(temporary);data.fill(0);}
268
+ } else {try{await api.writePrivateFile(t,data)}finally{data.fill(0)}}
269
+ } else throw error('BLUN_STARTUP_PAYLOAD_TYPE',s);
270
+ }
271
+ await visit(source,target);
272
+ },
273
+ async securePayload(source,target) {
274
+ // Enumerate the bounded shipped input, never the user's history or extras.
275
+ let entries=0;
276
+ async function visit(s,t,depth) {
277
+ if (++entries>4096 || depth>64) throw error('BLUN_STARTUP_PAYLOAD_LIMIT',t);
278
+ const stat=fs.lstatSync(s);
279
+ if (stat.isSymbolicLink()) throw error('BLUN_STARTUP_PAYLOAD_LINK',s);
280
+ if (stat.isDirectory()) {await api.ensurePrivateDirectory(t);for(const name of fs.readdirSync(s)) await visit(path.join(s,name),path.join(t,name),depth+1);}
281
+ else if (stat.isFile() && stat.nlink===1) await api.securePrivateFile(t);
282
+ else throw error('BLUN_STARTUP_PAYLOAD_TYPE',s);
283
+ }
284
+ await visit(source,target,0);
285
+ },
286
+ async close() {
287
+ if (closed) return;
288
+ let clean=false;
289
+ // Recheck the same temporary object while the existing host is alive.
290
+ // A failed security check leaves evidence intact; never delete by guess.
291
+ if(child && tempIdentity && !fatal && !pending) {
292
+ try {checkedTemp();await request(tempPath,'temp-verify');checkedTemp();clean=true;}
293
+ catch(e) {fatal ||= e;}
294
+ }
295
+ closed=true;clearTimeout(timer);
296
+ if (pending) fail(error('BLUN_STARTUP_SECURITY_UNFINISHED'));
297
+ if (!child) return;
298
+ lines?.close();child.stdin.end();
299
+ await new Promise(resolve=>{if(child.exitCode!==null || child.signalCode!==null)return resolve();const stop=setTimeout(()=>{child.kill();resolve()},500);child.once('exit',()=>{clearTimeout(stop);resolve()});});
300
+ if(clean) cleanupTemp();
301
+ if(fatal) throw fatal;
302
+ },
303
+ };
304
+ return api;
305
+ }
306
+ module.exports={createStartupSecurity};