@tempad-dev/mcp 1.0.4 → 1.0.5
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/README.md +5 -1
- package/README.zh-Hans.md +3 -1
- package/dist/{acquire-BtKFZ9Lz.mjs → acquire-C1v5UQB2.mjs} +1 -1
- package/dist/{acquire-DHwsqq0j.mjs → acquire-DK4Fg36-.mjs} +4 -4
- package/dist/{acquire-DHwsqq0j.mjs.map → acquire-DK4Fg36-.mjs.map} +1 -1
- package/dist/{bootstrap-B9-RyWlM.mjs → bootstrap-CNJpiOAm.mjs} +7 -7
- package/dist/{bootstrap-B9-RyWlM.mjs.map → bootstrap-CNJpiOAm.mjs.map} +1 -1
- package/dist/cli.mjs +4 -4
- package/dist/{cold-start-DOy9JsIQ.mjs → cold-start-BOLlW_0n.mjs} +4 -4
- package/dist/{cold-start-DOy9JsIQ.mjs.map → cold-start-BOLlW_0n.mjs.map} +1 -1
- package/dist/{cold-start-U3cW0q9T.mjs → cold-start-DeFnhN3x.mjs} +1 -1
- package/dist/{edge-CHzaTUFt.mjs → edge-DP-CwLYS.mjs} +1 -1
- package/dist/{edge-BUf7gs4J.mjs → edge-m9VuTeju.mjs} +5 -5
- package/dist/{edge-BUf7gs4J.mjs.map → edge-m9VuTeju.mjs.map} +1 -1
- package/dist/{hub-runtime-DsEO9zvX.mjs → hub-runtime-BBnfo1yd.mjs} +50 -26
- package/dist/hub-runtime-BBnfo1yd.mjs.map +1 -0
- package/dist/{hub-runtime-DjdqIgGl.mjs → hub-runtime-U3Set0EC.mjs} +1 -1
- package/dist/hub.mjs +2 -2
- package/dist/managed-runtime.mjs +10 -10
- package/dist/{probe-BeWkMbzQ.mjs → probe-CqjOWdnP.mjs} +4 -4
- package/dist/{probe-BeWkMbzQ.mjs.map → probe-CqjOWdnP.mjs.map} +1 -1
- package/dist/{processes-CBoalzSk.mjs → processes-BnvaDi81.mjs} +1 -1
- package/dist/{processes-BCCE8As7.mjs → processes-DOmrri5n.mjs} +6 -6
- package/dist/{processes-BCCE8As7.mjs.map → processes-DOmrri5n.mjs.map} +1 -1
- package/dist/runtime-installer.mjs +3 -3
- package/dist/runtime-manifest.json +49 -49
- package/dist/{runtime-platform-C-Yk9F3L.mjs → runtime-platform-CpunJOI4.mjs} +143 -43
- package/dist/runtime-platform-CpunJOI4.mjs.map +1 -0
- package/dist/runtime-verification.mjs +3 -3
- package/dist/{shared--othnF1c.mjs → shared-8_j_xlsJ.mjs} +8 -5
- package/dist/{shared--othnF1c.mjs.map → shared-8_j_xlsJ.mjs.map} +1 -1
- package/dist/{shared-S0dtOYq8.mjs → shared-Bvmw_Pv0.mjs} +1 -1
- package/dist/{startup-log-CYlFgdy5.mjs → startup-log-BI24ryBR.mjs} +2 -2
- package/dist/{startup-log-CYlFgdy5.mjs.map → startup-log-BI24ryBR.mjs.map} +1 -1
- package/dist/{startup-log-DqK2uwBd.mjs → startup-log-isQ9Wv18.mjs} +1 -1
- package/dist/{state-6qFcvi-I.mjs → state-4Dz7r-_n.mjs} +2 -2
- package/dist/{state-6qFcvi-I.mjs.map → state-4Dz7r-_n.mjs.map} +1 -1
- package/dist/{state-BrWBtYNG.mjs → state-DDpxeTVd.mjs} +1 -1
- package/dist/{supervisor-CesT-H5_.mjs → supervisor-Cu-xRt1k.mjs} +7 -7
- package/dist/{supervisor-CesT-H5_.mjs.map → supervisor-Cu-xRt1k.mjs.map} +1 -1
- package/dist/{task-storage-recovery-I9lpYYX6.mjs → task-storage-recovery-fSo2eskS.mjs} +2 -2
- package/dist/{task-storage-recovery-I9lpYYX6.mjs.map → task-storage-recovery-fSo2eskS.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/hub-runtime-DsEO9zvX.mjs.map +0 -1
- package/dist/runtime-platform-C-Yk9F3L.mjs.map +0 -1
|
@@ -75,7 +75,7 @@ async function assertPrivatePathAsync(path, kind) {
|
|
|
75
75
|
if (!state) return;
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
|
-
function ensurePrivateDirectory(path) {
|
|
78
|
+
function ensurePrivateDirectory(path, { recoverLegacyRoot = false } = {}) {
|
|
79
79
|
if (!isAbsolute(path)) throw new Error("Runtime directory must be absolute.");
|
|
80
80
|
if (process.platform !== "win32") {
|
|
81
81
|
mkdirSync(path, {
|
|
@@ -87,10 +87,23 @@ function ensurePrivateDirectory(path) {
|
|
|
87
87
|
}
|
|
88
88
|
try {
|
|
89
89
|
assertPrivatePath(path, "directory");
|
|
90
|
+
return;
|
|
90
91
|
} catch (error) {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
92
|
+
const code = error.code;
|
|
93
|
+
if (recoverLegacyRoot && code === "EINHERITEDACL") retireLegacyDirectory(path);
|
|
94
|
+
else if (code !== "ENOENT") throw error;
|
|
95
|
+
}
|
|
96
|
+
windowsSecurity("ensure", path, "directory");
|
|
97
|
+
if (recoverLegacyRoot) assertPrivatePath(path, "directory");
|
|
98
|
+
else rememberPermissions(path, inspectPath(path, "directory"));
|
|
99
|
+
}
|
|
100
|
+
function retireLegacyDirectory(path) {
|
|
101
|
+
try {
|
|
102
|
+
windowsSecurity("retire", path, "directory");
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
const code = cause.code;
|
|
105
|
+
if (code === "ENOENT" || code === "EBUSY") return;
|
|
106
|
+
throw new Error(`Cannot recover ${path}. Stop all TemPad MCP clients, rename the old directory, and restart. ${String(cause)}`, { cause });
|
|
94
107
|
}
|
|
95
108
|
}
|
|
96
109
|
async function ensurePrivateDirectoryAsync(path) {
|
|
@@ -133,7 +146,7 @@ function securityCommand(action, path, kind) {
|
|
|
133
146
|
"-NoProfile",
|
|
134
147
|
"-NonInteractive",
|
|
135
148
|
"-EncodedCommand",
|
|
136
|
-
Buffer.from(
|
|
149
|
+
Buffer.from(securityScript(action), "utf16le").toString("base64")
|
|
137
150
|
],
|
|
138
151
|
options: {
|
|
139
152
|
encoding: "utf8",
|
|
@@ -163,7 +176,7 @@ function windowsSecurity(action, path, kind) {
|
|
|
163
176
|
]
|
|
164
177
|
});
|
|
165
178
|
} catch (cause) {
|
|
166
|
-
throw securityFailure(cause, path, kind);
|
|
179
|
+
throw securityFailure(cause, path, kind, action);
|
|
167
180
|
}
|
|
168
181
|
}
|
|
169
182
|
async function windowsSecurityAsync(action, path, kind, signal) {
|
|
@@ -176,12 +189,12 @@ async function windowsSecurityAsync(action, path, kind, signal) {
|
|
|
176
189
|
if (error) reject(securityFailure(Object.assign(error, {
|
|
177
190
|
stdout,
|
|
178
191
|
stderr
|
|
179
|
-
}), path, kind));
|
|
192
|
+
}), path, kind, action));
|
|
180
193
|
else resolve();
|
|
181
194
|
}).stdin?.end();
|
|
182
195
|
});
|
|
183
196
|
}
|
|
184
|
-
function securityFailure(cause, path, kind) {
|
|
197
|
+
function securityFailure(cause, path, kind, action) {
|
|
185
198
|
const error = cause;
|
|
186
199
|
const detail = [error.stdout, error.stderr].filter(Boolean).join("\n").trim();
|
|
187
200
|
let code;
|
|
@@ -193,34 +206,57 @@ function securityFailure(cause, path, kind) {
|
|
|
193
206
|
} catch {}
|
|
194
207
|
const failure = new Error(`Refusing untrusted Windows runtime ${kind}: ${path}${detail ? ` (${detail})` : ""}`, { cause });
|
|
195
208
|
if (code === 2 || code === 3) failure.code = "ENOENT";
|
|
196
|
-
if (code === 231) failure.code = "EBUSY";
|
|
209
|
+
if (code === 231 || action === "retire" && code === 32) failure.code = "EBUSY";
|
|
197
210
|
if (code === "EPIPEUNPROTECTED") failure.code = code;
|
|
211
|
+
if (kind === "directory" && code === "EINHERITEDACL") failure.code = code;
|
|
198
212
|
if (!failure.code && kind === "pipe" && reportedFailure) failure.code = "EPIPEUNTRUSTED";
|
|
199
213
|
return failure;
|
|
200
214
|
}
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
|
|
205
|
-
# Module autoload can stall with a filtered host environment. Use the trusted
|
|
206
|
-
# built-in modules directly, without scanning host/user module locations.
|
|
207
|
-
Import-Module "$PSHOME\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1" -ErrorAction Stop
|
|
208
|
-
Import-Module "$PSHOME\Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1" -ErrorAction Stop
|
|
209
|
-
$PSModuleAutoloadingPreference = 'None'
|
|
210
|
-
$failureCode = $null
|
|
211
|
-
try {
|
|
212
|
-
$request = $env:TEMPAD_RUNTIME_ACL_REQUEST | ConvertFrom-Json
|
|
213
|
-
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
214
|
-
$allowed = @($user.Value, 'S-1-5-18', 'S-1-5-32-544')
|
|
215
|
-
if ($request.kind -eq 'pipe') {
|
|
216
|
-
Add-Type -TypeDefinition @'
|
|
217
|
-
using System;
|
|
218
|
-
using System.ComponentModel;
|
|
219
|
-
using System.Runtime.InteropServices;
|
|
220
|
-
using Microsoft.Win32.SafeHandles;
|
|
221
|
-
public static class TempadPipeSecurity {
|
|
215
|
+
const DIRECTORY_RECOVERY_METHODS = String.raw`
|
|
216
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
217
|
+
static extern bool SetFileInformationByHandle(SafeFileHandle handle, int kind, byte[] info, uint size);
|
|
222
218
|
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
223
|
-
static extern
|
|
219
|
+
static extern uint GetFinalPathNameByHandle(SafeFileHandle handle, System.Text.StringBuilder path, uint size, uint flags);
|
|
220
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
221
|
+
static extern uint GetLongPathName(string path, System.Text.StringBuilder expanded, uint size);
|
|
222
|
+
public static SafeFileHandle OpenLegacyDirectory(string path, bool retire) {
|
|
223
|
+
// FILE_READ_ATTRIBUTES, no share-delete, BACKUP_SEMANTICS | OPEN_REPARSE_POINT.
|
|
224
|
+
var handle = CreateFile(path, retire ? 0x10080u : 0x80u, 1, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero);
|
|
225
|
+
if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
226
|
+
try {
|
|
227
|
+
var final = new System.Text.StringBuilder(32768);
|
|
228
|
+
// Windows may supply an 8.3 profile name in TEMP. Expand only short names
|
|
229
|
+
// for the comparison; a junction still differs from the handle's final path.
|
|
230
|
+
var expanded = new System.Text.StringBuilder(32768);
|
|
231
|
+
uint length = GetLongPathName(path, expanded, (uint)expanded.Capacity);
|
|
232
|
+
uint count = GetFinalPathNameByHandle(handle, final, (uint)final.Capacity, 0);
|
|
233
|
+
if (length == 0 || length >= expanded.Capacity || count == 0 || count >= final.Capacity ||
|
|
234
|
+
!String.Equals(final.ToString(), @"\\?\" + expanded, StringComparison.OrdinalIgnoreCase) ||
|
|
235
|
+
(System.IO.File.GetAttributes(path) & (System.IO.FileAttributes.Directory | System.IO.FileAttributes.ReparsePoint)) != System.IO.FileAttributes.Directory)
|
|
236
|
+
throw new InvalidOperationException("Expected a canonical local runtime directory.");
|
|
237
|
+
return handle;
|
|
238
|
+
} catch { handle.Dispose(); throw; }
|
|
239
|
+
}
|
|
240
|
+
public static void Retire(SafeFileHandle handle, string path) {
|
|
241
|
+
foreach (string run in System.IO.Directory.GetFileSystemEntries(path, "run")) {
|
|
242
|
+
using (OpenLegacyDirectory(run, false)) {
|
|
243
|
+
foreach (string name in new[] { "hub.lock.lock", "mcp.lock.lock" }) {
|
|
244
|
+
if (System.IO.Directory.GetFileSystemEntries(run, name).Length != 0)
|
|
245
|
+
throw new InvalidOperationException("A runtime lock exists.");
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// FILE_RENAME_INFO with ReplaceIfExists=false and RootDirectory=NULL.
|
|
250
|
+
byte[] nameBytes = System.Text.Encoding.Unicode.GetBytes(path + ".legacy");
|
|
251
|
+
int lengthOffset = 2 * IntPtr.Size;
|
|
252
|
+
byte[] info = new byte[lengthOffset + 4 + nameBytes.Length + 2];
|
|
253
|
+
BitConverter.GetBytes(nameBytes.Length).CopyTo(info, lengthOffset);
|
|
254
|
+
nameBytes.CopyTo(info, lengthOffset + 4);
|
|
255
|
+
if (!SetFileInformationByHandle(handle, 3, info, (uint)info.Length))
|
|
256
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
257
|
+
}
|
|
258
|
+
`;
|
|
259
|
+
const PIPE_SECURITY_METHODS = String.raw`
|
|
224
260
|
[DllImport("advapi32.dll", SetLastError=true)]
|
|
225
261
|
static extern uint GetSecurityInfo(SafeFileHandle handle, uint type, uint info, out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr descriptor);
|
|
226
262
|
[DllImport("advapi32.dll", SetLastError=true)]
|
|
@@ -261,25 +297,71 @@ public static class TempadPipeSecurity {
|
|
|
261
297
|
} finally { LocalFree(descriptor); }
|
|
262
298
|
}
|
|
263
299
|
}
|
|
300
|
+
`;
|
|
301
|
+
function securityScript(action) {
|
|
302
|
+
return String.raw`
|
|
303
|
+
$ErrorActionPreference = 'Stop'
|
|
304
|
+
$ProgressPreference = 'SilentlyContinue'
|
|
305
|
+
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
|
|
306
|
+
# Module autoload can stall with a filtered host environment. Use the trusted
|
|
307
|
+
# built-in modules directly, without scanning host/user module locations.
|
|
308
|
+
Import-Module "$PSHOME\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1" -ErrorAction Stop
|
|
309
|
+
Import-Module "$PSHOME\Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1" -ErrorAction Stop
|
|
310
|
+
$PSModuleAutoloadingPreference = 'None'
|
|
311
|
+
$failureCode = $null
|
|
312
|
+
$legacy = $null
|
|
313
|
+
$compilerTemp = $null
|
|
314
|
+
function New-PrivateDirectory($path) {
|
|
315
|
+
$security = New-Object System.Security.AccessControl.DirectorySecurity
|
|
316
|
+
$security.SetOwner($user)
|
|
317
|
+
$security.SetAccessRuleProtection($true, $false)
|
|
318
|
+
foreach ($sid in $allowed) {
|
|
319
|
+
$principal = New-Object System.Security.Principal.SecurityIdentifier($sid)
|
|
320
|
+
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($principal, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
|
|
321
|
+
$security.AddAccessRule($rule)
|
|
322
|
+
}
|
|
323
|
+
[void][IO.Directory]::CreateDirectory($path, $security)
|
|
324
|
+
}
|
|
325
|
+
try {
|
|
326
|
+
$request = $env:TEMPAD_RUNTIME_ACL_REQUEST | ConvertFrom-Json
|
|
327
|
+
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
328
|
+
$allowed = @($user.Value, 'S-1-5-18', 'S-1-5-32-544')
|
|
329
|
+
if ($request.action -eq 'retire') {
|
|
330
|
+
# Windows PowerShell's Add-Type compiles via temporary files. Temp itself
|
|
331
|
+
# may be sandbox-writable in precisely the migration we are handling.
|
|
332
|
+
$local = [Environment]::GetFolderPath('LocalApplicationData')
|
|
333
|
+
if (![IO.Path]::IsPathRooted($local)) { throw 'Missing local application data directory.' }
|
|
334
|
+
$scratch = [IO.Path]::Combine($local, 'tempad-acl-' + [Guid]::NewGuid().ToString('N'))
|
|
335
|
+
New-PrivateDirectory $scratch
|
|
336
|
+
$compilerTemp = $scratch
|
|
337
|
+
$env:TMP = $env:TEMP = $scratch
|
|
338
|
+
}
|
|
339
|
+
if ($request.kind -eq 'pipe' -or $request.action -eq 'retire') {
|
|
340
|
+
Add-Type -TypeDefinition @'
|
|
341
|
+
using System;
|
|
342
|
+
using System.ComponentModel;
|
|
343
|
+
using System.Runtime.InteropServices;
|
|
344
|
+
using Microsoft.Win32.SafeHandles;
|
|
345
|
+
public static class TempadSecurity {
|
|
346
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
347
|
+
static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
|
|
348
|
+
${action === "retire" ? DIRECTORY_RECOVERY_METHODS : PIPE_SECURITY_METHODS}
|
|
264
349
|
}
|
|
265
350
|
'@
|
|
351
|
+
}
|
|
352
|
+
if ($request.kind -eq 'pipe') {
|
|
266
353
|
$sddl = $null
|
|
267
354
|
if ($request.action -eq 'protect') {
|
|
268
355
|
$sddl = 'D:P(D;;GA;;;NU)(A;;GA;;;' + $user.Value + ')(A;;GA;;;SY)(A;;GA;;;BA)'
|
|
269
356
|
}
|
|
270
|
-
$bytes = [
|
|
357
|
+
$bytes = [TempadSecurity]::Inspect($request.path, $sddl)
|
|
271
358
|
$descriptor = New-Object System.Security.AccessControl.RawSecurityDescriptor($bytes, 0)
|
|
272
359
|
} else {
|
|
360
|
+
if ($request.action -eq 'retire') {
|
|
361
|
+
$legacy = [TempadSecurity]::OpenLegacyDirectory($request.path, $true)
|
|
362
|
+
}
|
|
273
363
|
if ($request.action -eq 'ensure' -and ![IO.Directory]::Exists($request.path)) {
|
|
274
|
-
|
|
275
|
-
$security.SetOwner($user)
|
|
276
|
-
$security.SetAccessRuleProtection($true, $false)
|
|
277
|
-
foreach ($sid in $allowed) {
|
|
278
|
-
$principal = New-Object System.Security.Principal.SecurityIdentifier($sid)
|
|
279
|
-
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($principal, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
|
|
280
|
-
$security.AddAccessRule($rule)
|
|
281
|
-
}
|
|
282
|
-
[void][IO.Directory]::CreateDirectory($request.path, $security)
|
|
364
|
+
New-PrivateDirectory $request.path
|
|
283
365
|
}
|
|
284
366
|
try {
|
|
285
367
|
$acl = Get-Acl -LiteralPath $request.path
|
|
@@ -294,11 +376,13 @@ public static class TempadPipeSecurity {
|
|
|
294
376
|
}
|
|
295
377
|
$ownAccess = $false
|
|
296
378
|
$foreignAccess = $false
|
|
379
|
+
$inheritedOnly = $request.kind -eq 'directory' -and $descriptor.Owner.Value -eq $user.Value -and !$acl.AreAccessRulesProtected
|
|
297
380
|
$pendingProtection = $request.kind -eq 'pipe' -and $request.action -eq 'inspect'
|
|
298
381
|
foreach ($ace in $descriptor.DiscretionaryAcl) {
|
|
299
382
|
if ($ace.AceType -eq 'AccessAllowed') {
|
|
300
383
|
if ($allowed -notcontains $ace.SecurityIdentifier.Value) {
|
|
301
384
|
$foreignAccess = $true
|
|
385
|
+
if (!$ace.AceFlags.HasFlag([Security.AccessControl.AceFlags]::Inherited)) { $inheritedOnly = $false }
|
|
302
386
|
# Windows' initial pipe descriptor can be owned by Administrators and omit
|
|
303
387
|
# the user's ACE. Only its default reader grants are retryable, never trusted.
|
|
304
388
|
$defaultReader = @('S-1-1-0', 'S-1-5-7') -contains $ace.SecurityIdentifier.Value
|
|
@@ -306,13 +390,22 @@ public static class TempadPipeSecurity {
|
|
|
306
390
|
$pendingProtection = $pendingProtection -and $defaultReader -and $readOnly
|
|
307
391
|
}
|
|
308
392
|
if ($ace.SecurityIdentifier.Value -eq $user.Value) { $ownAccess = $true }
|
|
309
|
-
} elseif ($ace.AceType -
|
|
393
|
+
} elseif ($ace.AceType -eq 'AccessDenied') {
|
|
394
|
+
$inheritedOnly = $false
|
|
395
|
+
} else {
|
|
310
396
|
throw 'Unsupported ACL entry.'
|
|
311
397
|
}
|
|
312
398
|
}
|
|
313
399
|
if ($foreignAccess -and $pendingProtection) { $failureCode = 'EPIPEUNPROTECTED' }
|
|
314
400
|
if (!$ownAccess) { throw 'ACL does not explicitly grant the current user access.' }
|
|
315
401
|
if ($foreignAccess) {
|
|
402
|
+
if ($inheritedOnly -and $request.action -eq 'retire') {
|
|
403
|
+
# Tightening the old DACL cannot revoke open handles or authenticate existing files.
|
|
404
|
+
# Leave the entire tree untouched and recreate the private root at the enrolled path.
|
|
405
|
+
[TempadSecurity]::Retire($legacy, $request.path)
|
|
406
|
+
return
|
|
407
|
+
}
|
|
408
|
+
if ($inheritedOnly) { $failureCode = 'EINHERITEDACL' }
|
|
316
409
|
throw 'ACL grants another account access.'
|
|
317
410
|
}
|
|
318
411
|
} catch {
|
|
@@ -321,8 +414,15 @@ public static class TempadPipeSecurity {
|
|
|
321
414
|
if (!$failureCode) { $failureCode = $failure.NativeErrorCode }
|
|
322
415
|
[Console]::Error.WriteLine((@{ message = $failure.Message; code = $failureCode } | ConvertTo-Json -Compress))
|
|
323
416
|
exit 1
|
|
417
|
+
} finally {
|
|
418
|
+
if ($null -ne $legacy) { $legacy.Dispose() }
|
|
419
|
+
if ($null -ne $compilerTemp) {
|
|
420
|
+
# A scanner can still hold compiler output. Never let scratch cleanup undo a completed rename.
|
|
421
|
+
try { [IO.Directory]::Delete($compilerTemp, $true) } catch [IO.IOException] {}
|
|
422
|
+
}
|
|
324
423
|
}
|
|
325
424
|
`;
|
|
425
|
+
}
|
|
326
426
|
export { createPrivateTempDirectory as a, isPipe as c, cleanupEndpoint as i, protectPipeAsync as l, assertPrivatePath as n, ensurePrivateDirectory as o, assertPrivatePathAsync as r, ensurePrivateDirectoryAsync as s, assertPrivateEndpointAsync as t, runtimeEndpoint as u };
|
|
327
427
|
|
|
328
|
-
//# sourceMappingURL=runtime-platform-
|
|
428
|
+
//# sourceMappingURL=runtime-platform-CpunJOI4.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-platform-CpunJOI4.mjs","names":[],"sources":["../src/runtime-platform.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process'\nimport { createHash, randomUUID } from 'node:crypto'\nimport { lstatSync, mkdirSync, realpathSync, rmSync } from 'node:fs'\nimport { tmpdir, userInfo } from 'node:os'\nimport { isAbsolute, join, resolve } from 'node:path'\n\nconst PIPE_PREFIX = '\\\\\\\\.\\\\pipe\\\\'\nconst checkedPermissions = new Map<string, ReturnType<typeof inspectPath>>()\n\n/** Runtime overrides must isolate pipes as well as files, including on one Windows account. */\nexport function runtimeEndpoint(\n directory: string,\n name: string,\n platform: NodeJS.Platform = process.platform,\n user = userInfo().username\n) {\n if (platform !== 'win32') return join(directory, name)\n const identity = createHash('sha256')\n .update(user)\n .update('\\0')\n .update(directory.replaceAll('/', '\\\\').toLowerCase())\n .update('\\0')\n .update(name)\n .digest('hex')\n .slice(0, 32)\n return `${PIPE_PREFIX}tempad-runtime-${identity}`\n}\n\nexport function isPipe(path: string) {\n return path.startsWith(PIPE_PREFIX)\n}\n\nfunction canonical(path: string) {\n const actual = realpathSync(path)\n return process.platform === 'win32'\n ? actual.toLowerCase() === resolve(path).toLowerCase()\n : actual === path\n}\n\n/** Check real Windows ACLs; chmod and stat.mode do not establish Windows privacy. */\nfunction inspectPath(path: string, kind: 'file' | 'directory') {\n if (!isAbsolute(path)) throw new Error('Runtime path must be absolute.')\n const stat = lstatSync(path, { bigint: true })\n if (\n stat.isSymbolicLink() ||\n !(kind === 'file' ? stat.isFile() : stat.isDirectory()) ||\n !canonical(path) ||\n (process.platform !== 'win32' && (stat.uid !== BigInt(process.getuid!()) || stat.mode & 0o077n))\n )\n throw new Error(`Refusing untrusted runtime ${kind}: ${path}`)\n return {\n identity: `${stat.dev}:${stat.ino}:${stat.birthtimeNs}:${kind}`,\n revision: stat.ctimeNs\n }\n}\n\nfunction rememberPermissions(path: string, state: ReturnType<typeof inspectPath>) {\n if (checkedPermissions.size >= 1024) checkedPermissions.clear()\n checkedPermissions.set(path, state)\n}\n\nfunction uncheckedPath(path: string, kind: 'file' | 'directory') {\n const state = inspectPath(path, kind)\n if (process.platform !== 'win32') return\n const cached = checkedPermissions.get(path)\n if (cached?.identity === state.identity && cached.revision === state.revision) return\n checkedPermissions.delete(path)\n return state\n}\n\nfunction checkedPath(\n path: string,\n kind: 'file' | 'directory',\n state: ReturnType<typeof inspectPath>\n) {\n const next = inspectPath(path, kind)\n if (next.identity !== state.identity)\n throw Object.assign(new Error(`Runtime ${kind} changed during its permission check: ${path}`), {\n code: 'ERUNTIMEPATHCHANGED'\n })\n if (next.revision === state.revision) {\n rememberPermissions(path, next)\n return\n }\n return next\n}\n\nexport function assertPrivatePath(path: string, kind: 'file' | 'directory') {\n let state = uncheckedPath(path, kind)\n if (!state) return\n for (let attempt = 0; attempt < 2; attempt++) {\n windowsSecurity('inspect', path, kind)\n // ChangeTime covers ACL edits and ordinary child creation. Recheck once when it\n // changes, rejecting replacement but leaving an actively changing object uncached.\n state = checkedPath(path, kind, state)\n if (!state) return\n }\n}\n\n/** Serving processes must let control leases renew while Windows checks permissions. */\nexport async function assertPrivatePathAsync(path: string, kind: 'file' | 'directory') {\n let state = uncheckedPath(path, kind)\n if (!state) return\n for (let attempt = 0; attempt < 2; attempt++) {\n await windowsSecurityAsync('inspect', path, kind)\n state = checkedPath(path, kind, state)\n if (!state) return\n }\n}\n\nexport function ensurePrivateDirectory(path: string, { recoverLegacyRoot = false } = {}) {\n if (!isAbsolute(path)) throw new Error('Runtime directory must be absolute.')\n if (process.platform !== 'win32') {\n mkdirSync(path, { recursive: true, mode: 0o700 })\n assertPrivatePath(path, 'directory')\n return\n }\n try {\n assertPrivatePath(path, 'directory')\n return\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (recoverLegacyRoot && code === 'EINHERITEDACL') retireLegacyDirectory(path)\n else if (code !== 'ENOENT') throw error\n }\n windowsSecurity('ensure', path, 'directory')\n if (recoverLegacyRoot) assertPrivatePath(path, 'directory')\n else rememberPermissions(path, inspectPath(path, 'directory'))\n}\n\nfunction retireLegacyDirectory(path: string) {\n try {\n windowsSecurity('retire', path, 'directory')\n } catch (cause) {\n // Another launcher may already be replacing the root. Its successor still\n // has to pass ensurePrivateDirectory's independent ACL and identity checks.\n const code = (cause as NodeJS.ErrnoException).code\n if (code === 'ENOENT' || code === 'EBUSY') return\n throw new Error(\n `Cannot recover ${path}. Stop all TemPad MCP clients, rename the old directory, and restart. ${String(cause)}`,\n { cause }\n )\n }\n}\n\nexport async function ensurePrivateDirectoryAsync(path: string) {\n if (process.platform !== 'win32') return ensurePrivateDirectory(path)\n try {\n await assertPrivatePathAsync(path, 'directory')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await windowsSecurityAsync('ensure', path, 'directory')\n rememberPermissions(path, inspectPath(path, 'directory'))\n }\n}\n\nexport function createPrivateTempDirectory(prefix: string) {\n // macOS's per-user temp path leaves too little room for Unix socket names.\n const directory = process.platform === 'win32' ? tmpdir() : '/tmp'\n const path = join(realpathSync(directory), `${prefix}${randomUUID()}`)\n ensurePrivateDirectory(path)\n return path\n}\n\nexport function cleanupEndpoint(path: string) {\n if (!isPipe(path)) rmSync(path, { force: true })\n}\n\nexport function assertPrivateEndpoint(path: string) {\n if (!isPipe(path)) throw new Error('Expected a Windows runtime pipe.')\n windowsSecurity('inspect', path, 'pipe')\n}\n\nexport function protectPipe(path: string) {\n if (!isPipe(path)) throw new Error('Expected a Windows runtime pipe.')\n windowsSecurity('protect', path, 'pipe')\n}\n\nexport async function assertPrivateEndpointAsync(path: string, signal?: AbortSignal) {\n if (!isPipe(path)) throw new Error('Expected a Windows runtime pipe.')\n await windowsSecurityAsync('inspect', path, 'pipe', signal)\n}\n\nexport async function protectPipeAsync(path: string, signal?: AbortSignal) {\n if (!isPipe(path)) throw new Error('Expected a Windows runtime pipe.')\n await windowsSecurityAsync('protect', path, 'pipe', signal)\n}\n\nexport function windowsPowerShellEnvironment(env: NodeJS.ProcessEnv = process.env) {\n // PowerShell 7's module paths can load incompatible modules in Windows PowerShell 5.\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => key.toLowerCase() !== 'psmodulepath')\n )\n}\n\n// Built-in Windows PowerShell supplies the platform ACL API without an npm/native dependency.\n// JSON stays in a child-only environment value, never executable source or shell arguments.\n// Helper input is independent of host stdio and the Windows console's input code page.\ntype SecurityAction = 'ensure' | 'inspect' | 'protect' | 'retire'\n\nfunction securityCommand(action: SecurityAction, path: string, kind: string) {\n const systemRoot = process.env.SystemRoot\n if (!systemRoot || !isAbsolute(systemRoot))\n throw new Error('Windows SystemRoot is required to verify private runtime storage.')\n return {\n file: join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),\n args: [\n '-NoLogo',\n '-NoProfile',\n '-NonInteractive',\n '-EncodedCommand',\n Buffer.from(securityScript(action), 'utf16le').toString('base64')\n ],\n options: {\n encoding: 'utf8' as const,\n timeout: 15_000,\n maxBuffer: 64 * 1024,\n windowsHide: true,\n env: {\n ...windowsPowerShellEnvironment(),\n TEMPAD_RUNTIME_ACL_REQUEST: JSON.stringify({ action, path, kind })\n }\n }\n }\n}\n\nfunction windowsSecurity(action: SecurityAction, path: string, kind: string) {\n const { file, args, options } = securityCommand(action, path, kind)\n try {\n execFileSync(file, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] })\n } catch (cause) {\n throw securityFailure(cause, path, kind, action)\n }\n}\n\nasync function windowsSecurityAsync(\n action: 'ensure' | 'inspect' | 'protect',\n path: string,\n kind: string,\n signal?: AbortSignal\n) {\n const { file, args, options } = securityCommand(action, path, kind)\n await new Promise<void>((resolve, reject) => {\n const child = execFile(file, args, { ...options, signal }, (error, stdout, stderr) => {\n if (error)\n reject(securityFailure(Object.assign(error, { stdout, stderr }), path, kind, action))\n else resolve()\n })\n child.stdin?.end()\n })\n}\n\nfunction securityFailure(cause: unknown, path: string, kind: string, action: SecurityAction) {\n const error = cause as { stdout?: string; stderr?: string }\n const detail = [error.stdout, error.stderr].filter(Boolean).join('\\n').trim()\n let code: number | string | undefined\n let reportedFailure = false\n try {\n const report = JSON.parse(error.stderr ?? '{}')\n code = report.code\n reportedFailure = typeof report.message === 'string'\n } catch {\n // Startup and policy failures need not be JSON; they still fail closed.\n }\n const failure = new Error(\n `Refusing untrusted Windows runtime ${kind}: ${path}${detail ? ` (${detail})` : ''}`,\n {\n cause\n }\n ) as NodeJS.ErrnoException\n if (code === 2 || code === 3) failure.code = 'ENOENT'\n if (code === 231 || (action === 'retire' && code === 32)) failure.code = 'EBUSY'\n if (code === 'EPIPEUNPROTECTED') failure.code = code\n if (kind === 'directory' && code === 'EINHERITEDACL') failure.code = code\n if (!failure.code && kind === 'pipe' && reportedFailure) failure.code = 'EPIPEUNTRUSTED'\n return failure\n}\n\nconst DIRECTORY_RECOVERY_METHODS = String.raw`\n [DllImport(\"kernel32.dll\", SetLastError=true)]\n static extern bool SetFileInformationByHandle(SafeFileHandle handle, int kind, byte[] info, uint size);\n [DllImport(\"kernel32.dll\", CharSet=CharSet.Unicode, SetLastError=true)]\n static extern uint GetFinalPathNameByHandle(SafeFileHandle handle, System.Text.StringBuilder path, uint size, uint flags);\n [DllImport(\"kernel32.dll\", CharSet=CharSet.Unicode, SetLastError=true)]\n static extern uint GetLongPathName(string path, System.Text.StringBuilder expanded, uint size);\n public static SafeFileHandle OpenLegacyDirectory(string path, bool retire) {\n // FILE_READ_ATTRIBUTES, no share-delete, BACKUP_SEMANTICS | OPEN_REPARSE_POINT.\n var handle = CreateFile(path, retire ? 0x10080u : 0x80u, 1, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero);\n if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());\n try {\n var final = new System.Text.StringBuilder(32768);\n // Windows may supply an 8.3 profile name in TEMP. Expand only short names\n // for the comparison; a junction still differs from the handle's final path.\n var expanded = new System.Text.StringBuilder(32768);\n uint length = GetLongPathName(path, expanded, (uint)expanded.Capacity);\n uint count = GetFinalPathNameByHandle(handle, final, (uint)final.Capacity, 0);\n if (length == 0 || length >= expanded.Capacity || count == 0 || count >= final.Capacity ||\n !String.Equals(final.ToString(), @\"\\\\?\\\" + expanded, StringComparison.OrdinalIgnoreCase) ||\n (System.IO.File.GetAttributes(path) & (System.IO.FileAttributes.Directory | System.IO.FileAttributes.ReparsePoint)) != System.IO.FileAttributes.Directory)\n throw new InvalidOperationException(\"Expected a canonical local runtime directory.\");\n return handle;\n } catch { handle.Dispose(); throw; }\n }\n public static void Retire(SafeFileHandle handle, string path) {\n foreach (string run in System.IO.Directory.GetFileSystemEntries(path, \"run\")) {\n using (OpenLegacyDirectory(run, false)) {\n foreach (string name in new[] { \"hub.lock.lock\", \"mcp.lock.lock\" }) {\n if (System.IO.Directory.GetFileSystemEntries(run, name).Length != 0)\n throw new InvalidOperationException(\"A runtime lock exists.\");\n }\n }\n }\n // FILE_RENAME_INFO with ReplaceIfExists=false and RootDirectory=NULL.\n byte[] nameBytes = System.Text.Encoding.Unicode.GetBytes(path + \".legacy\");\n int lengthOffset = 2 * IntPtr.Size;\n byte[] info = new byte[lengthOffset + 4 + nameBytes.Length + 2];\n BitConverter.GetBytes(nameBytes.Length).CopyTo(info, lengthOffset);\n nameBytes.CopyTo(info, lengthOffset + 4);\n if (!SetFileInformationByHandle(handle, 3, info, (uint)info.Length))\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n`\n\nconst PIPE_SECURITY_METHODS = String.raw`\n [DllImport(\"advapi32.dll\", SetLastError=true)]\n static extern uint GetSecurityInfo(SafeFileHandle handle, uint type, uint info, out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr descriptor);\n [DllImport(\"advapi32.dll\", SetLastError=true)]\n static extern uint SetSecurityInfo(SafeFileHandle handle, uint type, uint info, IntPtr owner, IntPtr group, IntPtr dacl, IntPtr sacl);\n [DllImport(\"advapi32.dll\", CharSet=CharSet.Unicode, SetLastError=true)]\n static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string value, uint revision, out IntPtr descriptor, out uint length);\n [DllImport(\"advapi32.dll\", SetLastError=true)]\n static extern bool GetSecurityDescriptorDacl(IntPtr descriptor, out bool present, out IntPtr dacl, out bool defaulted);\n [DllImport(\"advapi32.dll\")]\n static extern uint GetSecurityDescriptorLength(IntPtr descriptor);\n [DllImport(\"kernel32.dll\")]\n static extern IntPtr LocalFree(IntPtr memory);\n public static byte[] Inspect(string path, string sddl) {\n // PowerShell converts a null string argument to an empty string.\n bool protect = !String.IsNullOrEmpty(sddl);\n SafeFileHandle opened = CreateFile(path, 0x20000u | (protect ? 0x40000u : 0u), 7, IntPtr.Zero, 3, 0x40000000, IntPtr.Zero);\n int openError = Marshal.GetLastWin32Error();\n using (SafeFileHandle handle = opened) {\n if (handle.IsInvalid) throw new Win32Exception(openError, \"CreateFile failed for the runtime pipe.\");\n if (protect) {\n IntPtr replacement; uint length;\n if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, out replacement, out length)) throw new Win32Exception(Marshal.GetLastWin32Error(), \"ConvertStringSecurityDescriptorToSecurityDescriptor failed.\");\n try {\n bool present, defaulted; IntPtr acl;\n if (!GetSecurityDescriptorDacl(replacement, out present, out acl, out defaulted)) throw new Win32Exception(Marshal.GetLastWin32Error(), \"GetSecurityDescriptorDacl failed.\");\n if (!present || acl == IntPtr.Zero) throw new InvalidOperationException(\"The replacement pipe descriptor has no discretionary ACL.\");\n uint changed = SetSecurityInfo(handle, 6, 4u | 0x80000000u, IntPtr.Zero, IntPtr.Zero, acl, IntPtr.Zero);\n if (changed != 0) throw new Win32Exception((int)changed, \"SetSecurityInfo failed for the runtime pipe.\");\n } finally { LocalFree(replacement); }\n }\n IntPtr owner, group, dacl, sacl, descriptor;\n uint result = GetSecurityInfo(handle, 6, 5, out owner, out group, out dacl, out sacl, out descriptor);\n if (result != 0) throw new Win32Exception((int)result, \"GetSecurityInfo failed for the runtime pipe.\");\n try {\n byte[] bytes = new byte[GetSecurityDescriptorLength(descriptor)];\n Marshal.Copy(descriptor, bytes, 0, bytes.Length);\n return bytes;\n } finally { LocalFree(descriptor); }\n }\n }\n`\n\nfunction securityScript(action: SecurityAction) {\n return String.raw`\n$ErrorActionPreference = 'Stop'\n$ProgressPreference = 'SilentlyContinue'\n[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)\n# Module autoload can stall with a filtered host environment. Use the trusted\n# built-in modules directly, without scanning host/user module locations.\nImport-Module \"$PSHOME\\Modules\\Microsoft.PowerShell.Utility\\Microsoft.PowerShell.Utility.psd1\" -ErrorAction Stop\nImport-Module \"$PSHOME\\Modules\\Microsoft.PowerShell.Security\\Microsoft.PowerShell.Security.psd1\" -ErrorAction Stop\n$PSModuleAutoloadingPreference = 'None'\n$failureCode = $null\n$legacy = $null\n$compilerTemp = $null\nfunction New-PrivateDirectory($path) {\n $security = New-Object System.Security.AccessControl.DirectorySecurity\n $security.SetOwner($user)\n $security.SetAccessRuleProtection($true, $false)\n foreach ($sid in $allowed) {\n $principal = New-Object System.Security.Principal.SecurityIdentifier($sid)\n $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($principal, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')\n $security.AddAccessRule($rule)\n }\n [void][IO.Directory]::CreateDirectory($path, $security)\n}\ntry {\n $request = $env:TEMPAD_RUNTIME_ACL_REQUEST | ConvertFrom-Json\n $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User\n $allowed = @($user.Value, 'S-1-5-18', 'S-1-5-32-544')\n if ($request.action -eq 'retire') {\n # Windows PowerShell's Add-Type compiles via temporary files. Temp itself\n # may be sandbox-writable in precisely the migration we are handling.\n $local = [Environment]::GetFolderPath('LocalApplicationData')\n if (![IO.Path]::IsPathRooted($local)) { throw 'Missing local application data directory.' }\n $scratch = [IO.Path]::Combine($local, 'tempad-acl-' + [Guid]::NewGuid().ToString('N'))\n New-PrivateDirectory $scratch\n $compilerTemp = $scratch\n $env:TMP = $env:TEMP = $scratch\n }\n if ($request.kind -eq 'pipe' -or $request.action -eq 'retire') {\n Add-Type -TypeDefinition @'\nusing System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing Microsoft.Win32.SafeHandles;\npublic static class TempadSecurity {\n [DllImport(\"kernel32.dll\", CharSet=CharSet.Unicode, SetLastError=true)]\n static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);\n${action === 'retire' ? DIRECTORY_RECOVERY_METHODS : PIPE_SECURITY_METHODS}\n}\n'@\n }\n if ($request.kind -eq 'pipe') {\n $sddl = $null\n if ($request.action -eq 'protect') {\n $sddl = 'D:P(D;;GA;;;NU)(A;;GA;;;' + $user.Value + ')(A;;GA;;;SY)(A;;GA;;;BA)'\n }\n $bytes = [TempadSecurity]::Inspect($request.path, $sddl)\n $descriptor = New-Object System.Security.AccessControl.RawSecurityDescriptor($bytes, 0)\n } else {\n if ($request.action -eq 'retire') {\n $legacy = [TempadSecurity]::OpenLegacyDirectory($request.path, $true)\n }\n if ($request.action -eq 'ensure' -and ![IO.Directory]::Exists($request.path)) {\n New-PrivateDirectory $request.path\n }\n try {\n $acl = Get-Acl -LiteralPath $request.path\n } catch [System.Management.Automation.ItemNotFoundException], [IO.FileNotFoundException], [IO.DirectoryNotFoundException] {\n $failureCode = 2\n throw\n }\n $descriptor = New-Object System.Security.AccessControl.RawSecurityDescriptor($acl.Sddl)\n }\n if ($allowed -notcontains $descriptor.Owner.Value -or $null -eq $descriptor.DiscretionaryAcl) {\n throw 'Unexpected owner or absent discretionary ACL.'\n }\n $ownAccess = $false\n $foreignAccess = $false\n $inheritedOnly = $request.kind -eq 'directory' -and $descriptor.Owner.Value -eq $user.Value -and !$acl.AreAccessRulesProtected\n $pendingProtection = $request.kind -eq 'pipe' -and $request.action -eq 'inspect'\n foreach ($ace in $descriptor.DiscretionaryAcl) {\n if ($ace.AceType -eq 'AccessAllowed') {\n if ($allowed -notcontains $ace.SecurityIdentifier.Value) {\n $foreignAccess = $true\n if (!$ace.AceFlags.HasFlag([Security.AccessControl.AceFlags]::Inherited)) { $inheritedOnly = $false }\n # Windows' initial pipe descriptor can be owned by Administrators and omit\n # the user's ACE. Only its default reader grants are retryable, never trusted.\n $defaultReader = @('S-1-1-0', 'S-1-5-7') -contains $ace.SecurityIdentifier.Value\n $readOnly = ($ace.AccessMask -band 0x7fedff76) -eq 0\n $pendingProtection = $pendingProtection -and $defaultReader -and $readOnly\n }\n if ($ace.SecurityIdentifier.Value -eq $user.Value) { $ownAccess = $true }\n } elseif ($ace.AceType -eq 'AccessDenied') {\n $inheritedOnly = $false\n } else {\n throw 'Unsupported ACL entry.'\n }\n }\n if ($foreignAccess -and $pendingProtection) { $failureCode = 'EPIPEUNPROTECTED' }\n if (!$ownAccess) { throw 'ACL does not explicitly grant the current user access.' }\n if ($foreignAccess) {\n if ($inheritedOnly -and $request.action -eq 'retire') {\n # Tightening the old DACL cannot revoke open handles or authenticate existing files.\n # Leave the entire tree untouched and recreate the private root at the enrolled path.\n [TempadSecurity]::Retire($legacy, $request.path)\n return\n }\n if ($inheritedOnly) { $failureCode = 'EINHERITEDACL' }\n throw 'ACL grants another account access.'\n }\n} catch {\n $failure = $_.Exception\n while ($failure.InnerException) { $failure = $failure.InnerException }\n if (!$failureCode) { $failureCode = $failure.NativeErrorCode }\n [Console]::Error.WriteLine((@{ message = $failure.Message; code = $failureCode } | ConvertTo-Json -Compress))\n exit 1\n} finally {\n if ($null -ne $legacy) { $legacy.Dispose() }\n if ($null -ne $compilerTemp) {\n # A scanner can still hold compiler output. Never let scratch cleanup undo a completed rename.\n try { [IO.Directory]::Delete($compilerTemp, $true) } catch [IO.IOException] {}\n }\n}\n`\n}\n"],"mappings":";;;;;;;;;;;;AAMA,MAAM,cAAc;AACpB,MAAM,qCAAqB,IAAI,IAA4C;;AAG3E,SAAgB,gBACd,WACA,MACA,WAA4B,QAAQ,UACpC,OAAO,SAAS,CAAC,CAAC,UAClB;CACA,IAAI,aAAa,SAAS,OAAO,KAAK,WAAW,IAAI;CACrD,MAAM,WAAW,WAAW,QAAQ,CAAC,CAClC,OAAO,IAAI,CAAC,CACZ,OAAO,IAAI,CAAC,CACZ,OAAO,UAAU,WAAW,KAAK,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,CACrD,OAAO,IAAI,CAAC,CACZ,OAAO,IAAI,CAAC,CACZ,OAAO,KAAK,CAAC,CACb,MAAM,GAAG,EAAE;CACd,OAAO,GAAG,YAAY,iBAAiB;AACzC;AAEA,SAAgB,OAAO,MAAc;CACnC,OAAO,KAAK,WAAW,WAAW;AACpC;AAEA,SAAS,UAAU,MAAc;CAC/B,MAAM,SAAS,aAAa,IA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AI;EACF,MAAM,SAAS,KAAK,MAAM,MAAM,UAAU,IAAI;EAC9C,OAAO,OAAO;EACd,kBAAkB,OAAO,OAAO,YAAY;CAC9C,QAAQ,CAER;CACA,MAAM,UAAU,IAAI,MAClB,sCAAsC,KAAK,IAAI,OAAO,SAAS,KAAK,OAAO,KAAK,MAChF,EACE,MACF,CACF;CACA,IAAI,SAAS,KAAK,SAAS,GAAG,QAAQ,OAAO;CAC7C,IAAI,SAAS,OAAQ,WAAW,YAAY,SAAS,IAAK,QAAQ,OAAO;CACzE,IAAI,SAAS,oBAAoB,QAAQ,OAAO;CAChD,IAAI,SAAS,eAAe,SAAS,iBAAiB,QAAQ,OAAO;CACrE,IAAI,CAAC,QAAQ,QAAQ,SAAS,UAAU,iBAAiB,QAAQ,OAAO;CACxE,OAAO;AACT;AAEA,MAAM,6BAA6B,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C7C,MAAM,wBAAwB,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CxC,SAAS,eAAe,QAAwB;CAC9C,OAAO,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8CjB,WAAW,WAAW,6BAA6B,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6E3E"}
|
|
@@ -4,9 +4,9 @@ globalThis.__bundlerPathsOverrides = {
|
|
|
4
4
|
'pino-worker': runtimeFilePath(new URL('./pino-worker.mjs', import.meta.url)),
|
|
5
5
|
'pino/file': runtimeFilePath(new URL('./pino-file.mjs', import.meta.url))
|
|
6
6
|
};
|
|
7
|
-
import { A as MANIFEST_PATH, C as sha256, D as readArchive, N as PolicySchema, O as verifyIntegrity, T as verifyPackage, V as validatePolicyBaseline, j as ManifestSchema, t as connectSocket, w as verifyArchive } from "./processes-
|
|
8
|
-
import { i as resolveRelease, n as downloadRelease, t as probeArtifact } from "./probe-
|
|
9
|
-
import { f as endLogging } from "./shared
|
|
7
|
+
import { A as MANIFEST_PATH, C as sha256, D as readArchive, N as PolicySchema, O as verifyIntegrity, T as verifyPackage, V as validatePolicyBaseline, j as ManifestSchema, t as connectSocket, w as verifyArchive } from "./processes-DOmrri5n.mjs";
|
|
8
|
+
import { i as resolveRelease, n as downloadRelease, t as probeArtifact } from "./probe-CqjOWdnP.mjs";
|
|
9
|
+
import { f as endLogging } from "./shared-8_j_xlsJ.mjs";
|
|
10
10
|
import { d as RuntimeDataTransport, f as SocketTransport, n as ControlPeer, t as CONTROL_VERSIONS } from "./protocol-7m-E_iFu.mjs";
|
|
11
11
|
import { tn as ResultSchema } from "./types-kNTSQOnR.mjs";
|
|
12
12
|
import { J as TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS } from "./config-Busa_Dqv.mjs";
|
|
@@ -7,7 +7,7 @@ globalThis.__bundlerPathsOverrides = {
|
|
|
7
7
|
import { i as __toESM } from "./rolldown-runtime-BH1-_iVd.mjs";
|
|
8
8
|
import { t as require_pino } from "./pino-BiEyUxFF.mjs";
|
|
9
9
|
import { n as getRuntimeTimingConfig } from "./config-Busa_Dqv.mjs";
|
|
10
|
-
import { o as ensurePrivateDirectory } from "./runtime-platform-
|
|
10
|
+
import { o as ensurePrivateDirectory } from "./runtime-platform-CpunJOI4.mjs";
|
|
11
11
|
import { dirname, isAbsolute, join } from "node:path";
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
13
|
import { homedir, tmpdir } from "node:os";
|
|
@@ -131,7 +131,7 @@ function runtimeSocketPath(runtime, profile = { kind: "release" }, platform = pr
|
|
|
131
131
|
// package.json
|
|
132
132
|
var package_default = {
|
|
133
133
|
name: "@tempad-dev/mcp",
|
|
134
|
-
version: "1.0.
|
|
134
|
+
version: "1.0.5",
|
|
135
135
|
description: "Connect coding agents to Figma for design inspection, native canvas editing, and UI implementation.",
|
|
136
136
|
license: "MIT",
|
|
137
137
|
repository: {
|
|
@@ -174,7 +174,7 @@ var package_default = {
|
|
|
174
174
|
"typescript": "^6.0.3",
|
|
175
175
|
"unplugin-raw": "^0.8.0",
|
|
176
176
|
"vitest": "5.1.0",
|
|
177
|
-
"ws": "^8.
|
|
177
|
+
"ws": "^8.23.0",
|
|
178
178
|
"zod": "^4.6.7"
|
|
179
179
|
},
|
|
180
180
|
bundleDependencies: [],
|
|
@@ -248,7 +248,10 @@ const directories = runtimeDirectories(process.env, RUNTIME_PROFILE, { prepare:
|
|
|
248
248
|
const RUNTIME_DIR = directories.runtime;
|
|
249
249
|
const LOG_DIR = directories.log;
|
|
250
250
|
const ASSET_DIR = directories.assets;
|
|
251
|
-
if (directories.root)
|
|
251
|
+
if (directories.root) {
|
|
252
|
+
if (process.platform === "win32" && RUNTIME_PROFILE.kind === "release" && !process.env.TEMPAD_MCP_RUNTIME_DIR && !process.env.TEMPAD_MCP_STATE_DIR && !process.env.TEMPAD_MCP_LOG_DIR && !process.env.TEMPAD_MCP_ASSET_DIR) ensurePrivateDirectory(directories.root, { recoverLegacyRoot: true });
|
|
253
|
+
else ensureDir(directories.root);
|
|
254
|
+
}
|
|
252
255
|
ensureDir(RUNTIME_DIR);
|
|
253
256
|
ensureDir(LOG_DIR);
|
|
254
257
|
ensureDir(ASSET_DIR);
|
|
@@ -286,4 +289,4 @@ function endLogging() {
|
|
|
286
289
|
const SOCK_PATH = resolveSockPath();
|
|
287
290
|
export { resolveDefaultRoot as S, normalizePackageVersion as _, HUB_RUNTIME_IDENTITY_PATH as a, resolveStateDir as b, PACKAGE_VERSION as c, SOCK_PATH as d, endLogging as f, log as g, getRecordProperty as h, HUB_LOCK_UPDATE_MS as i, RUNTIME_DIR as l, ensureFile as m, HUB_LOCK_PATH as n, LOCK_PATH as o, ensureDir as p, HUB_LOCK_STALE_MS as r, LOG_DIR as s, ASSET_DIR as t, RUNTIME_PROFILE as u, resolveLogLevel as v, assertTrustedSocket as x, resolveSockPath as y };
|
|
288
291
|
|
|
289
|
-
//# sourceMappingURL=shared
|
|
292
|
+
//# sourceMappingURL=shared-8_j_xlsJ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared--othnF1c.mjs","names":["process","process","packageJson","pino"],"sources":["../../../agent-plugin/src/clients/shared/runtime-paths.mjs","../../../agent-plugin/src/clients/shared/runtime-profile.mjs","../package.json","../src/log-retention.ts","../src/shared.ts"],"sourcesContent":["import { lstatSync, mkdirSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\n\nfunction inspectRoot(path) {\n try {\n return lstatSync(path)\n } catch (error) {\n if (error.code !== 'ENOENT') throw error\n return null\n }\n}\n\nfunction isPrivateRoot(stat, uid) {\n return stat?.isDirectory() && stat.uid === uid && (stat.mode & 0o777) === 0o700\n}\n\nfunction hasHubFiles(root) {\n return (\n inspectRoot(join(root, 'run', 'mcp.sock')) !== null ||\n inspectRoot(join(root, 'run', 'hub.lock.lock')) !== null\n )\n}\n\nexport function resolveDefaultRoot(\n systemTmpDir = tmpdir(),\n platform = process.platform,\n uid = process.getuid?.()\n) {\n const legacyRoot = join(systemTmpDir, 'tempad-dev')\n if (platform !== 'linux') return legacyRoot\n const isolatedRoot = join(systemTmpDir, `tempad-dev-${uid}`)\n const legacy = inspectRoot(legacyRoot)\n const isolated = inspectRoot(isolatedRoot)\n const legacyPrivate = isPrivateRoot(legacy, uid)\n const isolatedPrivate = isPrivateRoot(isolated, uid)\n const legacyActive = legacy?.uid === uid && hasHubFiles(legacyRoot)\n const isolatedActive = isolated?.uid === uid && hasHubFiles(isolatedRoot)\n if (\n (legacyActive && !legacyPrivate) ||\n (isolatedActive && !isolatedPrivate) ||\n (legacyActive && isolatedActive)\n )\n throw new Error(\n `Ambiguous or unsafe Hub runtime roots: ${legacyRoot}, ${isolatedRoot}. Stop the existing runtimes and correct ownership/permissions before reconnecting; automatic migration is refused.`\n )\n if (isolatedPrivate && !legacyActive) return isolatedRoot\n if (legacyPrivate || !legacy) return legacyRoot\n return isolatedRoot\n}\n\nexport function prepareDefaultRoot(\n systemTmpDir = tmpdir(),\n platform = process.platform,\n uid = process.getuid?.()\n) {\n const selected = resolveDefaultRoot(systemTmpDir, platform, uid)\n if (platform !== 'linux' || selected !== join(systemTmpDir, 'tempad-dev')) return selected\n // Claim the released path atomically so old installed hooks still work after a reboot.\n try {\n mkdirSync(selected, { mode: 0o700 })\n } catch (error) {\n if (error.code !== 'EEXIST') throw error\n }\n return resolveDefaultRoot(systemTmpDir, platform, uid)\n}\n\nexport function assertTrustedSocket(\n socketPath,\n platform = process.platform,\n uid = process.getuid?.()\n) {\n if (platform === 'win32') return\n const parent = lstatSync(dirname(socketPath))\n const socket = lstatSync(socketPath)\n if (\n !parent.isDirectory() ||\n parent.uid !== uid ||\n (parent.mode & 0o077) !== 0 ||\n !socket.isSocket() ||\n socket.uid !== uid ||\n (socket.mode & 0o077) !== 0\n )\n throw new Error(\n `Refusing untrusted Hub socket: ${socketPath}. Check its owner and private permissions before reconnecting.`\n )\n}\n","import { Buffer } from 'node:buffer'\nimport { createHash } from 'node:crypto'\nimport { realpathSync, statSync } from 'node:fs'\nimport { homedir, tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join } from 'node:path'\nimport process from 'node:process'\nimport { fileURLToPath } from 'node:url'\n\nimport { prepareDefaultRoot, resolveDefaultRoot } from './runtime-paths.mjs'\n\nfunction hash(value) {\n return createHash('sha256').update(value).digest('hex').slice(0, 16)\n}\n\nexport function checkoutProfile(checkout) {\n if (!isAbsolute(checkout)) throw new Error('TEMPAD_MCP_DEV_CHECKOUT must be an absolute path.')\n const root = realpathSync(checkout)\n if (!statSync(root).isDirectory()) throw new Error('The checkout must be a directory.')\n return { kind: 'checkout', id: hash(root) }\n}\n\nexport function resolveRuntimeProfile(env = process.env, entryUrl) {\n if (env.TEMPAD_MCP_DEV_CHECKOUT === undefined) return { kind: 'release' }\n const profile = checkoutProfile(env.TEMPAD_MCP_DEV_CHECKOUT)\n if (entryUrl) {\n const root = realpathSync(env.TEMPAD_MCP_DEV_CHECKOUT)\n const dist = join(root, 'packages/mcp-server/dist')\n for (const name of ['cli.mjs', 'hub.mjs']) {\n const path = join(dist, name)\n try {\n if (realpathSync(path) === path && statSync(path).isFile()) continue\n } catch (cause) {\n throw new Error(`Missing checkout runtime: ${path}. Run pnpm build:mcp in the checkout.`, {\n cause\n })\n }\n throw new Error(`Invalid checkout runtime: ${path}. Build the checkout before starting MCP.`)\n }\n if (dirname(realpathSync(fileURLToPath(entryUrl))) !== dist)\n throw new Error('The MCP entry point does not belong to TEMPAD_MCP_DEV_CHECKOUT.')\n }\n return profile\n}\n\nexport function runtimeDirectories(\n env = process.env,\n profile = resolveRuntimeProfile(env),\n options = {}\n) {\n const temporary = options.tmpdir ?? tmpdir()\n const home = options.homedir ?? homedir()\n const user = options.uid ?? process.getuid?.() ?? hash(home)\n const checkout = profile.kind === 'checkout'\n const needsRoot =\n !env.TEMPAD_MCP_RUNTIME_DIR || !env.TEMPAD_MCP_LOG_DIR || !env.TEMPAD_MCP_ASSET_DIR\n let root\n if (needsRoot) {\n root = checkout\n ? join(temporary, `tpd-${user}-${profile.id}`)\n : (options.prepare ? prepareDefaultRoot : resolveDefaultRoot)(temporary)\n }\n // Explicit directories remain usable for isolated tests, but never merge checkout and release.\n const directory = (override, name) => {\n if (!override) return join(root, name)\n return checkout ? join(override, `checkout-${profile.id}`) : override\n }\n const runtime = directory(env.TEMPAD_MCP_RUNTIME_DIR, 'run')\n let state\n if (!checkout && env.TEMPAD_MCP_STATE_DIR !== undefined) {\n state = env.TEMPAD_MCP_STATE_DIR\n } else if (env.TEMPAD_MCP_STATE_DIR) {\n state = directory(env.TEMPAD_MCP_STATE_DIR, 'state')\n } else if (env.TEMPAD_MCP_RUNTIME_DIR) {\n state = join(runtime, 'state')\n } else {\n state = checkout\n ? join(home, '.tempad-dev', 'checkouts', profile.id, 'state')\n : join(home, '.tempad-dev', 'state')\n }\n return {\n root,\n runtime,\n log: directory(env.TEMPAD_MCP_LOG_DIR, 'log'),\n assets: directory(env.TEMPAD_MCP_ASSET_DIR, 'assets'),\n state\n }\n}\n\nexport function runtimeSocketPath(\n runtime,\n profile = { kind: 'release' },\n platform = process.platform,\n home = homedir()\n) {\n if (platform !== 'win32') {\n const socket = join(runtime, 'mcp.sock')\n if (profile.kind === 'checkout' && Buffer.byteLength(socket) > 103)\n throw new Error('Checkout socket path is too long. Choose a shorter TEMPAD_MCP_RUNTIME_DIR.')\n return socket\n }\n return profile.kind === 'checkout'\n ? `\\\\\\\\.\\\\pipe\\\\tempad-mcp-${hash(home)}-${profile.id}`\n : '\\\\\\\\.\\\\pipe\\\\tempad-mcp'\n}\n","","import { lstatSync, readdirSync, unlinkSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst RETENTION_MS = 7 * 24 * 60 * 60 * 1000\nconst LOG_NAME = /^(?:startup-)?mcp-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z-([1-9]\\d*)\\.log$/\n\n/** Best-effort housekeeping: never remove a log a running process may still own. */\nexport function pruneExpiredLogs(directory: string, now = Date.now()): number {\n let names: string[]\n try {\n names = readdirSync(directory)\n } catch {\n return 0\n }\n let removed = 0\n for (const name of names) {\n const match = LOG_NAME.exec(name)\n if (!match) continue\n const pid = Number(match[1])\n if (!Number.isSafeInteger(pid) || pid > 2147483647 || pid === process.pid) continue\n try {\n const path = join(directory, name)\n const stat = lstatSync(path)\n if (\n !stat.isFile() ||\n stat.isSymbolicLink() ||\n (process.platform !== 'win32' && stat.uid !== process.getuid?.()) ||\n stat.mtimeMs > now - RETENTION_MS\n )\n continue\n try {\n process.kill(pid, 0)\n continue\n } catch (error) {\n // EPERM and platform-specific probe failures do not establish that a\n // process has exited. PID reuse deliberately favors keeping the log.\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') continue\n }\n unlinkSync(path)\n removed++\n } catch {\n // Concurrent cleanup, antivirus and storage failures must not block MCP.\n }\n }\n return removed\n}\n","import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport pino from 'pino'\n\nimport {\n resolveRuntimeProfile,\n runtimeDirectories,\n runtimeSocketPath\n} from '../../../agent-plugin/src/clients/shared/runtime-profile.mjs'\nimport packageJson from '../package.json' with { type: 'json' }\nimport { getRuntimeTimingConfig } from './config'\nimport { pruneExpiredLogs } from './log-retention'\nimport { ensurePrivateDirectory } from './runtime-platform'\n\nexport {\n assertTrustedSocket,\n resolveDefaultRoot\n} from '../../../agent-plugin/src/clients/shared/runtime-paths.mjs'\n\nexport function normalizePackageVersion(version: unknown): string {\n return typeof version === 'string' ? version : '0.0.0'\n}\n\nexport function ensureDir(dirPath: string): void {\n if (process.platform === 'win32') {\n ensurePrivateDirectory(dirPath)\n return\n }\n mkdirSync(dirPath, { recursive: true, mode: 0o700 })\n const stat = lstatSync(dirPath)\n if (\n !stat.isDirectory() ||\n stat.isSymbolicLink() ||\n stat.uid !== process.getuid?.() ||\n (stat.mode & 0o077) !== 0\n )\n throw new Error(`Refusing untrusted runtime directory: ${dirPath}`)\n}\n\nexport function getRecordProperty(record: unknown, key: string): unknown {\n if (!record || typeof record !== 'object') {\n return undefined\n }\n return Reflect.get(record, key)\n}\n\nexport const PACKAGE_VERSION = normalizePackageVersion(getRecordProperty(packageJson, 'version'))\nexport const RUNTIME_PROFILE = resolveRuntimeProfile(process.env, import.meta.url)\n\nexport function resolveRuntimeDir(\n env: NodeJS.ProcessEnv = process.env,\n systemTmpDir: string = tmpdir()\n): string {\n return runtimeDirectories(env, undefined, { tmpdir: systemTmpDir }).runtime\n}\n\nexport function resolveLogDir(\n env: NodeJS.ProcessEnv = process.env,\n systemTmpDir: string = tmpdir()\n): string {\n return runtimeDirectories(env, undefined, { tmpdir: systemTmpDir }).log\n}\n\nexport function resolveAssetDir(\n env: NodeJS.ProcessEnv = process.env,\n systemTmpDir: string = tmpdir()\n): string {\n return runtimeDirectories(env, undefined, { tmpdir: systemTmpDir }).assets\n}\n\nexport function resolveStateDir(env: NodeJS.ProcessEnv = process.env): string {\n return runtimeDirectories(env).state\n}\n\nexport function resolveLogLevel(\n debugValue: string | undefined = process.env.DEBUG\n): 'debug' | 'info' {\n return debugValue ? 'debug' : 'info'\n}\n\nexport function resolveSockPath(\n platform: NodeJS.Platform = process.platform,\n runtimeDir: string = RUNTIME_DIR\n): string {\n return runtimeSocketPath(runtimeDir, RUNTIME_PROFILE, platform)\n}\n\nconst directories = runtimeDirectories(process.env, RUNTIME_PROFILE, { prepare: true })\nexport const RUNTIME_DIR = directories.runtime\nexport const LOG_DIR = directories.log\nexport const ASSET_DIR = directories.assets\n\nif (directories.root) ensureDir(directories.root)\nensureDir(RUNTIME_DIR)\nensureDir(LOG_DIR)\nensureDir(ASSET_DIR)\n\nexport function ensureFile(filePath: string): void {\n const fd = openSync(filePath, 'a')\n closeSync(fd)\n}\n\nexport const LOCK_PATH = join(RUNTIME_DIR, 'mcp.lock')\nexport const HUB_LOCK_PATH = join(RUNTIME_DIR, 'hub.lock')\nexport const HUB_RUNTIME_IDENTITY_PATH = join(RUNTIME_DIR, 'hub-runtime.json')\nensureFile(LOCK_PATH)\nensureFile(HUB_LOCK_PATH)\n\nexport const HUB_BUSY_EXIT_CODE = 75\nconst runtimeTiming = getRuntimeTimingConfig()\nexport const HUB_LOCK_STALE_MS = runtimeTiming.hubLockStaleMs\nexport const HUB_LOCK_UPDATE_MS = runtimeTiming.hubLockUpdateMs\n\nconst timestamp = new Date().toISOString().replaceAll(':', '-').replaceAll('.', '-')\nconst pid = process.pid\nconst LOG_FILE = join(LOG_DIR, `mcp-${timestamp}-${pid}.log`)\n\npruneExpiredLogs(LOG_DIR)\n\nconst prettyTransport = pino.transport({\n // An ESM worker is a file, even when its parent was launched through --eval.\n ...(process.execArgv.some((arg) => arg === '--input-type' || arg.startsWith('--input-type='))\n ? { worker: { execArgv: [] } }\n : {}),\n target: fileURLToPath(\n import.meta.url.endsWith('.ts')\n ? new URL('./log-transport.ts', import.meta.url)\n : new URL('./log-transport.mjs', import.meta.url)\n ),\n options: {\n translateTime: 'SYS:HH:MM:ss',\n destination: LOG_FILE\n }\n})\n\nexport const log = pino(\n {\n level: resolveLogLevel(),\n msgPrefix: '[tempad-dev/mcp] '\n },\n prettyTransport\n)\n\nexport function endLogging(): void {\n // Shutdown must drain the worker even when its ready event is still pending.\n prettyTransport.end()\n}\n\nexport const SOCK_PATH = resolveSockPath()\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAKA,SAAS,YAAY,MAAM;CACzB,IAAI;EACF,OAAO,UAAU,IAAI;CACvB,SAAS,OAAO;EACd,IAAI,MAAM,SAAS,UAAU,MAAM;EACnC,OAAO;CACT;AACF;AAEA,SAAS,cAAc,MAAM,KAAK;CAChC,OAAO,MAAM,YAAY,KAAK,KAAK,QAAQ,QAAQ,KAAK,OAAO,SAAW;AAC5E;AAEA,SAAS,YAAY,MAAM;CACzB,OACE,YAAY,KAAK,MAAM,OAAO,UAAU,CAAC,MAAM,QAC/C,YAAY,KAAK,MAAM,OAAO,eAAe,CAAC,MAAM;AAExD;AAEA,SAAgB,mBACd,eAAe,OAAO,GACtB,WAAWA,UAAQ,UACnB,MAAMA,UAAQ,SAAS,GACvB;CACA,MAAM,aAAa,KAAK,cAAc,YAAY;CAClD,IAAI,aAAa,SAAS,OAAO;CACjC,MAAM,eAAe,KAAK,cAAc,cAAc,KAAK;CAC3D,MAAM,SAAS,YAAY,UAAU;CACrC,MAAM,WAAW,YAAY,YAAY;CACzC,MAAM,gBAAgB,cAAc,QAAQ,GAAG;CAC/C,MAAM,kBAAkB,cAAc,UAAU,GAAG;CACnD,MAAM,eAAe,QAAQ,QAAQ,OAAO,YAAY,UAAU;CAClE,MAAM,iBAAiB,UAAU,QAAQ,OAAO,YAA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AI,IAAI,uBAAuB,YAAY,GAAG,CACpD;CACA,SAAS;EACP,eAAe;EACf,aAAa;CACf;AACF,CAAC;AAED,MAAa,OAAA,GAAMA,YAAAA,QAAAA,CACjB;CACE,OAAO,gBAAgB;CACvB,WAAW;AACb,GACA,eACF;AAEA,SAAgB,aAAmB;CAEjC,gBAAgB,IAAI;AACtB;AAEA,MAAa,YAAY,gBAAgB"}
|
|
1
|
+
{"version":3,"file":"shared-8_j_xlsJ.mjs","names":["process","process","packageJson","pino"],"sources":["../../../agent-plugin/src/clients/shared/runtime-paths.mjs","../../../agent-plugin/src/clients/shared/runtime-profile.mjs","../package.json","../src/log-retention.ts","../src/shared.ts"],"sourcesContent":["import { lstatSync, mkdirSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\n\nfunction inspectRoot(path) {\n try {\n return lstatSync(path)\n } catch (error) {\n if (error.code !== 'ENOENT') throw error\n return null\n }\n}\n\nfunction isPrivateRoot(stat, uid) {\n return stat?.isDirectory() && stat.uid === uid && (stat.mode & 0o777) === 0o700\n}\n\nfunction hasHubFiles(root) {\n return (\n inspectRoot(join(root, 'run', 'mcp.sock')) !== null ||\n inspectRoot(join(root, 'run', 'hub.lock.lock')) !== null\n )\n}\n\nexport function resolveDefaultRoot(\n systemTmpDir = tmpdir(),\n platform = process.platform,\n uid = process.getuid?.()\n) {\n const legacyRoot = join(systemTmpDir, 'tempad-dev')\n if (platform !== 'linux') return legacyRoot\n const isolatedRoot = join(systemTmpDir, `tempad-dev-${uid}`)\n const legacy = inspectRoot(legacyRoot)\n const isolated = inspectRoot(isolatedRoot)\n const legacyPrivate = isPrivateRoot(legacy, uid)\n const isolatedPrivate = isPrivateRoot(isolated, uid)\n const legacyActive = legacy?.uid === uid && hasHubFiles(legacyRoot)\n const isolatedActive = isolated?.uid === uid && hasHubFiles(isolatedRoot)\n if (\n (legacyActive && !legacyPrivate) ||\n (isolatedActive && !isolatedPrivate) ||\n (legacyActive && isolatedActive)\n )\n throw new Error(\n `Ambiguous or unsafe Hub runtime roots: ${legacyRoot}, ${isolatedRoot}. Stop the existing runtimes and correct ownership/permissions before reconnecting; automatic migration is refused.`\n )\n if (isolatedPrivate && !legacyActive) return isolatedRoot\n if (legacyPrivate || !legacy) return legacyRoot\n return isolatedRoot\n}\n\nexport function prepareDefaultRoot(\n systemTmpDir = tmpdir(),\n platform = process.platform,\n uid = process.getuid?.()\n) {\n const selected = resolveDefaultRoot(systemTmpDir, platform, uid)\n if (platform !== 'linux' || selected !== join(systemTmpDir, 'tempad-dev')) return selected\n // Claim the released path atomically so old installed hooks still work after a reboot.\n try {\n mkdirSync(selected, { mode: 0o700 })\n } catch (error) {\n if (error.code !== 'EEXIST') throw error\n }\n return resolveDefaultRoot(systemTmpDir, platform, uid)\n}\n\nexport function assertTrustedSocket(\n socketPath,\n platform = process.platform,\n uid = process.getuid?.()\n) {\n if (platform === 'win32') return\n const parent = lstatSync(dirname(socketPath))\n const socket = lstatSync(socketPath)\n if (\n !parent.isDirectory() ||\n parent.uid !== uid ||\n (parent.mode & 0o077) !== 0 ||\n !socket.isSocket() ||\n socket.uid !== uid ||\n (socket.mode & 0o077) !== 0\n )\n throw new Error(\n `Refusing untrusted Hub socket: ${socketPath}. Check its owner and private permissions before reconnecting.`\n )\n}\n","import { Buffer } from 'node:buffer'\nimport { createHash } from 'node:crypto'\nimport { realpathSync, statSync } from 'node:fs'\nimport { homedir, tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join } from 'node:path'\nimport process from 'node:process'\nimport { fileURLToPath } from 'node:url'\n\nimport { prepareDefaultRoot, resolveDefaultRoot } from './runtime-paths.mjs'\n\nfunction hash(value) {\n return createHash('sha256').update(value).digest('hex').slice(0, 16)\n}\n\nexport function checkoutProfile(checkout) {\n if (!isAbsolute(checkout)) throw new Error('TEMPAD_MCP_DEV_CHECKOUT must be an absolute path.')\n const root = realpathSync(checkout)\n if (!statSync(root).isDirectory()) throw new Error('The checkout must be a directory.')\n return { kind: 'checkout', id: hash(root) }\n}\n\nexport function resolveRuntimeProfile(env = process.env, entryUrl) {\n if (env.TEMPAD_MCP_DEV_CHECKOUT === undefined) return { kind: 'release' }\n const profile = checkoutProfile(env.TEMPAD_MCP_DEV_CHECKOUT)\n if (entryUrl) {\n const root = realpathSync(env.TEMPAD_MCP_DEV_CHECKOUT)\n const dist = join(root, 'packages/mcp-server/dist')\n for (const name of ['cli.mjs', 'hub.mjs']) {\n const path = join(dist, name)\n try {\n if (realpathSync(path) === path && statSync(path).isFile()) continue\n } catch (cause) {\n throw new Error(`Missing checkout runtime: ${path}. Run pnpm build:mcp in the checkout.`, {\n cause\n })\n }\n throw new Error(`Invalid checkout runtime: ${path}. Build the checkout before starting MCP.`)\n }\n if (dirname(realpathSync(fileURLToPath(entryUrl))) !== dist)\n throw new Error('The MCP entry point does not belong to TEMPAD_MCP_DEV_CHECKOUT.')\n }\n return profile\n}\n\nexport function runtimeDirectories(\n env = process.env,\n profile = resolveRuntimeProfile(env),\n options = {}\n) {\n const temporary = options.tmpdir ?? tmpdir()\n const home = options.homedir ?? homedir()\n const user = options.uid ?? process.getuid?.() ?? hash(home)\n const checkout = profile.kind === 'checkout'\n const needsRoot =\n !env.TEMPAD_MCP_RUNTIME_DIR || !env.TEMPAD_MCP_LOG_DIR || !env.TEMPAD_MCP_ASSET_DIR\n let root\n if (needsRoot) {\n root = checkout\n ? join(temporary, `tpd-${user}-${profile.id}`)\n : (options.prepare ? prepareDefaultRoot : resolveDefaultRoot)(temporary)\n }\n // Explicit directories remain usable for isolated tests, but never merge checkout and release.\n const directory = (override, name) => {\n if (!override) return join(root, name)\n return checkout ? join(override, `checkout-${profile.id}`) : override\n }\n const runtime = directory(env.TEMPAD_MCP_RUNTIME_DIR, 'run')\n let state\n if (!checkout && env.TEMPAD_MCP_STATE_DIR !== undefined) {\n state = env.TEMPAD_MCP_STATE_DIR\n } else if (env.TEMPAD_MCP_STATE_DIR) {\n state = directory(env.TEMPAD_MCP_STATE_DIR, 'state')\n } else if (env.TEMPAD_MCP_RUNTIME_DIR) {\n state = join(runtime, 'state')\n } else {\n state = checkout\n ? join(home, '.tempad-dev', 'checkouts', profile.id, 'state')\n : join(home, '.tempad-dev', 'state')\n }\n return {\n root,\n runtime,\n log: directory(env.TEMPAD_MCP_LOG_DIR, 'log'),\n assets: directory(env.TEMPAD_MCP_ASSET_DIR, 'assets'),\n state\n }\n}\n\nexport function runtimeSocketPath(\n runtime,\n profile = { kind: 'release' },\n platform = process.platform,\n home = homedir()\n) {\n if (platform !== 'win32') {\n const socket = join(runtime, 'mcp.sock')\n if (profile.kind === 'checkout' && Buffer.byteLength(socket) > 103)\n throw new Error('Checkout socket path is too long. Choose a shorter TEMPAD_MCP_RUNTIME_DIR.')\n return socket\n }\n return profile.kind === 'checkout'\n ? `\\\\\\\\.\\\\pipe\\\\tempad-mcp-${hash(home)}-${profile.id}`\n : '\\\\\\\\.\\\\pipe\\\\tempad-mcp'\n}\n","","import { lstatSync, readdirSync, unlinkSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst RETENTION_MS = 7 * 24 * 60 * 60 * 1000\nconst LOG_NAME = /^(?:startup-)?mcp-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z-([1-9]\\d*)\\.log$/\n\n/** Best-effort housekeeping: never remove a log a running process may still own. */\nexport function pruneExpiredLogs(directory: string, now = Date.now()): number {\n let names: string[]\n try {\n names = readdirSync(directory)\n } catch {\n return 0\n }\n let removed = 0\n for (const name of names) {\n const match = LOG_NAME.exec(name)\n if (!match) continue\n const pid = Number(match[1])\n if (!Number.isSafeInteger(pid) || pid > 2147483647 || pid === process.pid) continue\n try {\n const path = join(directory, name)\n const stat = lstatSync(path)\n if (\n !stat.isFile() ||\n stat.isSymbolicLink() ||\n (process.platform !== 'win32' && stat.uid !== process.getuid?.()) ||\n stat.mtimeMs > now - RETENTION_MS\n )\n continue\n try {\n process.kill(pid, 0)\n continue\n } catch (error) {\n // EPERM and platform-specific probe failures do not establish that a\n // process has exited. PID reuse deliberately favors keeping the log.\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') continue\n }\n unlinkSync(path)\n removed++\n } catch {\n // Concurrent cleanup, antivirus and storage failures must not block MCP.\n }\n }\n return removed\n}\n","import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport pino from 'pino'\n\nimport {\n resolveRuntimeProfile,\n runtimeDirectories,\n runtimeSocketPath\n} from '../../../agent-plugin/src/clients/shared/runtime-profile.mjs'\nimport packageJson from '../package.json' with { type: 'json' }\nimport { getRuntimeTimingConfig } from './config'\nimport { pruneExpiredLogs } from './log-retention'\nimport { ensurePrivateDirectory } from './runtime-platform'\n\nexport {\n assertTrustedSocket,\n resolveDefaultRoot\n} from '../../../agent-plugin/src/clients/shared/runtime-paths.mjs'\n\nexport function normalizePackageVersion(version: unknown): string {\n return typeof version === 'string' ? version : '0.0.0'\n}\n\nexport function ensureDir(dirPath: string): void {\n if (process.platform === 'win32') {\n ensurePrivateDirectory(dirPath)\n return\n }\n mkdirSync(dirPath, { recursive: true, mode: 0o700 })\n const stat = lstatSync(dirPath)\n if (\n !stat.isDirectory() ||\n stat.isSymbolicLink() ||\n stat.uid !== process.getuid?.() ||\n (stat.mode & 0o077) !== 0\n )\n throw new Error(`Refusing untrusted runtime directory: ${dirPath}`)\n}\n\nexport function getRecordProperty(record: unknown, key: string): unknown {\n if (!record || typeof record !== 'object') {\n return undefined\n }\n return Reflect.get(record, key)\n}\n\nexport const PACKAGE_VERSION = normalizePackageVersion(getRecordProperty(packageJson, 'version'))\nexport const RUNTIME_PROFILE = resolveRuntimeProfile(process.env, import.meta.url)\n\nexport function resolveRuntimeDir(\n env: NodeJS.ProcessEnv = process.env,\n systemTmpDir: string = tmpdir()\n): string {\n return runtimeDirectories(env, undefined, { tmpdir: systemTmpDir }).runtime\n}\n\nexport function resolveLogDir(\n env: NodeJS.ProcessEnv = process.env,\n systemTmpDir: string = tmpdir()\n): string {\n return runtimeDirectories(env, undefined, { tmpdir: systemTmpDir }).log\n}\n\nexport function resolveAssetDir(\n env: NodeJS.ProcessEnv = process.env,\n systemTmpDir: string = tmpdir()\n): string {\n return runtimeDirectories(env, undefined, { tmpdir: systemTmpDir }).assets\n}\n\nexport function resolveStateDir(env: NodeJS.ProcessEnv = process.env): string {\n return runtimeDirectories(env).state\n}\n\nexport function resolveLogLevel(\n debugValue: string | undefined = process.env.DEBUG\n): 'debug' | 'info' {\n return debugValue ? 'debug' : 'info'\n}\n\nexport function resolveSockPath(\n platform: NodeJS.Platform = process.platform,\n runtimeDir: string = RUNTIME_DIR\n): string {\n return runtimeSocketPath(runtimeDir, RUNTIME_PROFILE, platform)\n}\n\nconst directories = runtimeDirectories(process.env, RUNTIME_PROFILE, { prepare: true })\nexport const RUNTIME_DIR = directories.runtime\nexport const LOG_DIR = directories.log\nexport const ASSET_DIR = directories.assets\n\nif (directories.root) {\n const defaultRelease =\n process.platform === 'win32' &&\n RUNTIME_PROFILE.kind === 'release' &&\n !process.env.TEMPAD_MCP_RUNTIME_DIR &&\n !process.env.TEMPAD_MCP_STATE_DIR &&\n !process.env.TEMPAD_MCP_LOG_DIR &&\n !process.env.TEMPAD_MCP_ASSET_DIR\n if (defaultRelease) ensurePrivateDirectory(directories.root, { recoverLegacyRoot: true })\n else ensureDir(directories.root)\n}\nensureDir(RUNTIME_DIR)\nensureDir(LOG_DIR)\nensureDir(ASSET_DIR)\n\nexport function ensureFile(filePath: string): void {\n const fd = openSync(filePath, 'a')\n closeSync(fd)\n}\n\nexport const LOCK_PATH = join(RUNTIME_DIR, 'mcp.lock')\nexport const HUB_LOCK_PATH = join(RUNTIME_DIR, 'hub.lock')\nexport const HUB_RUNTIME_IDENTITY_PATH = join(RUNTIME_DIR, 'hub-runtime.json')\nensureFile(LOCK_PATH)\nensureFile(HUB_LOCK_PATH)\n\nexport const HUB_BUSY_EXIT_CODE = 75\nconst runtimeTiming = getRuntimeTimingConfig()\nexport const HUB_LOCK_STALE_MS = runtimeTiming.hubLockStaleMs\nexport const HUB_LOCK_UPDATE_MS = runtimeTiming.hubLockUpdateMs\n\nconst timestamp = new Date().toISOString().replaceAll(':', '-').replaceAll('.', '-')\nconst pid = process.pid\nconst LOG_FILE = join(LOG_DIR, `mcp-${timestamp}-${pid}.log`)\n\npruneExpiredLogs(LOG_DIR)\n\nconst prettyTransport = pino.transport({\n // An ESM worker is a file, even when its parent was launched through --eval.\n ...(process.execArgv.some((arg) => arg === '--input-type' || arg.startsWith('--input-type='))\n ? { worker: { execArgv: [] } }\n : {}),\n target: fileURLToPath(\n import.meta.url.endsWith('.ts')\n ? new URL('./log-transport.ts', import.meta.url)\n : new URL('./log-transport.mjs', import.meta.url)\n ),\n options: {\n translateTime: 'SYS:HH:MM:ss',\n destination: LOG_FILE\n }\n})\n\nexport const log = pino(\n {\n level: resolveLogLevel(),\n msgPrefix: '[tempad-dev/mcp] '\n },\n prettyTransport\n)\n\nexport function endLogging(): void {\n // Shutdown must drain the worker even when its ready event is still pending.\n prettyTransport.end()\n}\n\nexport const SOCK_PATH = resolveSockPath()\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAKA,SAAS,YAAY,MAAM;CACzB,IAAI;EACF,OAAO,UAAU,IAAI;CACvB,SAAS,OAAO;EACd,IAAI,MAAM,SAAS,UAAU,MAAM;EACnC,OAAO;CACT;AACF;AAEA,SAAS,cAAc,MAAM,KAAK;CAChC,OAAO,MAAM,YAAY,KAAK,KAAK,QAAQ,QAAQ,KAAK,OAAO,SAAW;AAC5E;AAEA,SAAS,YAAY,MAAM;CACzB,OACE,YAAY,KAAK,MAAM,OAAO,UAAU,CAAC,MAAM,QAC/C,YAAY,KAAK,MAAM,OAAO,eAAe,CAAC,MAAM;AAExD;AAEA,SAAgB,mBACd,eAAe,OAAO,GACtB,WAAWA,UAAQ,UACnB,MAAMA,UAA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MAAM,gBAAgB,uBAAuB;AAC7C,MAAa,oBAAoB,cAAc;AAC/C,MAAa,qBAAqB,cAAc;AAEhD,MAAM,6BAAY,IAAI,KAAK,EAAA,CAAE,YAAY,CAAC,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC,WAAW,KAAK,GAAG;AACnF,MAAM,MAAM,QAAQ;AACpB,MAAM,WAAW,KAAK,SAAS,OAAO,UAAU,GAAG,IAAI,KAAK;AAE5D,iBAAiB,OAAO;AAExB,MAAM,kBAAkBC,YAAAA,QAAK,UAAU;CAErC,GAAI,QAAQ,SAAS,MAAM,QAAQ,QAAQ,kBAAkB,IAAI,WAAW,eAAe,CAAC,IACxF,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE,EAAE,IAC3B,CAAC;CACL,QAAQ,cACN,YAAY,IAAI,SAAS,KAAK,IAC1B,IAAI,IAAI,sBAAsB,YAAY,GAAG,IAC7C,IAAI,IAAI,uBAAuB,YAAY,GAAG,CACpD;CACA,SAAS;EACP,eAAe;EACf,aAAa;CACf;AACF,CAAC;AAED,MAAa,OAAA,GAAMA,YAAAA,QAAAA,CACjB;CACE,OAAO,gBAAgB;CACvB,WAAW;AACb,GACA,eACF;AAEA,SAAgB,aAAmB;CAEjC,gBAAgB,IAAI;AACtB;AAEA,MAAa,YAAY,gBAAgB"}
|
|
@@ -4,4 +4,4 @@ globalThis.__bundlerPathsOverrides = {
|
|
|
4
4
|
'pino-worker': runtimeFilePath(new URL('./pino-worker.mjs', import.meta.url)),
|
|
5
5
|
'pino/file': runtimeFilePath(new URL('./pino-file.mjs', import.meta.url))
|
|
6
6
|
};
|
|
7
|
-
export { f as endLogging } from "./shared
|
|
7
|
+
export { f as endLogging } from "./shared-8_j_xlsJ.mjs";
|
|
@@ -4,7 +4,7 @@ globalThis.__bundlerPathsOverrides = {
|
|
|
4
4
|
'pino-worker': runtimeFilePath(new URL('./pino-worker.mjs', import.meta.url)),
|
|
5
5
|
'pino/file': runtimeFilePath(new URL('./pino-file.mjs', import.meta.url))
|
|
6
6
|
};
|
|
7
|
-
import { c as PACKAGE_VERSION, s as LOG_DIR } from "./shared
|
|
7
|
+
import { c as PACKAGE_VERSION, s as LOG_DIR } from "./shared-8_j_xlsJ.mjs";
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
import { closeSync, openSync, writeFileSync, writeSync } from "node:fs";
|
|
10
10
|
// src/startup-log.ts
|
|
@@ -76,4 +76,4 @@ function startupPhase(phase, action) {
|
|
|
76
76
|
}
|
|
77
77
|
export { startStartup as n, startupPhase as r, finishStartup as t };
|
|
78
78
|
|
|
79
|
-
//# sourceMappingURL=startup-log-
|
|
79
|
+
//# sourceMappingURL=startup-log-BI24ryBR.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"startup-log-
|
|
1
|
+
{"version":3,"file":"startup-log-BI24ryBR.mjs","names":[],"sources":["../src/startup-log.ts"],"sourcesContent":["import { closeSync, openSync, writeFileSync, writeSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { LOG_DIR, PACKAGE_VERSION } from './shared'\n\nlet started = 0\nlet role = ''\nlet active = false\nlet descriptor: number | undefined\nlet bytes = 0\n\n/** Keep startup evidence available even if the host kills a logging worker. */\nfunction startupEvent(phase: string, event: string, durationMs?: number, error?: unknown): void {\n if (!active) return\n const line =\n JSON.stringify({\n time: new Date().toISOString(),\n pid: process.pid,\n role,\n version: PACKAGE_VERSION,\n node: process.version,\n elapsedMs: Math.round(performance.now() - started),\n phase,\n event,\n ...(error === undefined ? {} : { error: String(error).slice(0, 1000) }),\n ...(durationMs === undefined ? {} : { durationMs: Math.round(durationMs) })\n }) + '\\n'\n try {\n const size = Buffer.byteLength(line)\n if (bytes + size > 1024 * 1024) return\n descriptor ??= openSync(\n join(\n LOG_DIR,\n `startup-mcp-${new Date().toISOString().replaceAll(':', '-').replaceAll('.', '-')}-${process.pid}.log`\n ),\n 'wx',\n 0o600\n )\n writeFileSync(descriptor, line)\n bytes += size\n } catch {\n // Diagnostics must not prevent the runtime from starting.\n }\n if (\n role === 'cli' &&\n !process.stdin.isTTY &&\n process.argv.slice(2).every((arg) => arg.startsWith('--runtime-updates=')) &&\n (event === 'ready' || event === 'failed')\n ) {\n try {\n writeSync(2, `TemPad startup ${line}`)\n } catch {\n /* Host may have disconnected. */\n }\n }\n}\n\nexport function startStartup(processRole: string): void {\n role = processRole\n started = performance.now()\n active = true\n startupEvent(role, 'start')\n}\n\nexport function finishStartup(event: 'ready' | 'failed', error?: unknown): void {\n if (!active) return\n startupEvent(role, event, performance.now() - started, error)\n active = false\n try {\n if (descriptor !== undefined) closeSync(descriptor)\n } catch {\n /* Logging must not block readiness or error handling. */\n }\n descriptor = undefined\n}\n\nexport function startupPhase<T>(phase: string, action: () => T): T {\n if (!active) return action()\n const start = performance.now()\n startupEvent(phase, 'start')\n const complete = <V>(value: V): V => {\n startupEvent(phase, 'complete', performance.now() - start)\n return value\n }\n const failed = (error: unknown): never => {\n startupEvent(phase, 'failed', performance.now() - start, error)\n throw error\n }\n try {\n const result = action()\n if (result instanceof Promise) return result.then(complete, failed) as T\n return complete(result)\n } catch (error) {\n return failed(error)\n }\n}\n"],"mappings":";;;;;;;;;;AAKA,IAAI,UAAU;AACd,IAAI,OAAO;AACX,IAAI,SAAS;AACb,IAAI;AACJ,IAAI,QAAQ;;AAGZ,SAAS,aAAa,OAAe,OAAe,YAAqB,OAAuB;CAC9F,IAAI,CAAC,QAAQ;CACb,MAAM,OACJ,KAAK,UAAU;EACb,uBAAM,IAAI,KAAK,EAAA,CAAE,YAAY;EAC7B,KAAK,QAAQ;EACb;EACA,SAAS;EACT,MAAM,QAAQ;EACd,WAAW,KAAK,MAAM,YAAY,IAAI,IAAI,OAAO;EACjD;EACA;EACA,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,GAAI,EAAE;EACrE,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAA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;EACtB,IAAI,kBAAkB,SAAS,OAAO,OAAO,KAAK,UAAU,MAAM;EAClE,OAAO,SAAS,MAAM;CACxB,SAAS,OAAO;EACd,OAAO,OAAO,KAAK;CACrB;AACF"}
|
|
@@ -4,4 +4,4 @@ globalThis.__bundlerPathsOverrides = {
|
|
|
4
4
|
'pino-worker': runtimeFilePath(new URL('./pino-worker.mjs', import.meta.url)),
|
|
5
5
|
'pino/file': runtimeFilePath(new URL('./pino-file.mjs', import.meta.url))
|
|
6
6
|
};
|
|
7
|
-
export { t as finishStartup, n as startStartup } from "./startup-log-
|
|
7
|
+
export { t as finishStartup, n as startStartup } from "./startup-log-BI24ryBR.mjs";
|
|
@@ -6,7 +6,7 @@ globalThis.__bundlerPathsOverrides = {
|
|
|
6
6
|
};
|
|
7
7
|
import { S as uuid, d as literal, i as _enum, m as object, o as array, p as number, v as string } from "./schemas-ZDdPV7RQ.mjs";
|
|
8
8
|
import { t as writeDurableJson } from "./durable-json-_WKesGDj.mjs";
|
|
9
|
-
import { n as assertPrivatePath, r as assertPrivatePathAsync } from "./runtime-platform-
|
|
9
|
+
import { n as assertPrivatePath, r as assertPrivatePathAsync } from "./runtime-platform-CpunJOI4.mjs";
|
|
10
10
|
import { isAbsolute, join } from "node:path";
|
|
11
11
|
import { readFileSync } from "node:fs";
|
|
12
12
|
// src/runtime-prototype/state.ts
|
|
@@ -104,4 +104,4 @@ function newerVersion(candidate, active) {
|
|
|
104
104
|
}
|
|
105
105
|
export { newerVersion as a, readJournalAsync as c, writeEndpoints as d, writeJournal as f, JournalSchema as i, readPrivateJson as l, ConfigSchema as n, readEndpoints as o, EndpointsSchema as r, readJournal as s, ArtifactSchema as t, readPrivateJsonAsync as u };
|
|
106
106
|
|
|
107
|
-
//# sourceMappingURL=state-
|
|
107
|
+
//# sourceMappingURL=state-4Dz7r-_n.mjs.map
|