@xmoon76/dsh-pi-tui 0.5.8 → 0.5.9
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.en.md +61 -25
- package/README.md +61 -25
- package/cordis.patch.yml +13 -0
- package/dist/acp-stdio.mjs +151 -0
- package/dist/{bootstrap-CMIjGyuk.mjs → bootstrap-CVyHGQDX.mjs} +21901 -6575
- package/dist/browser-CDUSHIIr.mjs +76 -0
- package/dist/builtins.mjs +2 -2
- package/dist/{client-bootstrap-BjGPc-DM.mjs → client-bootstrap-4UoeVIHE.mjs} +2488 -2734
- package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
- package/dist/{daemon-launcher-Dult7Jxv.mjs → daemon-launcher-DxIgjBHW.mjs} +1549 -172
- package/dist/daemon-launcher.d.mts +85 -14
- package/dist/daemon-launcher.mjs +2 -2
- package/dist/{local-profile-daemon-admin-BmQSdzT0.mjs → diagnostics-Db5iVcuJ.mjs} +3 -90
- package/dist/{entry-control-DjNsE3I0.mjs → entry-control-BDLZgg4m.mjs} +1 -1
- package/dist/{extensions-B4uLpSTv.mjs → extensions-Dx7ncPNA.mjs} +1 -1
- package/dist/extensions.mjs +1 -1
- package/dist/handoff-BjoEy3f8.mjs +106 -0
- package/dist/history-search-limits-Cx2UvRC2.mjs +16 -0
- package/dist/history-search-remote-BHuoellG.mjs +113 -0
- package/dist/history-search-remote-BzXdvrxk.mjs +26 -0
- package/dist/history-search-seat-BcHJTpeB.mjs +639 -0
- package/dist/history-search-seat-rZcq0XV6.mjs +639 -0
- package/dist/{host-bootstrap-MVxks641.mjs → host-bootstrap-BfnufpnW.mjs} +37 -72
- package/dist/{host-foundation-probe-DMNTmNrH.mjs → host-foundation-probe-DlD8-N_Q.mjs} +2 -2
- package/dist/host-runtime.mjs +5611 -290
- package/dist/index.d.mts +13 -6
- package/dist/index.mjs +22334 -6695
- package/dist/installed-dsh-BjUiJSwR.mjs +142 -0
- package/dist/interaction-port-D1Yv9zgu.mjs +45 -0
- package/dist/local-acp-control-CC5z4Xbq.mjs +304 -0
- package/dist/local-acp-endpoint-D1jYdJdv.mjs +41 -0
- package/dist/local-acp-listener-Cmgb5M0H.mjs +9493 -0
- package/dist/local-acp-status-B_25Q6kU.mjs +101 -0
- package/dist/local-client.mjs +292 -63
- package/dist/local-daemon-control-BFJAC8Kg.mjs +2199 -0
- package/dist/local-daemon-control-Bm3imctD.mjs +2101 -0
- package/dist/{local-discovery-uOBfFq5j.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
- package/dist/{local-discovery-egN4_gsQ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
- package/dist/{local-discovery-DOSsCh9q.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
- package/dist/local-host.mjs +952 -501
- package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
- package/dist/{local-scope-DamiMqPd.mjs → local-scope-5DEKA_lW.mjs} +1023 -96
- package/dist/{local-transport-Iwo0mtu3.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
- package/dist/{local-web-control-DMrjwCkl.mjs → local-web-control-Dny93N-r.mjs} +10 -7
- package/dist/{local-workspace-object-D06GL0UO.mjs → local-workspace-object-D0RVQt8U.mjs} +33 -9
- package/dist/model-selection-CYlqg2DV.mjs +83 -0
- package/dist/native-client-domains-Dg4srzYt.mjs +2 -0
- package/dist/native-client.d.mts +735 -0
- package/dist/native-client.mjs +3534 -0
- package/dist/{open-CmOBxSjN.mjs → open-QQva8-ar.mjs} +24 -20
- package/dist/{pi-tui-remote-contribution-Do8ECrUy.mjs → pi-tui-remote-contribution-565wiLWp.mjs} +741 -150
- package/dist/preferences.mjs +1 -1
- package/dist/{profile-preferences-migration-CThz4rHH.mjs → profile-preferences-migration-CNOWIdnr.mjs} +1 -1
- package/dist/{profile-preferences-migration-BfUGdPZx.mjs → profile-preferences-migration-IrnXcJWK.mjs} +10 -8
- package/dist/{prompt-sections-DXmjB58H.mjs → prompt-sections-Bi-9_Gr_.mjs} +28 -10
- package/dist/{prompt-sections-DUKmWb8g.mjs → prompt-sections-DFS1dqsY.mjs} +342 -56
- package/dist/{dist-BFgC-5tL.mjs → recall-scope-9Nuoto_i.mjs} +353 -1
- package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
- package/dist/schema-CCLvDa7Q.mjs +177 -0
- package/dist/{schema-qE_P09zJ.mjs → schema-t97l3aK8.mjs} +56 -3
- package/dist/{session-C6tSs86s.mjs → session-Cs8iLCEx.mjs} +784 -342
- package/dist/{session-CstInGIA.mjs → session-EBRZF6Ow.mjs} +783 -341
- package/dist/session-create-facts-CkfG5DpQ.mjs +20 -0
- package/dist/{startup-CarQxWwi.d.mts → startup-Dti3Udne.d.mts} +30 -3
- package/dist/{startup-EG5UqIcd.mjs → startup-UtFQSDe_.mjs} +90 -15
- package/dist/startup.d.mts +2 -2
- package/dist/startup.mjs +1 -1
- package/dist/task-read-remote-DRtkXDrZ.mjs +1083 -0
- package/dist/{terminal-progress-source-CpfpQO_h.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -332
- package/dist/{transcript-view-CuJYWkhp.mjs → transcript-view-B6vCnukn.mjs} +2096 -977
- package/dist/{transcript-view-C1YtJ49Y.mjs → transcript-view-DSSdE2vK.mjs} +2078 -651
- package/dist/write-failure-xNKczXH7.mjs +189 -0
- package/package.json +20 -3
- package/dist/local-acp-listener-B65J0Bx4.mjs +0 -3115
- package/dist/local-daemon-control-C14q9KnD.mjs +0 -1588
- package/dist/local-daemon-control-TCnERL7n.mjs +0 -1424
- package/dist/preset-BcWqOtY7.mjs +0 -46
|
@@ -0,0 +1,2199 @@
|
|
|
1
|
+
import { B as closeWin32Handle, C as darwinHostProfileSeatDir, D as materializeBuild, H as openWin32StopSignal, K as win32SystemDirectory, L as readKernelProcess, S as bindProfileKernelSeat, T as inspectInstalledProfileScope, U as waitWin32Handle, V as openWin32Process, W as win32CurrentTokenSid, b as bindDarwinKernelSeat, k as readLinuxStarttime, w as ensureInstalledProfileScopeDirectory, x as bindProcessSeat, y as LocalScopeError, z as sameKernelProcess } from "./daemon-launcher-DxIgjBHW.mjs";
|
|
2
|
+
import { a as installedDshManifest, o as readManifestObject } from "./installed-dsh-BjUiJSwR.mjs";
|
|
3
|
+
import { t as observeAuthenticatedLocalAcpStatus } from "./local-acp-status-B_25Q6kU.mjs";
|
|
4
|
+
import { C as launchdServiceMatches, S as launchdLogPaths, T as uninstallLaunchdUnit, _ as stopOwnedProfileUnit, a as inspectHostProcess, b as inspectOwnedLaunchdUnit, c as buildUnitName, d as inspectOwnedProfileUnit, f as installProfileHostUnit, g as setOwnedProfileUnitEnablement, h as selectRuntimeDir, i as ensureLocalHost, l as collectLaunchdProfileFacts, m as runSystemctl, n as assertRecordedHostKernelIdentityCurrent, o as readLocalRecord, p as queryOwnedProfileUnit, r as authenticateLocalHost, s as sameLocalInstanceRecord, t as assertClientHostCompatible, u as collectLaunchdUnitFacts, v as uninstallOwnedProfileUnit, w as stopLaunchdService, x as installLaunchdUnit, y as inspectLaunchdService } from "./local-discovery-BMhaGIiJ.mjs";
|
|
5
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
|
|
6
|
+
import { dirname, isAbsolute, join, posix, sep } from "node:path";
|
|
7
|
+
import "node:crypto";
|
|
8
|
+
import { execFile } from "node:child_process";
|
|
9
|
+
import { stripVTControlCharacters } from "node:util";
|
|
10
|
+
import "node:net";
|
|
11
|
+
import "@agentclientprotocol/sdk";
|
|
12
|
+
//#region src/app/remote-process/local-host-windows-login.ts
|
|
13
|
+
/**
|
|
14
|
+
* Windows login-only Task Scheduler adapter (DS-08).
|
|
15
|
+
*
|
|
16
|
+
* This module owns exactly ONE Windows login-startup route: one native
|
|
17
|
+
* Scheduled Task in the root `\` folder that starts the existing public
|
|
18
|
+
* `daemon start` CLI at the current user's logon. It is NOT Host supervision:
|
|
19
|
+
* it never observes readiness, never restarts after an abnormal exit, and it
|
|
20
|
+
* never becomes a second Host/Session/Agent/Writer authority. The Host remains
|
|
21
|
+
* the only business owner and the existing Event/held-handle stop path is
|
|
22
|
+
* unchanged.
|
|
23
|
+
*
|
|
24
|
+
* The task definition is the ONLY persistent authority. There is no marker
|
|
25
|
+
* file, receipt, registry or shadow state: the exact task name, description
|
|
26
|
+
* and current-user principal SID are the ownership metadata of the one native
|
|
27
|
+
* task, and a fresh task is created with COM `TASK_CREATE` (create-only, no
|
|
28
|
+
* overwrite). The adapter talks to the same system Task Scheduler service
|
|
29
|
+
* through system Windows PowerShell; no schtasks/cmdlet fallback, no WMI, no
|
|
30
|
+
* admin and no stored password.
|
|
31
|
+
*
|
|
32
|
+
* @module app/remote-process/local-host-windows-login
|
|
33
|
+
*/
|
|
34
|
+
/** The deterministic task-name prefix; the full scope id is the suffix. */
|
|
35
|
+
const WINDOWS_LOGIN_TASK_PREFIX = "dsh-pi-tui-login-";
|
|
36
|
+
/** The exact description metadata; the full scope id is the suffix. */
|
|
37
|
+
const WINDOWS_LOGIN_DESCRIPTION_PREFIX = "dsh-pi-tui login-only scope=";
|
|
38
|
+
/** Bound on one system-PowerShell invocation. */
|
|
39
|
+
const WINDOWS_LOGIN_TIMEOUT_MS = 15e3;
|
|
40
|
+
/** Hard cap on captured PowerShell output. */
|
|
41
|
+
const WINDOWS_LOGIN_MAX_OUTPUT_BYTES = 65536;
|
|
42
|
+
/** The fixed COM state values used by the idle-unregister admission. */
|
|
43
|
+
const TASK_STATE_DISABLED = 1;
|
|
44
|
+
const TASK_STATE_READY = 3;
|
|
45
|
+
/** The exact Task Scheduler COM not-found HRESULT. */
|
|
46
|
+
const TASK_NOT_FOUND_HRESULT = "0x80070002";
|
|
47
|
+
/** The only supported official DSH CLI entry inside the installed package. */
|
|
48
|
+
const OFFICIAL_DSH_BIN = "lib/bin.js";
|
|
49
|
+
/** Safe operator hint for a possibly-committed uninstall. */
|
|
50
|
+
const WINDOWS_UNINSTALL_UNCERTAIN = "the Task Scheduler uninstall may already be committed; inspect the native Task Scheduler task before deciding";
|
|
51
|
+
/** The deterministic task name for one canonical profile scope. */
|
|
52
|
+
function buildWindowsLoginTaskName(scopeId) {
|
|
53
|
+
return `${WINDOWS_LOGIN_TASK_PREFIX}${scopeId}`;
|
|
54
|
+
}
|
|
55
|
+
/** The deterministic native description for one canonical profile scope. */
|
|
56
|
+
function buildWindowsLoginDescription(scopeId) {
|
|
57
|
+
return `${WINDOWS_LOGIN_DESCRIPTION_PREFIX}${scopeId}`;
|
|
58
|
+
}
|
|
59
|
+
/** Build the inner action script data (UTF-16LE command payload). */
|
|
60
|
+
function buildWindowsLoginActionArgument(data) {
|
|
61
|
+
const script = [
|
|
62
|
+
"$ErrorActionPreference = 'Continue'",
|
|
63
|
+
`$f = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(JSON.stringify(data), "utf8").toString("base64")}')) | ConvertFrom-Json`,
|
|
64
|
+
"$env:DSH_HOME = [string]$f.home",
|
|
65
|
+
"$LASTEXITCODE = $null",
|
|
66
|
+
"& ([string]$f.node) ([string]$f.cli) --profile ([string]$f.profile) daemon start",
|
|
67
|
+
"$code = $LASTEXITCODE",
|
|
68
|
+
"if ($null -eq $code) { exit 1 }",
|
|
69
|
+
"exit $code"
|
|
70
|
+
].join("\n");
|
|
71
|
+
return `-NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
|
|
72
|
+
}
|
|
73
|
+
/** The fixed outer native-script prefix; the operation payload is data only. */
|
|
74
|
+
const NATIVE_SCRIPT_PREFIX = String.raw`$ErrorActionPreference = 'Stop'
|
|
75
|
+
[Console]::OutputEncoding = [Text.Encoding]::UTF8
|
|
76
|
+
function Hex([int32]$value) { return ('0x{0:X8}' -f ([BitConverter]::ToUInt32([BitConverter]::GetBytes($value), 0))) }
|
|
77
|
+
function ActualHResult($exception) {
|
|
78
|
+
$outer = $null
|
|
79
|
+
if ($exception.HResult) { $outer = Hex $exception.HResult }
|
|
80
|
+
$inner = $exception.InnerException
|
|
81
|
+
$innerHr = $null
|
|
82
|
+
if ($inner -and $inner.HResult) { $innerHr = Hex $inner.HResult }
|
|
83
|
+
if ($innerHr) { return [ordered]@{ hresult = $innerHr; outerHresult = $outer; innerHresult = $innerHr } }
|
|
84
|
+
return [ordered]@{ hresult = $outer; outerHresult = $outer; innerHresult = $null }
|
|
85
|
+
}
|
|
86
|
+
function Exact([string]$left, [string]$right) { return [string]::Equals($left, $right, [StringComparison]::Ordinal) }
|
|
87
|
+
function Emit($value) { [Console]::Out.Write(($value | ConvertTo-Json -Compress -Depth 8)) }
|
|
88
|
+
function Get-ExactTask([string]$name) {
|
|
89
|
+
try {
|
|
90
|
+
$task = $folder.GetTask($name)
|
|
91
|
+
return [ordered]@{ present = $true; task = $task; hresult = $null }
|
|
92
|
+
} catch {
|
|
93
|
+
$hr = ActualHResult $_.Exception
|
|
94
|
+
return [ordered]@{ present = $false; task = $null; hresult = $hr.hresult; outerHresult = $hr.outerHresult; innerHresult = $hr.innerHresult }
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function Get-Identity($task) {
|
|
98
|
+
$principalUserId = [string]$task.Definition.Principal.UserId
|
|
99
|
+
$principalSid = $null
|
|
100
|
+
try { $principalSid = ([Security.Principal.NTAccount]::new($principalUserId)).Translate([Security.Principal.SecurityIdentifier]).Value } catch { $principalSid = $null }
|
|
101
|
+
return [ordered]@{
|
|
102
|
+
name = [string]$task.Name
|
|
103
|
+
path = [string]$task.Path
|
|
104
|
+
description = [string]$task.Definition.RegistrationInfo.Description
|
|
105
|
+
principalUserId = $principalUserId
|
|
106
|
+
principalSid = $principalSid
|
|
107
|
+
state = [int]$task.State
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
$committed = $false
|
|
111
|
+
$payload = $null
|
|
112
|
+
try {
|
|
113
|
+
$payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__')) | ConvertFrom-Json
|
|
114
|
+
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
|
115
|
+
$account = $identity.Name
|
|
116
|
+
$sid = $identity.User.Value
|
|
117
|
+
$elevated = (New-Object Security.Principal.WindowsPrincipal($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
|
118
|
+
if ($elevated) { Emit ([ordered]@{ kind = 'refused'; reason = 'elevated' }); exit 0 }
|
|
119
|
+
$service = New-Object -ComObject 'Schedule.Service'
|
|
120
|
+
$service.Connect()
|
|
121
|
+
$folder = $service.GetFolder('\')
|
|
122
|
+
switch ([string]$payload.op) {
|
|
123
|
+
'inspect' {
|
|
124
|
+
$observed = Get-ExactTask ([string]$payload.taskName)
|
|
125
|
+
if (-not $observed.present) {
|
|
126
|
+
if ($observed.hresult -eq '0x80070002') { Emit ([ordered]@{ kind = 'absent'; hresult = $observed.hresult; outerHresult = $observed.outerHresult; innerHresult = $observed.innerHresult }) }
|
|
127
|
+
else { Emit ([ordered]@{ kind = 'error'; phase = 'get-task'; hresult = $observed.hresult }) }
|
|
128
|
+
} else {
|
|
129
|
+
Emit ([ordered]@{ kind = 'existing'; identity = (Get-Identity $observed.task) })
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
'install' {
|
|
133
|
+
$observed = Get-ExactTask ([string]$payload.taskName)
|
|
134
|
+
if (-not $observed.present -and $observed.hresult -ne '0x80070002') {
|
|
135
|
+
Emit ([ordered]@{ kind = 'error'; phase = 'get-task'; hresult = $observed.hresult })
|
|
136
|
+
exit 0
|
|
137
|
+
}
|
|
138
|
+
if ($observed.present) {
|
|
139
|
+
Emit ([ordered]@{ kind = 'exists'; identity = (Get-Identity $observed.task) })
|
|
140
|
+
exit 0
|
|
141
|
+
}
|
|
142
|
+
$definition = $service.NewTask(0)
|
|
143
|
+
$definition.RegistrationInfo.Description = [string]$payload.description
|
|
144
|
+
$definition.Principal.UserId = $account
|
|
145
|
+
$definition.Principal.LogonType = 3
|
|
146
|
+
$definition.Principal.RunLevel = 0
|
|
147
|
+
$trigger = $definition.Triggers.Create(9)
|
|
148
|
+
$trigger.UserId = $account
|
|
149
|
+
$trigger.Enabled = $true
|
|
150
|
+
$action = $definition.Actions.Create(0)
|
|
151
|
+
$action.Path = [string]$payload.action.path
|
|
152
|
+
$action.Arguments = [string]$payload.action.arguments
|
|
153
|
+
$action.WorkingDirectory = [string]$payload.action.workingDirectory
|
|
154
|
+
$definition.Settings.Enabled = $true
|
|
155
|
+
$definition.Settings.MultipleInstances = 2
|
|
156
|
+
$definition.Settings.ExecutionTimeLimit = 'PT5M'
|
|
157
|
+
$definition.Settings.DisallowStartIfOnBatteries = $false
|
|
158
|
+
$definition.Settings.StopIfGoingOnBatteries = $false
|
|
159
|
+
$definition.Settings.RunOnlyIfIdle = $false
|
|
160
|
+
$definition.Settings.RunOnlyIfNetworkAvailable = $false
|
|
161
|
+
$definition.Settings.AllowDemandStart = $true
|
|
162
|
+
$definition.Settings.RestartCount = 0
|
|
163
|
+
$definition.Settings.StartWhenAvailable = $false
|
|
164
|
+
$committed = $true
|
|
165
|
+
try {
|
|
166
|
+
$registered = $folder.RegisterTaskDefinition([string]$payload.taskName, $definition, 2, $account, $null, 3, $null)
|
|
167
|
+
} catch {
|
|
168
|
+
$hr = ActualHResult $_.Exception
|
|
169
|
+
$hresult = $hr.hresult
|
|
170
|
+
$afterRegister = Get-ExactTask ([string]$payload.taskName)
|
|
171
|
+
if ($afterRegister.present) {
|
|
172
|
+
Emit ([ordered]@{ kind = 'collision'; hresult = $hresult; identity = (Get-Identity $afterRegister.task) })
|
|
173
|
+
} elseif ($afterRegister.hresult -eq '0x80070002') {
|
|
174
|
+
Emit ([ordered]@{ kind = 'error'; phase = 'register'; hresult = $hresult })
|
|
175
|
+
} else {
|
|
176
|
+
Emit ([ordered]@{ kind = 'uncertain'; phase = 'register-readback'; hresult = $afterRegister.hresult })
|
|
177
|
+
}
|
|
178
|
+
exit 0
|
|
179
|
+
}
|
|
180
|
+
Emit ([ordered]@{ kind = 'created'; identity = (Get-Identity $registered) })
|
|
181
|
+
}
|
|
182
|
+
'uninstall' {
|
|
183
|
+
$observed = Get-ExactTask ([string]$payload.taskName)
|
|
184
|
+
if (-not $observed.present) {
|
|
185
|
+
if ($observed.hresult -eq '0x80070002') { Emit ([ordered]@{ kind = 'absent'; hresult = $observed.hresult; outerHresult = $observed.outerHresult; innerHresult = $observed.innerHresult }) }
|
|
186
|
+
else { Emit ([ordered]@{ kind = 'error'; phase = 'get-task'; hresult = $observed.hresult }) }
|
|
187
|
+
exit 0
|
|
188
|
+
}
|
|
189
|
+
$before = Get-Identity $observed.task
|
|
190
|
+
$owned = (Exact $before.name ([string]$payload.taskName)) -and (Exact $before.path ('\' + [string]$payload.taskName)) -and (Exact $before.description ([string]$payload.description)) -and (Exact $before.principalSid $sid)
|
|
191
|
+
if (-not $owned) { Emit ([ordered]@{ kind = 'refused'; identity = $before }); exit 0 }
|
|
192
|
+
if ($before.state -ne 1 -and $before.state -ne 3) { Emit ([ordered]@{ kind = 'busy'; identity = $before }); exit 0 }
|
|
193
|
+
$recheck = Get-ExactTask ([string]$payload.taskName)
|
|
194
|
+
if (-not $recheck.present) {
|
|
195
|
+
if ($recheck.hresult -eq '0x80070002') { Emit ([ordered]@{ kind = 'absent'; hresult = $recheck.hresult; outerHresult = $recheck.outerHresult; innerHresult = $recheck.innerHresult }) }
|
|
196
|
+
else { Emit ([ordered]@{ kind = 'error'; phase = 'recheck'; hresult = $recheck.hresult }) }
|
|
197
|
+
exit 0
|
|
198
|
+
}
|
|
199
|
+
$current = Get-Identity $recheck.task
|
|
200
|
+
$same = (Exact $current.name $before.name) -and (Exact $current.path $before.path) -and (Exact $current.description $before.description) -and (Exact $current.principalSid $before.principalSid) -and ($current.state -eq $before.state)
|
|
201
|
+
if (-not $same) { Emit ([ordered]@{ kind = 'uncertain'; reason = 'changed' }); exit 0 }
|
|
202
|
+
$committed = $true
|
|
203
|
+
try {
|
|
204
|
+
$folder.DeleteTask([string]$payload.taskName, 0)
|
|
205
|
+
} catch {
|
|
206
|
+
$hr = ActualHResult $_.Exception
|
|
207
|
+
$hresult = $hr.hresult
|
|
208
|
+
$afterDelete = Get-ExactTask ([string]$payload.taskName)
|
|
209
|
+
Emit ([ordered]@{ kind = 'delete-error'; hresult = $hresult; after = [ordered]@{ present = $afterDelete.present; hresult = $afterDelete.hresult; identity = $(if ($afterDelete.present) { Get-Identity $afterDelete.task } else { $null }) } })
|
|
210
|
+
exit 0
|
|
211
|
+
}
|
|
212
|
+
$after = Get-ExactTask ([string]$payload.taskName)
|
|
213
|
+
if (-not $after.present -and $after.hresult -eq '0x80070002') {
|
|
214
|
+
Emit ([ordered]@{ kind = 'deleted'; identity = $before })
|
|
215
|
+
} else {
|
|
216
|
+
Emit ([ordered]@{ kind = 'uncertain'; phase = 'post-delete'; hresult = $after.hresult })
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
default {
|
|
220
|
+
Emit ([ordered]@{ kind = 'error'; phase = 'payload'; hresult = $null })
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
} catch {
|
|
224
|
+
$hr = ActualHResult $_.Exception
|
|
225
|
+
$hresult = $hr.hresult
|
|
226
|
+
if ($committed) { Emit ([ordered]@{ kind = 'uncertain'; phase = 'exception'; hresult = $hresult; outerHresult = $hr.outerHresult; innerHresult = $hr.innerHresult }) }
|
|
227
|
+
else { Emit ([ordered]@{ kind = 'error'; phase = 'exception'; hresult = $hresult }) }
|
|
228
|
+
}
|
|
229
|
+
exit 0`;
|
|
230
|
+
/** Build one outer native script; the payload is base64 UTF-8 JSON data. */
|
|
231
|
+
function buildNativeScript(payload) {
|
|
232
|
+
const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
|
|
233
|
+
return NATIVE_SCRIPT_PREFIX.replace("__PAYLOAD__", encoded);
|
|
234
|
+
}
|
|
235
|
+
/** The production system Windows PowerShell path from kernel32, never the environment. */
|
|
236
|
+
function defaultSystemPowerShell() {
|
|
237
|
+
const systemDirectory = win32SystemDirectory();
|
|
238
|
+
if (systemDirectory === void 0) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the Windows system directory is unavailable");
|
|
239
|
+
return join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
240
|
+
}
|
|
241
|
+
/** The production system-PowerShell runner, with a bounded process. */
|
|
242
|
+
const runWindowsPowerShell = async (executable, args) => {
|
|
243
|
+
try {
|
|
244
|
+
if (!lstatSync(executable).isFile()) return {
|
|
245
|
+
kind: "spawn-error",
|
|
246
|
+
error: Object.assign(/* @__PURE__ */ new Error("system Windows PowerShell is not a regular file"), { code: "ENOENT" })
|
|
247
|
+
};
|
|
248
|
+
} catch (error) {
|
|
249
|
+
return {
|
|
250
|
+
kind: "spawn-error",
|
|
251
|
+
error
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
return await new Promise((resolve) => {
|
|
255
|
+
let child;
|
|
256
|
+
child = execFile(executable, [...args], {
|
|
257
|
+
timeout: WINDOWS_LOGIN_TIMEOUT_MS,
|
|
258
|
+
maxBuffer: WINDOWS_LOGIN_MAX_OUTPUT_BYTES,
|
|
259
|
+
encoding: "utf8",
|
|
260
|
+
windowsHide: true
|
|
261
|
+
}, (error, stdout, stderr) => {
|
|
262
|
+
if (error !== null && error !== void 0) {
|
|
263
|
+
const failure = error;
|
|
264
|
+
if (failure.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
|
|
265
|
+
resolve({ kind: "output-overflow" });
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (failure.killed === true || failure.signal === "SIGTERM") {
|
|
269
|
+
resolve({ kind: "timeout" });
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (typeof failure.code === "number") {
|
|
273
|
+
resolve({
|
|
274
|
+
kind: "exited",
|
|
275
|
+
code: failure.code,
|
|
276
|
+
stdout: String(stdout),
|
|
277
|
+
stderr: String(stderr)
|
|
278
|
+
});
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
if (child?.pid === void 0) {
|
|
282
|
+
resolve({
|
|
283
|
+
kind: "spawn-error",
|
|
284
|
+
error: failure
|
|
285
|
+
});
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
resolve({
|
|
289
|
+
kind: "runner-error",
|
|
290
|
+
error: failure
|
|
291
|
+
});
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
resolve({
|
|
295
|
+
kind: "exited",
|
|
296
|
+
code: 0,
|
|
297
|
+
stdout: String(stdout),
|
|
298
|
+
stderr: String(stderr)
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
});
|
|
302
|
+
};
|
|
303
|
+
/** Prove one absolute regular file, returning its canonical target. */
|
|
304
|
+
function absoluteRegularFile(pathValue, label) {
|
|
305
|
+
if (!isAbsolute(pathValue)) throw new LocalScopeError("HOST_MANAGER_ERROR", `windows login: the ${label} must be an absolute path`);
|
|
306
|
+
try {
|
|
307
|
+
const real = realpathSync.native(pathValue);
|
|
308
|
+
if (!lstatSync(real).isFile()) throw new LocalScopeError("HOST_MANAGER_ERROR", `windows login: the ${label} must be a regular file`);
|
|
309
|
+
return real;
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (error instanceof LocalScopeError) throw error;
|
|
312
|
+
throw new LocalScopeError("HOST_MANAGER_ERROR", `windows login: the ${label} is not readable`, error);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/** Validate the current installed Node/official-CLI/Profile facts for a FRESH task. */
|
|
316
|
+
function freshFacts(profile, scope, deps) {
|
|
317
|
+
const node = absoluteRegularFile(deps.nodePath ?? process.execPath, "Node executable");
|
|
318
|
+
const anchor = installedDshManifest(profile.installAnchor);
|
|
319
|
+
if (anchor === void 0) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the installed DSH anchor is not an @deepseek-ai/dsh manifest");
|
|
320
|
+
const manifest = readManifestObject(anchor);
|
|
321
|
+
if (manifest === void 0 || manifest.version !== profile.dshVersion) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the installed DSH version does not match the profile");
|
|
322
|
+
const binField = manifest.bin;
|
|
323
|
+
const declaredBin = typeof binField === "string" ? binField : binField !== null && typeof binField === "object" && !Array.isArray(binField) && typeof binField.dsh === "string" ? binField.dsh : void 0;
|
|
324
|
+
if (declaredBin === void 0 || posix.normalize(declaredBin) !== OFFICIAL_DSH_BIN) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the installed DSH manifest does not declare the supported official dsh bin");
|
|
325
|
+
let packageDir;
|
|
326
|
+
try {
|
|
327
|
+
packageDir = realpathSync.native(dirname(anchor));
|
|
328
|
+
} catch (error) {
|
|
329
|
+
throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the installed DSH package directory is unavailable", error);
|
|
330
|
+
}
|
|
331
|
+
const cli = absoluteRegularFile(join(packageDir, OFFICIAL_DSH_BIN), "official dsh bin");
|
|
332
|
+
if (!cli.startsWith(`${packageDir}${sep}`)) throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the official dsh bin escapes its package");
|
|
333
|
+
const systemPowerShell = absoluteRegularFile(deps.systemPowerShell ?? defaultSystemPowerShell(), "system Windows PowerShell");
|
|
334
|
+
return {
|
|
335
|
+
action: {
|
|
336
|
+
path: systemPowerShell,
|
|
337
|
+
arguments: buildWindowsLoginActionArgument({
|
|
338
|
+
node,
|
|
339
|
+
cli,
|
|
340
|
+
home: scope.dshHome,
|
|
341
|
+
profile: profile.name
|
|
342
|
+
}),
|
|
343
|
+
workingDirectory: scope.profileRealpath
|
|
344
|
+
},
|
|
345
|
+
systemPowerShell
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
/** Resolve the current token SID or fail closed. */
|
|
349
|
+
function currentSidOf(deps) {
|
|
350
|
+
const sid = deps.currentSid ?? win32CurrentTokenSid();
|
|
351
|
+
if (sid === void 0 || sid === "") throw new LocalScopeError("HOST_MANAGER_ERROR", "windows login: the current token SID is unavailable");
|
|
352
|
+
return sid;
|
|
353
|
+
}
|
|
354
|
+
/** Run one native script with the injected/production runner. */
|
|
355
|
+
async function invokeNative(deps, script, executable) {
|
|
356
|
+
return await (deps.runPowerShell ?? runWindowsPowerShell)(executable, [
|
|
357
|
+
"-NoProfile",
|
|
358
|
+
"-NonInteractive",
|
|
359
|
+
"-EncodedCommand",
|
|
360
|
+
Buffer.from(script, "utf16le").toString("base64")
|
|
361
|
+
]);
|
|
362
|
+
}
|
|
363
|
+
/** Strictly parse one native JSON result; any extra/malformed output is undefined. */
|
|
364
|
+
function parseNativeOutput(result) {
|
|
365
|
+
if (result.kind !== "exited" || result.code !== 0) return void 0;
|
|
366
|
+
return parseJsonRecord(result.stdout);
|
|
367
|
+
}
|
|
368
|
+
function parseJsonRecord(text) {
|
|
369
|
+
const trimmed = text.replace(/^\uFEFF/u, "").trim();
|
|
370
|
+
if (trimmed === "") return void 0;
|
|
371
|
+
try {
|
|
372
|
+
const value = JSON.parse(trimmed);
|
|
373
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
374
|
+
} catch {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
/** Parse one identity object; a missing SID is a foreign/unresolved fact. */
|
|
379
|
+
function parseIdentity(value) {
|
|
380
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
381
|
+
const record = value;
|
|
382
|
+
const name = typeof record.name === "string" ? record.name : void 0;
|
|
383
|
+
const path = typeof record.path === "string" ? record.path : void 0;
|
|
384
|
+
const description = typeof record.description === "string" ? record.description : void 0;
|
|
385
|
+
const principalUserId = typeof record.principalUserId === "string" ? record.principalUserId : void 0;
|
|
386
|
+
const principalSid = typeof record.principalSid === "string" ? record.principalSid : void 0;
|
|
387
|
+
const state = typeof record.state === "number" && Number.isInteger(record.state) ? record.state : void 0;
|
|
388
|
+
if (name === void 0 || path === void 0 || description === void 0 || principalUserId === void 0 || state === void 0) return void 0;
|
|
389
|
+
return {
|
|
390
|
+
name,
|
|
391
|
+
path,
|
|
392
|
+
description,
|
|
393
|
+
principalUserId,
|
|
394
|
+
principalSid,
|
|
395
|
+
state
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
/** The identity predicate: exact task path/name/description/current-user SID. */
|
|
399
|
+
function isOwnedIdentity(identity, taskName, description, currentSid) {
|
|
400
|
+
return identity.name === taskName && identity.path === `\\${taskName}` && identity.description === description && identity.principalSid === currentSid;
|
|
401
|
+
}
|
|
402
|
+
/** The safe reason for an elevated/unknown native refusal. */
|
|
403
|
+
function safeReason(value, fallback) {
|
|
404
|
+
return typeof value === "string" && /^[a-z0-9-]{1,64}$/u.test(value) ? value : fallback;
|
|
405
|
+
}
|
|
406
|
+
/** Inspect the exact login task for one profile. */
|
|
407
|
+
async function inspectWindowsLoginTask(scope, deps = {}) {
|
|
408
|
+
const taskName = buildWindowsLoginTaskName(scope.scopeId);
|
|
409
|
+
const description = buildWindowsLoginDescription(scope.scopeId);
|
|
410
|
+
const sid = currentSidOf(deps);
|
|
411
|
+
let executable;
|
|
412
|
+
try {
|
|
413
|
+
executable = absoluteRegularFile(deps.systemPowerShell ?? defaultSystemPowerShell(), "system Windows PowerShell");
|
|
414
|
+
} catch {
|
|
415
|
+
return {
|
|
416
|
+
kind: "os-failure",
|
|
417
|
+
reason: "the system Windows PowerShell is unavailable"
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
try {
|
|
421
|
+
const output = parseNativeOutput(await invokeNative(deps, buildNativeScript({
|
|
422
|
+
op: "inspect",
|
|
423
|
+
taskName
|
|
424
|
+
}), executable));
|
|
425
|
+
if (output === void 0) return {
|
|
426
|
+
kind: "os-failure",
|
|
427
|
+
reason: "the Task Scheduler inspection did not return a valid result"
|
|
428
|
+
};
|
|
429
|
+
switch (output.kind) {
|
|
430
|
+
case "absent":
|
|
431
|
+
if (output.hresult !== TASK_NOT_FOUND_HRESULT) return {
|
|
432
|
+
kind: "os-failure",
|
|
433
|
+
reason: "the Task Scheduler inspection returned an unconfirmed missing task"
|
|
434
|
+
};
|
|
435
|
+
return {
|
|
436
|
+
kind: "absent",
|
|
437
|
+
hresult: TASK_NOT_FOUND_HRESULT
|
|
438
|
+
};
|
|
439
|
+
case "existing": {
|
|
440
|
+
const identity = parseIdentity(output.identity);
|
|
441
|
+
if (identity === void 0) return {
|
|
442
|
+
kind: "os-failure",
|
|
443
|
+
reason: "the existing Task Scheduler identity is malformed"
|
|
444
|
+
};
|
|
445
|
+
return isOwnedIdentity(identity, taskName, description, sid) ? {
|
|
446
|
+
kind: "owned",
|
|
447
|
+
taskName,
|
|
448
|
+
identity
|
|
449
|
+
} : {
|
|
450
|
+
kind: "foreign",
|
|
451
|
+
taskName,
|
|
452
|
+
identity
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
case "refused": return {
|
|
456
|
+
kind: "refused",
|
|
457
|
+
reason: safeReason(output.reason, "the Task Scheduler refused the operation")
|
|
458
|
+
};
|
|
459
|
+
default: return {
|
|
460
|
+
kind: "os-failure",
|
|
461
|
+
reason: "the Task Scheduler inspection failed"
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
} catch (error) {
|
|
465
|
+
if (error instanceof LocalScopeError) return {
|
|
466
|
+
kind: "os-failure",
|
|
467
|
+
reason: error.message
|
|
468
|
+
};
|
|
469
|
+
return {
|
|
470
|
+
kind: "os-failure",
|
|
471
|
+
reason: "the Task Scheduler inspection could not be completed"
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
/** Create one FRESH login task with COM TASK_CREATE (never overwrite). */
|
|
476
|
+
async function createWindowsLoginTask(scope, profile, deps = {}) {
|
|
477
|
+
const taskName = buildWindowsLoginTaskName(scope.scopeId);
|
|
478
|
+
const description = buildWindowsLoginDescription(scope.scopeId);
|
|
479
|
+
const sid = currentSidOf(deps);
|
|
480
|
+
let facts;
|
|
481
|
+
try {
|
|
482
|
+
facts = freshFacts(profile, scope, deps);
|
|
483
|
+
} catch (error) {
|
|
484
|
+
if (error instanceof LocalScopeError) return {
|
|
485
|
+
kind: "os-failure",
|
|
486
|
+
reason: error.message
|
|
487
|
+
};
|
|
488
|
+
return {
|
|
489
|
+
kind: "os-failure",
|
|
490
|
+
reason: "the current installed Node/DSH facts are unavailable"
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
let result;
|
|
494
|
+
try {
|
|
495
|
+
result = await invokeNative(deps, buildNativeScript({
|
|
496
|
+
op: "install",
|
|
497
|
+
taskName,
|
|
498
|
+
description,
|
|
499
|
+
action: facts.action
|
|
500
|
+
}), facts.systemPowerShell);
|
|
501
|
+
} catch {
|
|
502
|
+
return {
|
|
503
|
+
kind: "uncertain",
|
|
504
|
+
reason: "the Task Scheduler create request could not be confirmed"
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
if (result.kind === "spawn-error") return {
|
|
508
|
+
kind: "os-failure",
|
|
509
|
+
reason: "the Task Scheduler create PowerShell could not be started"
|
|
510
|
+
};
|
|
511
|
+
const output = parseNativeOutput(result);
|
|
512
|
+
if (output === void 0) return {
|
|
513
|
+
kind: "uncertain",
|
|
514
|
+
reason: "the Task Scheduler create request could not be confirmed"
|
|
515
|
+
};
|
|
516
|
+
switch (output.kind) {
|
|
517
|
+
case "created": {
|
|
518
|
+
const identity = parseIdentity(output.identity);
|
|
519
|
+
if (identity === void 0 || !isOwnedIdentity(identity, taskName, description, sid)) return {
|
|
520
|
+
kind: "uncertain",
|
|
521
|
+
reason: "the created Task Scheduler identity could not be confirmed"
|
|
522
|
+
};
|
|
523
|
+
return {
|
|
524
|
+
kind: "created",
|
|
525
|
+
taskName,
|
|
526
|
+
identity
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
case "exists":
|
|
530
|
+
case "collision": {
|
|
531
|
+
const identity = parseIdentity(output.identity);
|
|
532
|
+
if (identity === void 0) return {
|
|
533
|
+
kind: "uncertain",
|
|
534
|
+
reason: "the competing Task Scheduler identity is malformed"
|
|
535
|
+
};
|
|
536
|
+
return isOwnedIdentity(identity, taskName, description, sid) ? {
|
|
537
|
+
kind: "reused",
|
|
538
|
+
taskName,
|
|
539
|
+
identity
|
|
540
|
+
} : {
|
|
541
|
+
kind: "foreign",
|
|
542
|
+
taskName,
|
|
543
|
+
identity
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
case "refused": return {
|
|
547
|
+
kind: "refused",
|
|
548
|
+
reason: safeReason(output.reason, "the Task Scheduler refused the operation")
|
|
549
|
+
};
|
|
550
|
+
case "uncertain": return {
|
|
551
|
+
kind: "uncertain",
|
|
552
|
+
reason: "the Task Scheduler create request may already be committed"
|
|
553
|
+
};
|
|
554
|
+
default: return {
|
|
555
|
+
kind: "os-failure",
|
|
556
|
+
reason: "the Task Scheduler create request failed"
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/** Uninstall the exact login task; missing is an idempotent absence. */
|
|
561
|
+
async function uninstallWindowsLoginTask(scope, profile, deps = {}) {
|
|
562
|
+
const taskName = buildWindowsLoginTaskName(scope.scopeId);
|
|
563
|
+
const description = buildWindowsLoginDescription(scope.scopeId);
|
|
564
|
+
const sid = currentSidOf(deps);
|
|
565
|
+
let executable;
|
|
566
|
+
try {
|
|
567
|
+
executable = absoluteRegularFile(deps.systemPowerShell ?? defaultSystemPowerShell(), "system Windows PowerShell");
|
|
568
|
+
} catch {
|
|
569
|
+
return {
|
|
570
|
+
kind: "os-failure",
|
|
571
|
+
reason: "the system Windows PowerShell is unavailable"
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
let result;
|
|
575
|
+
try {
|
|
576
|
+
result = await invokeNative(deps, buildNativeScript({
|
|
577
|
+
op: "uninstall",
|
|
578
|
+
taskName,
|
|
579
|
+
description
|
|
580
|
+
}), executable);
|
|
581
|
+
} catch {
|
|
582
|
+
return {
|
|
583
|
+
kind: "uncertain",
|
|
584
|
+
reason: WINDOWS_UNINSTALL_UNCERTAIN
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
if (result.kind === "spawn-error") return {
|
|
588
|
+
kind: "os-failure",
|
|
589
|
+
reason: "the Task Scheduler uninstall PowerShell could not be started"
|
|
590
|
+
};
|
|
591
|
+
const output = parseNativeOutput(result);
|
|
592
|
+
if (output === void 0) return {
|
|
593
|
+
kind: "uncertain",
|
|
594
|
+
reason: WINDOWS_UNINSTALL_UNCERTAIN
|
|
595
|
+
};
|
|
596
|
+
switch (output.kind) {
|
|
597
|
+
case "absent":
|
|
598
|
+
if (output.hresult !== TASK_NOT_FOUND_HRESULT) return {
|
|
599
|
+
kind: "os-failure",
|
|
600
|
+
reason: "the Task Scheduler uninstall absence was not confirmed"
|
|
601
|
+
};
|
|
602
|
+
return { kind: "absent" };
|
|
603
|
+
case "deleted": {
|
|
604
|
+
const identity = parseIdentity(output.identity);
|
|
605
|
+
if (identity === void 0 || !isOwnedIdentity(identity, taskName, description, sid)) return {
|
|
606
|
+
kind: "uncertain",
|
|
607
|
+
reason: WINDOWS_UNINSTALL_UNCERTAIN
|
|
608
|
+
};
|
|
609
|
+
return { kind: "deleted" };
|
|
610
|
+
}
|
|
611
|
+
case "refused": return {
|
|
612
|
+
kind: "refused",
|
|
613
|
+
reason: safeReason(output.reason, "the Task Scheduler refused the operation")
|
|
614
|
+
};
|
|
615
|
+
case "busy": {
|
|
616
|
+
const state = parseIdentity(output.identity)?.state;
|
|
617
|
+
if (state === void 0) return {
|
|
618
|
+
kind: "uncertain",
|
|
619
|
+
reason: WINDOWS_UNINSTALL_UNCERTAIN
|
|
620
|
+
};
|
|
621
|
+
return {
|
|
622
|
+
kind: "busy",
|
|
623
|
+
state,
|
|
624
|
+
reason: "the login task is running or queued; wait for the short action to settle and retry"
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
case "delete-error": {
|
|
628
|
+
const after = output.after !== null && typeof output.after === "object" && !Array.isArray(output.after) ? output.after : void 0;
|
|
629
|
+
if (after !== void 0 && after.present === true) {
|
|
630
|
+
const identity = parseIdentity(after.identity);
|
|
631
|
+
if (identity !== void 0 && isOwnedIdentity(identity, taskName, description, sid) && (identity.state === TASK_STATE_READY || identity.state === TASK_STATE_DISABLED)) return {
|
|
632
|
+
kind: "os-failure",
|
|
633
|
+
reason: "the Task Scheduler delete failed and the owned task remains"
|
|
634
|
+
};
|
|
635
|
+
return {
|
|
636
|
+
kind: "uncertain",
|
|
637
|
+
reason: WINDOWS_UNINSTALL_UNCERTAIN
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
if (after !== void 0 && after.present === false && after.hresult === TASK_NOT_FOUND_HRESULT) return { kind: "deleted" };
|
|
641
|
+
return {
|
|
642
|
+
kind: "uncertain",
|
|
643
|
+
reason: WINDOWS_UNINSTALL_UNCERTAIN
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
case "error": return {
|
|
647
|
+
kind: "os-failure",
|
|
648
|
+
reason: "the Task Scheduler uninstall failed"
|
|
649
|
+
};
|
|
650
|
+
default: return {
|
|
651
|
+
kind: "uncertain",
|
|
652
|
+
reason: WINDOWS_UNINSTALL_UNCERTAIN
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
//#endregion
|
|
657
|
+
//#region src/app/remote-process/local-acp-endpoint.ts
|
|
658
|
+
/**
|
|
659
|
+
* The one transport-neutral description of the local ACP endpoint name.
|
|
660
|
+
*
|
|
661
|
+
* POSIX keeps the existing pathname Unix socket contract (Linux/Darwin derive
|
|
662
|
+
* it in the listener module). Native Windows uses one profile-scoped Named
|
|
663
|
+
* Pipe address derived from the existing canonical scope id: this module owns
|
|
664
|
+
* only the pure shape/validation and performs no IO, so the listener, the
|
|
665
|
+
* daemon-control reader and the standalone stdio entry share exactly one
|
|
666
|
+
* definition without pulling Host or SDK side effects into the byte relay.
|
|
667
|
+
*
|
|
668
|
+
* @module app/remote-process/local-acp-endpoint
|
|
669
|
+
*/
|
|
670
|
+
/** The exact local Windows Named Pipe prefix of this product. */
|
|
671
|
+
const ACP_PIPE_PREFIX = "\\\\.\\pipe\\dsh-pi-tui-acp-";
|
|
672
|
+
/** The canonical local Named Pipe address of one existing profile scope. The
|
|
673
|
+
* scope id comes from the internal canonical scope producer; external addresses
|
|
674
|
+
* are admitted only through {@link isAcpPipeAddress}. */
|
|
675
|
+
function acpPipeAddress(scopeId) {
|
|
676
|
+
return `${ACP_PIPE_PREFIX}${scopeId}`;
|
|
677
|
+
}
|
|
678
|
+
JSON.stringify(["unset"]);
|
|
679
|
+
Object.freeze([{
|
|
680
|
+
id: "default",
|
|
681
|
+
name: "Default",
|
|
682
|
+
description: "Normal collaboration mode."
|
|
683
|
+
}, {
|
|
684
|
+
id: "plan",
|
|
685
|
+
name: "Plan",
|
|
686
|
+
description: "Plan and review before implementation; does not change sandbox or approval policy."
|
|
687
|
+
}]);
|
|
688
|
+
//#endregion
|
|
689
|
+
//#region src/app/remote-process/local-acp-listener.ts
|
|
690
|
+
/** The logical socket file name inside the 0700 scope directory. */
|
|
691
|
+
const SOCKET_FILE = "acp.sock";
|
|
692
|
+
/** Owner-only private subdirectory (inside the 0700 scope) where the server is
|
|
693
|
+
* actually BOUND before its inode is hard-linked onto the contract path. Node's
|
|
694
|
+
* server.close() unlink always targets this private dir, so it can never delete
|
|
695
|
+
* a foreign inode at the contract path. */
|
|
696
|
+
const PRIVATE_DIR = ".acp-priv";
|
|
697
|
+
/** The trusted, OS-owned sticky parent of the Darwin profile-scoped endpoint. Never
|
|
698
|
+
* `$TMPDIR`, `DSH_HOME` or the user home: those are variable and unbounded. */
|
|
699
|
+
const DARWIN_SOCKET_PARENT = "/private/tmp";
|
|
700
|
+
/** Darwin `sockaddr_un.sun_path` capacity in bytes INCLUDING the trailing NUL. */
|
|
701
|
+
const DARWIN_SUN_PATH_BYTES = 104;
|
|
702
|
+
/** Prefix of the one deterministic Darwin endpoint root per profile scope. */
|
|
703
|
+
const DARWIN_ROOT_PREFIX = "dpt-";
|
|
704
|
+
/** Scope-id hex characters kept in the Darwin root name (the existing 160-bit
|
|
705
|
+
* collision budget the local seats already use). */
|
|
706
|
+
const DARWIN_SCOPE_PREFIX_HEX = 40;
|
|
707
|
+
`${JSON.stringify({
|
|
708
|
+
jsonrpc: "2.0",
|
|
709
|
+
id: null,
|
|
710
|
+
error: {
|
|
711
|
+
code: -32041,
|
|
712
|
+
message: "ACP connection capacity exceeded",
|
|
713
|
+
data: { code: "LOCAL_ACP_CAPACITY_EXCEEDED" }
|
|
714
|
+
}
|
|
715
|
+
})}`;
|
|
716
|
+
/** A startup failure that carries one stable local-ACP classification code. */
|
|
717
|
+
var LocalAcpError = class extends Error {
|
|
718
|
+
/** Stable classification asserted by the Host entry failure record. */
|
|
719
|
+
code;
|
|
720
|
+
constructor(code, message, cause) {
|
|
721
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
722
|
+
this.name = "LocalAcpError";
|
|
723
|
+
this.code = code;
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
/**
|
|
727
|
+
* Compute the FROZEN Darwin endpoint from the real profile scope id and the
|
|
728
|
+
* current OS uid: `/private/tmp/dpt-<decimal-uid>-<scope40>` holds one 0700 root
|
|
729
|
+
* whose `acp.sock` is the public address and whose `.acp-priv/acp.sock` is the
|
|
730
|
+
* private bind name. No configuration, environment variable or user path can
|
|
731
|
+
* change it, and both names must fit `sun_path[104]` INCLUDING the NUL. The
|
|
732
|
+
* caller creates/admits the root; this function performs no filesystem IO.
|
|
733
|
+
*
|
|
734
|
+
* @param scope - the canonical profile scope (its `scopeId` is a 64-hex SHA-256).
|
|
735
|
+
* @param uid - the current process uid; the root is scoped to this exact uid.
|
|
736
|
+
* @returns the public, root and private bind pathnames.
|
|
737
|
+
* @throws {LocalAcpError} `LOCAL_ACP_SOCKET_PATH_UNSUPPORTED` when a name exceeds
|
|
738
|
+
* the Darwin kernel path capacity.
|
|
739
|
+
*/
|
|
740
|
+
function darwinAcpSocketPaths(scope, uid) {
|
|
741
|
+
const privateRoot = join(DARWIN_SOCKET_PARENT, `${DARWIN_ROOT_PREFIX}${String(uid)}-${scope.scopeId.slice(0, DARWIN_SCOPE_PREFIX_HEX)}`);
|
|
742
|
+
const publicPath = join(privateRoot, SOCKET_FILE);
|
|
743
|
+
const privateBindPath = join(privateRoot, PRIVATE_DIR, SOCKET_FILE);
|
|
744
|
+
if (Buffer.byteLength(publicPath, "utf8") + 1 > DARWIN_SUN_PATH_BYTES || Buffer.byteLength(privateBindPath, "utf8") + 1 > DARWIN_SUN_PATH_BYTES) throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the Darwin endpoint exceeds the kernel sun_path byte limit");
|
|
745
|
+
return {
|
|
746
|
+
publicPath,
|
|
747
|
+
privateRoot,
|
|
748
|
+
privateBindPath
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
//#endregion
|
|
752
|
+
//#region src/app/remote-process/local-daemon-control.ts
|
|
753
|
+
/**
|
|
754
|
+
* The M6-2C daemon management control plane.
|
|
755
|
+
*
|
|
756
|
+
* This is the ONE module that turns a typed `DaemonControlIntent` into a real
|
|
757
|
+
* local OS observation or an explicit supervision transition for ONE official
|
|
758
|
+
* Profile. It owns no Host business object: Host readiness is always the
|
|
759
|
+
* existing authenticated `/connect` Cookie + identity echo + fresh kernel
|
|
760
|
+
* identity handshake (Linux `/proc` starttime, macOS Darwin schema 2), and a
|
|
761
|
+
* Host stop remains the existing `runProfile` shutdown owner reached either
|
|
762
|
+
* through the verified profile unit's manager SIGTERM, a verified user-level
|
|
763
|
+
* launchd job's `bootout`, or a single verified-PID POSIX SIGTERM when the
|
|
764
|
+
* authenticated Host is independent.
|
|
765
|
+
*
|
|
766
|
+
* `status` and `logs` are strictly read-only: they never create the profile run
|
|
767
|
+
* directory, never write a service definition, never start a Host and never
|
|
768
|
+
* touch a Session. The mutating verbs (start, stop, restart, install, uninstall,
|
|
769
|
+
* enable and disable) are serialized by one short-lived profile-scoped admin
|
|
770
|
+
* seat: Linux holds the abstract-socket name, macOS holds the Darwin `O_EXLOCK` `admin` seat
|
|
771
|
+
* file beside the Host singleton seat. The kernel releases it when the command
|
|
772
|
+
* dies, so there is no persistent lock file or second state machine.
|
|
773
|
+
*
|
|
774
|
+
* @module app/remote-process/local-daemon-control
|
|
775
|
+
*/
|
|
776
|
+
/** The fixed exit class of every stable code. */
|
|
777
|
+
const EXIT_CODE = {
|
|
778
|
+
UNSUPPORTED_PLATFORM: 3,
|
|
779
|
+
IDENTITY_OR_OWNERSHIP_REFUSED: 3,
|
|
780
|
+
MANAGER_OR_OS_FAILURE: 4,
|
|
781
|
+
LOG_SOURCE_UNAVAILABLE: 4,
|
|
782
|
+
DAEMON_CONTROL_BUSY: 5,
|
|
783
|
+
TRANSITION_UNCERTAIN: 5
|
|
784
|
+
};
|
|
785
|
+
/** A management failure carrying the stable code and exit class. */
|
|
786
|
+
var DaemonControlError = class extends Error {
|
|
787
|
+
code;
|
|
788
|
+
exitCode;
|
|
789
|
+
reason;
|
|
790
|
+
constructor(code, reason, cause) {
|
|
791
|
+
super(reason, cause === void 0 ? void 0 : { cause });
|
|
792
|
+
this.name = "DaemonControlError";
|
|
793
|
+
this.code = code;
|
|
794
|
+
this.exitCode = EXIT_CODE[code];
|
|
795
|
+
this.reason = reason;
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
/** The fixed one-line error format; never a raw Error message or argv. */
|
|
799
|
+
function formatDaemonControlError(error) {
|
|
800
|
+
return `dsh-pi-tui daemon: ${error.code}: ${sanitizeReason(error.reason)}\n`;
|
|
801
|
+
}
|
|
802
|
+
/** Visible risk reminder printed beside log output. */
|
|
803
|
+
const LOG_SANITIZATION_NOTICE = "dsh-pi-tui daemon: note: log output is best-effort sanitized; review it before sharing\n";
|
|
804
|
+
/** The fixed running-work warning every mutating verb prints on success. */
|
|
805
|
+
const RUNNING_WORK_NOTICE = "dsh-pi-tui daemon: note: stopping or restarting the Host may interrupt a running Session, Job or Interaction; unsettled writes are not replayed automatically\n";
|
|
806
|
+
/** The fixed note for an existing Windows login task that was preserved. */
|
|
807
|
+
const WINDOWS_EXISTING_DEFINITION_NOTE = "dsh-pi-tui daemon: note: existing definition preserved; --autostart applies only to a new installation\n";
|
|
808
|
+
/** The admin seat prefix; the kernel releases the abstract name on process death. */
|
|
809
|
+
const ADMIN_SEAT_PREFIX = "\0dsh-pi-tui-admin-";
|
|
810
|
+
/** Bound on one journalctl invocation. */
|
|
811
|
+
const JOURNALCTL_TIMEOUT_MS = 1e4;
|
|
812
|
+
/** Hard cap on captured journal output. */
|
|
813
|
+
const JOURNAL_MAX_OUTPUT_BYTES = 262144;
|
|
814
|
+
/** Bound on one scope host.log tail read (from the end of the file). */
|
|
815
|
+
const HOST_LOG_MAX_BYTES = 262144;
|
|
816
|
+
/** Bound on one displayed log line. */
|
|
817
|
+
const MAX_LOG_LINE_LENGTH = 2e3;
|
|
818
|
+
/** The fixed journal executable. */
|
|
819
|
+
const JOURNALCTL = "journalctl";
|
|
820
|
+
/** Stable truncation marker for bounded log reads. */
|
|
821
|
+
const LOG_TRUNCATION_MARKER = "[dsh-pi-tui daemon: log output truncated]";
|
|
822
|
+
/** Replace absolute paths and control characters in a human reason. */
|
|
823
|
+
function sanitizeReason(text) {
|
|
824
|
+
return (text.split(/\r?\n/u).map((part) => part.trim()).find((part) => part !== "") ?? "").replace(/\/[^\s"']+/gu, "<path>").replace(/https?:\/\/[^\s"']+/giu, "<url>").replace(/[\u0000-\u001f\u007f]/gu, "").slice(0, 200);
|
|
825
|
+
}
|
|
826
|
+
/** Map a lower-level stable failure onto the management error taxonomy. */
|
|
827
|
+
function toDaemonControlError(error) {
|
|
828
|
+
if (error instanceof DaemonControlError) return error;
|
|
829
|
+
if (error instanceof LocalScopeError) switch (error.code) {
|
|
830
|
+
case "B1_PLATFORM_UNSUPPORTED": return new DaemonControlError("UNSUPPORTED_PLATFORM", "this daemon command requires Linux, macOS or Windows");
|
|
831
|
+
case "HOST_MANAGER_UNIT_CONFLICT":
|
|
832
|
+
case "HOST_IDENTITY_MISMATCH":
|
|
833
|
+
case "HOST_PROTOCOL_INCOMPATIBLE":
|
|
834
|
+
case "HOST_BUILD_INCOMPATIBLE":
|
|
835
|
+
case "HOST_AUTH_FAILED":
|
|
836
|
+
case "SCOPE_DIRECTORY_UNSAFE":
|
|
837
|
+
case "LOCAL_FILE_UNSAFE":
|
|
838
|
+
case "PROCESS_STARTTIME_UNAVAILABLE": return new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", error.message, error);
|
|
839
|
+
case "HOST_STOP_TIMEOUT": return new DaemonControlError("TRANSITION_UNCERTAIN", error.message, error);
|
|
840
|
+
case "HOST_START_TIMEOUT": return afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", error.message, error), "Host start");
|
|
841
|
+
case "DAEMON_CONTROL_BUSY": return new DaemonControlError("DAEMON_CONTROL_BUSY", "another daemon control operation is already running for this profile", error);
|
|
842
|
+
case "HOST_UNRESPONSIVE": return new DaemonControlError("MANAGER_OR_OS_FAILURE", error.message, error);
|
|
843
|
+
default: return new DaemonControlError("MANAGER_OR_OS_FAILURE", error.message, error);
|
|
844
|
+
}
|
|
845
|
+
return new DaemonControlError("MANAGER_OR_OS_FAILURE", "an unexpected local management failure occurred", error);
|
|
846
|
+
}
|
|
847
|
+
/** Add recovery context only to a completed operation's failed confirmation. */
|
|
848
|
+
function afterCommittedAction(failure, action) {
|
|
849
|
+
return new DaemonControlError(failure.code, `${action} may already be committed; final verification failed. Run daemon status before retrying. ${failure.reason}`, failure);
|
|
850
|
+
}
|
|
851
|
+
/** Throw when the supervisor is shutting down and the operation must settle. */
|
|
852
|
+
function assertNotAborted(signal) {
|
|
853
|
+
if (signal !== void 0 && signal.aborted) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the management operation was cancelled by supervisor shutdown");
|
|
854
|
+
}
|
|
855
|
+
/** The effective platform/uid inputs. */
|
|
856
|
+
function platformOf(deps) {
|
|
857
|
+
return deps.platform ?? process.platform;
|
|
858
|
+
}
|
|
859
|
+
function uidOf(deps) {
|
|
860
|
+
const uid = deps.uid ?? (typeof process.getuid === "function" ? process.getuid() : void 0);
|
|
861
|
+
if (uid === void 0) throw new DaemonControlError("UNSUPPORTED_PLATFORM", "this daemon command requires a local user identity");
|
|
862
|
+
return uid;
|
|
863
|
+
}
|
|
864
|
+
/** Compute the read-only scope; no directory is created. */
|
|
865
|
+
function inspectScope(profile, deps) {
|
|
866
|
+
const platform = platformOf(deps);
|
|
867
|
+
if (platform !== "linux" && platform !== "darwin" && platform !== "win32") throw new DaemonControlError("UNSUPPORTED_PLATFORM", "this daemon command requires Linux, macOS or Windows");
|
|
868
|
+
try {
|
|
869
|
+
return inspectInstalledProfileScope({
|
|
870
|
+
dshHome: profile.home,
|
|
871
|
+
profileDir: profile.dir,
|
|
872
|
+
packageRoot: profile.packageRoot,
|
|
873
|
+
dshVersion: profile.dshVersion
|
|
874
|
+
});
|
|
875
|
+
} catch (error) {
|
|
876
|
+
throw toDaemonControlError(error);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
/** Resolve the fixed runtime dir for the current user. */
|
|
880
|
+
function runtimeDirOf(deps) {
|
|
881
|
+
return selectRuntimeDir(uidOf(deps));
|
|
882
|
+
}
|
|
883
|
+
/** The narrow local-Host-manager seams this command passes through. */
|
|
884
|
+
function managerDepsOf(deps) {
|
|
885
|
+
const unitDir = deps.unitDir;
|
|
886
|
+
return {
|
|
887
|
+
...deps.systemctl === void 0 ? {} : { systemctl: deps.systemctl },
|
|
888
|
+
...unitDir === void 0 ? {} : { unitDir: () => unitDir }
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
/** The Darwin launchd adapter inputs; production uses the OS account home and
|
|
892
|
+
* the real `/bin/launchctl`. */
|
|
893
|
+
function launchdDepsOf(deps) {
|
|
894
|
+
return {
|
|
895
|
+
uid: uidOf(deps),
|
|
896
|
+
...deps.darwinAccountHome === void 0 ? {} : { accountHome: deps.darwinAccountHome },
|
|
897
|
+
...deps.launchctl === void 0 ? {} : { launchctl: deps.launchctl }
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
/** Collect the validated launchd facts for one installed profile. */
|
|
901
|
+
function launchdFactsOf(scope, profile) {
|
|
902
|
+
return collectLaunchdProfileFacts(scope, profile.name, profile.installAnchor);
|
|
903
|
+
}
|
|
904
|
+
/** Map one actual launchd job state onto the stable status vocabulary. */
|
|
905
|
+
function launchdUnitState(state) {
|
|
906
|
+
switch (state) {
|
|
907
|
+
case "running": return "running";
|
|
908
|
+
case "not running": return "not-running";
|
|
909
|
+
case "spawn scheduled": return "spawn-scheduled";
|
|
910
|
+
default: return "unknown";
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* Read the authenticated Host facts once. No manager query, service definition,
|
|
915
|
+
* current-package walk or Host mutation belongs to this observation.
|
|
916
|
+
*/
|
|
917
|
+
async function readHostFacts(scope, deps) {
|
|
918
|
+
const readRecord = deps.readRecord ?? readLocalRecord;
|
|
919
|
+
const inspectProcess = deps.inspectProcess ?? inspectHostProcess;
|
|
920
|
+
let failure;
|
|
921
|
+
let exitCode = 0;
|
|
922
|
+
let host = "stopped";
|
|
923
|
+
let authenticated;
|
|
924
|
+
let hostAuthenticationFailed = false;
|
|
925
|
+
let hostCompatibilityFailed = false;
|
|
926
|
+
let record;
|
|
927
|
+
try {
|
|
928
|
+
record = readRecord(scope);
|
|
929
|
+
} catch (error) {
|
|
930
|
+
if (failure === void 0) {
|
|
931
|
+
failure = toDaemonControlError(error);
|
|
932
|
+
exitCode = failure.exitCode;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
let processAlive = false;
|
|
936
|
+
if (record !== void 0) try {
|
|
937
|
+
processAlive = inspectProcess(record) === "alive";
|
|
938
|
+
} catch (error) {
|
|
939
|
+
if (failure === void 0) {
|
|
940
|
+
failure = toDaemonControlError(error);
|
|
941
|
+
exitCode = failure.exitCode;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
if (processAlive && record !== void 0) {
|
|
945
|
+
let compatibilityFailure;
|
|
946
|
+
try {
|
|
947
|
+
assertClientHostCompatible(record, scope);
|
|
948
|
+
} catch (error) {
|
|
949
|
+
host = "incompatible";
|
|
950
|
+
hostCompatibilityFailed = true;
|
|
951
|
+
compatibilityFailure = toDaemonControlError(error);
|
|
952
|
+
if (failure === void 0) {
|
|
953
|
+
failure = compatibilityFailure;
|
|
954
|
+
exitCode = failure.exitCode;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
if (compatibilityFailure === void 0) try {
|
|
958
|
+
authenticated = await (deps.authenticate ?? authenticateLocalHost)(record, scope);
|
|
959
|
+
host = "ready";
|
|
960
|
+
} catch (error) {
|
|
961
|
+
const mapped = toDaemonControlError(error);
|
|
962
|
+
host = "unresponsive";
|
|
963
|
+
hostAuthenticationFailed = true;
|
|
964
|
+
if (failure === void 0) {
|
|
965
|
+
failure = mapped;
|
|
966
|
+
exitCode = mapped.exitCode;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
return {
|
|
971
|
+
scope,
|
|
972
|
+
record,
|
|
973
|
+
processAlive,
|
|
974
|
+
authenticated,
|
|
975
|
+
hostAuthenticationFailed,
|
|
976
|
+
hostCompatibilityFailed,
|
|
977
|
+
host,
|
|
978
|
+
failure,
|
|
979
|
+
exitCode
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* Read-only snapshot; `status` and mutating-command pre-flight checks consume it.
|
|
984
|
+
*
|
|
985
|
+
* The installed unit fact is the ONLY manager-IO admission: with no unit file
|
|
986
|
+
* (or no user unit directory) no `systemctl` invocation is made at all, so a
|
|
987
|
+
* missing/broken user manager cannot affect an independent basic Host. With a
|
|
988
|
+
* unit, exactly one `systemctl show` of that unit decides `user-manager` and
|
|
989
|
+
* the unit state. The Host's own registry/authentication chain is always read,
|
|
990
|
+
* even after a unit-identity refusal, so `status` can report a real ready Host
|
|
991
|
+
* beside a foreign unit while still exiting nonzero.
|
|
992
|
+
*/
|
|
993
|
+
async function readSnapshot(profile, deps, scope, preadHostFacts) {
|
|
994
|
+
const platform = platformOf(deps);
|
|
995
|
+
let unit;
|
|
996
|
+
let unitState = "not-found";
|
|
997
|
+
/** The manager's raw ActiveState; `unitState` is the coarse presentation. */
|
|
998
|
+
let unitActiveState = "";
|
|
999
|
+
let unitMainPid = 0;
|
|
1000
|
+
/** No owned name means no installed definition; other platforms never project this fact. */
|
|
1001
|
+
let unitFileState = platform === "linux" ? "not-found" : void 0;
|
|
1002
|
+
let userManager = "not-checked";
|
|
1003
|
+
let unitInspectionFailure;
|
|
1004
|
+
let unitQueryFailure;
|
|
1005
|
+
let launchdUnit;
|
|
1006
|
+
let launchdService;
|
|
1007
|
+
let launchdFacts;
|
|
1008
|
+
let launchdInspectionFailure;
|
|
1009
|
+
let launchdQueryFailure;
|
|
1010
|
+
if (platform === "linux") {
|
|
1011
|
+
const systemctl = deps.systemctl ?? runSystemctl;
|
|
1012
|
+
const runtimeDir = runtimeDirOf(deps);
|
|
1013
|
+
try {
|
|
1014
|
+
const inspected = inspectOwnedProfileUnit(scope, profile.name, deps.unitDir);
|
|
1015
|
+
if (inspected.kind === "owned") {
|
|
1016
|
+
unit = inspected;
|
|
1017
|
+
unitInspectionFailure = void 0;
|
|
1018
|
+
try {
|
|
1019
|
+
const state = await queryOwnedProfileUnit(inspected, runtimeDir, systemctl);
|
|
1020
|
+
userManager = "available";
|
|
1021
|
+
unitMainPid = state.mainPid;
|
|
1022
|
+
unitFileState = state.unitFileState === "" ? "unknown" : state.unitFileState;
|
|
1023
|
+
unitActiveState = state.loadState === "not-found" ? "" : state.activeState;
|
|
1024
|
+
unitState = state.loadState === "not-found" ? "not-found" : state.activeState === "active" ? "active" : state.activeState === "inactive" || state.activeState === "failed" ? "inactive" : "unknown";
|
|
1025
|
+
} catch (error) {
|
|
1026
|
+
userManager = "error";
|
|
1027
|
+
unitQueryFailure = toDaemonControlError(error);
|
|
1028
|
+
unitState = "unknown";
|
|
1029
|
+
unitFileState = "unknown";
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
unitInspectionFailure = toDaemonControlError(error);
|
|
1034
|
+
unitState = "unknown";
|
|
1035
|
+
unitFileState = "unknown";
|
|
1036
|
+
}
|
|
1037
|
+
} else if (platform === "darwin") try {
|
|
1038
|
+
launchdFacts = launchdFactsOf(scope, profile);
|
|
1039
|
+
const launchdDeps = launchdDepsOf(deps);
|
|
1040
|
+
const inspected = inspectOwnedLaunchdUnit(launchdFacts, launchdDeps);
|
|
1041
|
+
if (inspected.kind === "owned") {
|
|
1042
|
+
launchdUnit = inspected.unit;
|
|
1043
|
+
try {
|
|
1044
|
+
launchdService = await inspectLaunchdService(inspected.unit, launchdDeps);
|
|
1045
|
+
userManager = "available";
|
|
1046
|
+
if (launchdService.kind === "not-loaded") unitState = "not-found";
|
|
1047
|
+
else if (launchdService.kind === "loaded") {
|
|
1048
|
+
const service = launchdService.service;
|
|
1049
|
+
unitActiveState = service.state;
|
|
1050
|
+
unitState = launchdUnitState(service.state);
|
|
1051
|
+
unitMainPid = service.pid ?? 0;
|
|
1052
|
+
if (!launchdServiceMatches(launchdFacts, inspected.unit, service)) launchdQueryFailure = new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the loaded launchd job does not match the installed profile plist");
|
|
1053
|
+
} else {
|
|
1054
|
+
userManager = "error";
|
|
1055
|
+
unitState = "unknown";
|
|
1056
|
+
launchdQueryFailure = new DaemonControlError("MANAGER_OR_OS_FAILURE", "the loaded launchd job state is not recognizable");
|
|
1057
|
+
}
|
|
1058
|
+
} catch (error) {
|
|
1059
|
+
userManager = "error";
|
|
1060
|
+
unitState = "unknown";
|
|
1061
|
+
launchdQueryFailure = toDaemonControlError(error);
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
launchdInspectionFailure = toDaemonControlError(error);
|
|
1066
|
+
unitState = "unknown";
|
|
1067
|
+
}
|
|
1068
|
+
const managerFailure = unitInspectionFailure ?? unitQueryFailure ?? launchdInspectionFailure ?? launchdQueryFailure;
|
|
1069
|
+
const hostFacts = preadHostFacts ?? await readHostFacts(scope, deps);
|
|
1070
|
+
let failure = managerFailure ?? hostFacts.failure;
|
|
1071
|
+
let exitCode = managerFailure?.exitCode ?? hostFacts.exitCode;
|
|
1072
|
+
let host = hostFacts.host;
|
|
1073
|
+
const { record, processAlive, authenticated, hostAuthenticationFailed, hostCompatibilityFailed } = hostFacts;
|
|
1074
|
+
let manager = "unmanaged";
|
|
1075
|
+
if (authenticated !== void 0 && record !== void 0) {
|
|
1076
|
+
if (platform === "darwin") {
|
|
1077
|
+
if (launchdUnit === void 0) manager = "process";
|
|
1078
|
+
else if (launchdInspectionFailure !== void 0 || launchdQueryFailure !== void 0 || launchdService === void 0) manager = "unmanaged";
|
|
1079
|
+
else if (launchdService.kind === "loaded") {
|
|
1080
|
+
const service = launchdService.service;
|
|
1081
|
+
if (service.state === "running") {
|
|
1082
|
+
if (service.pid === void 0) {
|
|
1083
|
+
manager = "unmanaged";
|
|
1084
|
+
if (failure === void 0) {
|
|
1085
|
+
failure = new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job reports running without a PID");
|
|
1086
|
+
exitCode = failure.exitCode;
|
|
1087
|
+
}
|
|
1088
|
+
} else if (service.pid === record.hostPid) manager = "launchd";
|
|
1089
|
+
else {
|
|
1090
|
+
manager = "process";
|
|
1091
|
+
if (failure === void 0) {
|
|
1092
|
+
failure = new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job PID is not the authenticated Host; use launchctl for this custom service");
|
|
1093
|
+
exitCode = failure.exitCode;
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
} else if (service.state === "spawn scheduled") {
|
|
1097
|
+
manager = "unmanaged";
|
|
1098
|
+
if (failure === void 0) {
|
|
1099
|
+
failure = new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job is still starting beside a live Host");
|
|
1100
|
+
exitCode = failure.exitCode;
|
|
1101
|
+
}
|
|
1102
|
+
} else if (service.state === "not running") manager = "process";
|
|
1103
|
+
else {
|
|
1104
|
+
manager = "unmanaged";
|
|
1105
|
+
if (failure === void 0) {
|
|
1106
|
+
failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${service.state === "" ? "unknown" : service.state})`);
|
|
1107
|
+
exitCode = failure.exitCode;
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
} else manager = "process";
|
|
1111
|
+
} else {
|
|
1112
|
+
const loaded = unit !== void 0 && unitState !== "not-found";
|
|
1113
|
+
const running = unitActiveState === "active" || unitActiveState === "activating";
|
|
1114
|
+
const ended = unitActiveState === "inactive" || unitActiveState === "failed";
|
|
1115
|
+
if (unitInspectionFailure !== void 0 || unitQueryFailure !== void 0) manager = "unmanaged";
|
|
1116
|
+
else if (loaded && running) {
|
|
1117
|
+
if (unitMainPid === record.hostPid) manager = "systemd";
|
|
1118
|
+
else {
|
|
1119
|
+
manager = "process";
|
|
1120
|
+
if (failure === void 0) {
|
|
1121
|
+
failure = new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the unit MainPID is not the authenticated Host; use systemctl --user for this custom service");
|
|
1122
|
+
exitCode = failure.exitCode;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
} else if (loaded && !ended) {
|
|
1126
|
+
manager = "unmanaged";
|
|
1127
|
+
if (failure === void 0) {
|
|
1128
|
+
failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState})`);
|
|
1129
|
+
exitCode = failure.exitCode;
|
|
1130
|
+
}
|
|
1131
|
+
} else manager = "process";
|
|
1132
|
+
}
|
|
1133
|
+
} else if (record === void 0 || !processAlive) {
|
|
1134
|
+
if (platform === "darwin") {
|
|
1135
|
+
if (launchdUnit !== void 0 && launchdService?.kind === "loaded") {
|
|
1136
|
+
const state = launchdService.service.state;
|
|
1137
|
+
if (state === "running" || state === "spawn scheduled") host = "starting";
|
|
1138
|
+
else if (state === "not running") host = "stopped";
|
|
1139
|
+
else {
|
|
1140
|
+
host = "unknown";
|
|
1141
|
+
if (failure === void 0) {
|
|
1142
|
+
failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${state === "" ? "unknown" : state})`);
|
|
1143
|
+
exitCode = failure.exitCode;
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
} else {
|
|
1148
|
+
const loaded = unit !== void 0 && unitState !== "not-found";
|
|
1149
|
+
if (loaded && (unitActiveState === "active" || unitActiveState === "activating")) host = "starting";
|
|
1150
|
+
else if (loaded && unitActiveState !== "inactive" && unitActiveState !== "failed") {
|
|
1151
|
+
host = "unknown";
|
|
1152
|
+
if (failure === void 0) {
|
|
1153
|
+
failure = new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState})`);
|
|
1154
|
+
exitCode = failure.exitCode;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
if (failure !== void 0 && host === "stopped") host = "unknown";
|
|
1160
|
+
return {
|
|
1161
|
+
unit,
|
|
1162
|
+
launchdUnit,
|
|
1163
|
+
launchdService,
|
|
1164
|
+
launchdFacts,
|
|
1165
|
+
launchdInspectionFailure,
|
|
1166
|
+
launchdQueryFailure,
|
|
1167
|
+
userManager,
|
|
1168
|
+
unitInspectionFailure,
|
|
1169
|
+
unitQueryFailure,
|
|
1170
|
+
unitState,
|
|
1171
|
+
unitActiveState,
|
|
1172
|
+
unitMainPid,
|
|
1173
|
+
...hostFacts,
|
|
1174
|
+
host,
|
|
1175
|
+
status: {
|
|
1176
|
+
profile: profile.name,
|
|
1177
|
+
manager,
|
|
1178
|
+
userManager,
|
|
1179
|
+
host,
|
|
1180
|
+
unit: platform === "darwin" ? launchdUnit === void 0 ? "none" : launchdUnit.label : unit === void 0 ? "none" : unit.unitName,
|
|
1181
|
+
unitState,
|
|
1182
|
+
...unitFileState === void 0 ? {} : { unitFileState },
|
|
1183
|
+
compatibility: host === "ready" ? "compatible" : host === "incompatible" ? "incompatible" : host === "stopped" || host === "starting" ? "none" : "unknown",
|
|
1184
|
+
...processAlive && record !== void 0 ? { pid: record.hostPid } : {},
|
|
1185
|
+
...processAlive && record !== void 0 ? { instance: record.instanceId.slice(0, 8) } : {}
|
|
1186
|
+
},
|
|
1187
|
+
exitCode,
|
|
1188
|
+
failure
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
/** The stable `key=value` status block (no secret or private path). */
|
|
1192
|
+
function formatDaemonStatus(status) {
|
|
1193
|
+
const lines = [
|
|
1194
|
+
`profile=${status.profile.replace(/[\u0000-\u001f\u007f]/gu, "")}`,
|
|
1195
|
+
`manager=${status.manager}`,
|
|
1196
|
+
`user-manager=${status.userManager}`,
|
|
1197
|
+
`host=${status.host}`,
|
|
1198
|
+
`unit=${status.unit}`,
|
|
1199
|
+
`unit-state=${status.unitState}`,
|
|
1200
|
+
...status.unitFileState === void 0 ? [] : [`unit-file-state=${status.unitFileState.replace(/[\u0000-\u001f\u007f]/gu, "")}`],
|
|
1201
|
+
`compatibility=${status.compatibility}`
|
|
1202
|
+
];
|
|
1203
|
+
if (status.pid !== void 0) lines.push(`pid=${String(status.pid)}`);
|
|
1204
|
+
if (status.instance !== void 0) lines.push(`instance=${status.instance}`);
|
|
1205
|
+
if (status.acp !== void 0) lines.push(`acp=${status.acp}`);
|
|
1206
|
+
if (status.acpSocket !== void 0) lines.push(`acp-socket=${status.acpSocket}`);
|
|
1207
|
+
return `${lines.join("\n")}\n`;
|
|
1208
|
+
}
|
|
1209
|
+
/** Format one status result without changing the command's success semantics. */
|
|
1210
|
+
function statusResult(snapshot, extras = {}, options = {}) {
|
|
1211
|
+
const failure = options.commandSuccess === true || snapshot.failure === void 0 ? "" : formatDaemonControlError(snapshot.failure);
|
|
1212
|
+
return {
|
|
1213
|
+
code: options.commandSuccess === true ? 0 : snapshot.exitCode,
|
|
1214
|
+
stdout: formatDaemonStatus({
|
|
1215
|
+
...snapshot.status,
|
|
1216
|
+
...extras
|
|
1217
|
+
}),
|
|
1218
|
+
stderr: `${failure}${options.extraStderr ?? ""}`
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* Acquire the ONE profile-scoped admin seat for a mutating verb. The seat is
|
|
1223
|
+
* held for exactly the lifetime of THIS command's operation: two concurrently
|
|
1224
|
+
* running management commands of the same Profile cannot interleave, and the
|
|
1225
|
+
* kernel releases the claim when the process exits. Linux keeps its abstract
|
|
1226
|
+
* socket name; Darwin claims the existing `admin` `O_EXLOCK` file beside the
|
|
1227
|
+
* Host singleton seat. There is no persistent lock file and no in-memory shadow
|
|
1228
|
+
* of OS operations — a command that dies with the process releases the seat,
|
|
1229
|
+
* and the next command re-reads the real systemd/Host state.
|
|
1230
|
+
*/
|
|
1231
|
+
async function withAdminSeat(scope, deps, operation) {
|
|
1232
|
+
let seat;
|
|
1233
|
+
try {
|
|
1234
|
+
if (platformOf(deps) === "linux") seat = await bindProcessSeat(`${ADMIN_SEAT_PREFIX}${scope.scopeId.slice(0, 40)}`, "DAEMON_CONTROL_BUSY");
|
|
1235
|
+
else if (platformOf(deps) === "win32") seat = await bindProfileKernelSeat(scope, "admin", "DAEMON_CONTROL_BUSY");
|
|
1236
|
+
else seat = await bindDarwinKernelSeat(darwinHostProfileSeatDir(scope.scopeId, deps.darwinAccountHome), scope.scopeId, "admin", "DAEMON_CONTROL_BUSY");
|
|
1237
|
+
} catch (error) {
|
|
1238
|
+
throw toDaemonControlError(error);
|
|
1239
|
+
}
|
|
1240
|
+
try {
|
|
1241
|
+
return await operation();
|
|
1242
|
+
} finally {
|
|
1243
|
+
await seat.close();
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
/** A live Host authentication or compatibility failure is a diagnosis, not a
|
|
1247
|
+
* unit-ownership verdict. A verified current-Profile service remains
|
|
1248
|
+
* manageable through the manager; every other snapshot failure keeps its
|
|
1249
|
+
* normal admission. The product never auto-recovers — this only permits an
|
|
1250
|
+
* explicit user command. */
|
|
1251
|
+
function verifiedUnitManagementAdmitted(snapshot) {
|
|
1252
|
+
return (snapshot.hostAuthenticationFailed || snapshot.hostCompatibilityFailed) && snapshot.unit !== void 0 && snapshot.userManager === "available";
|
|
1253
|
+
}
|
|
1254
|
+
/** The same admission for a verified launchd job whose real PID is the live
|
|
1255
|
+
* Host record (or whose job state proves no process is running). */
|
|
1256
|
+
function verifiedLaunchdManagementAdmitted(snapshot) {
|
|
1257
|
+
const { launchdUnit, launchdFacts, launchdService, record, processAlive } = snapshot;
|
|
1258
|
+
if (launchdUnit === void 0 || launchdFacts === void 0 || launchdService?.kind !== "loaded") return false;
|
|
1259
|
+
if (!launchdServiceMatches(launchdFacts, launchdUnit, launchdService.service)) return false;
|
|
1260
|
+
if (!processAlive || record === void 0) return true;
|
|
1261
|
+
return launchdService.service.pid !== void 0 && launchdService.service.pid === record.hostPid;
|
|
1262
|
+
}
|
|
1263
|
+
/** A stable local error for an unknown Host state. */
|
|
1264
|
+
function refuseHostState(status) {
|
|
1265
|
+
if (status.host === "incompatible") return new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host uses an incompatible protocol or DSH runtime");
|
|
1266
|
+
if (status.host === "unresponsive") return new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live Host could not prove its authenticated identity");
|
|
1267
|
+
return new DaemonControlError("TRANSITION_UNCERTAIN", `the Host is ${status.host}; refusing to change supervision`);
|
|
1268
|
+
}
|
|
1269
|
+
/** The bounded post-stop wait for the original Host's terminal state. Linux
|
|
1270
|
+
* uses the discovery classifier's gone/different-birth/terminal-state verdict;
|
|
1271
|
+
* Darwin requires the recorded schema-2 identity to become `gone`/`different`.
|
|
1272
|
+
* An `unknown` kernel read is uncertainty and never proves a stop. */
|
|
1273
|
+
async function waitForHostStopped(record, mainPid, deps) {
|
|
1274
|
+
const now = deps.now ?? Date.now;
|
|
1275
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1276
|
+
const deadline = now() + (deps.stopTimeoutMs ?? 2e4);
|
|
1277
|
+
if (platformOf(deps) === "darwin") {
|
|
1278
|
+
if (record === void 0 || record.schema !== 2) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host kernel identity is unavailable for the stop proof");
|
|
1279
|
+
const readKernel = deps.readKernel ?? readKernelProcess;
|
|
1280
|
+
for (;;) {
|
|
1281
|
+
const classification = sameKernelProcess(record.hostKernelIdentity, readKernel(record.hostPid));
|
|
1282
|
+
if (classification === "gone" || classification === "different") return;
|
|
1283
|
+
if (now() >= deadline) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the old Host process did not exit within the bounded window");
|
|
1284
|
+
await sleep(100);
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
const readStarttime = deps.readStarttime ?? ((pid) => {
|
|
1288
|
+
try {
|
|
1289
|
+
return readLinuxStarttime(pid);
|
|
1290
|
+
} catch {
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1293
|
+
});
|
|
1294
|
+
const inspectProcess = deps.inspectProcess ?? inspectHostProcess;
|
|
1295
|
+
for (;;) {
|
|
1296
|
+
if (record !== void 0 ? inspectProcess(record) === "dead" : mainPid === 0 || readStarttime(mainPid) === void 0) return;
|
|
1297
|
+
if (now() >= deadline) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the old Host process did not exit within the bounded window");
|
|
1298
|
+
await sleep(100);
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
/** Reject an obviously non-Host command before signalling the authenticated PID. */
|
|
1302
|
+
function assertProcessHostOwnership(record, deps) {
|
|
1303
|
+
const cmdline = (deps.readCmdline ?? ((pid) => {
|
|
1304
|
+
try {
|
|
1305
|
+
return readFileString(`/proc/${String(pid)}/cmdline`);
|
|
1306
|
+
} catch {
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
1309
|
+
}))(record.hostPid);
|
|
1310
|
+
if (cmdline === void 0 || cmdline === "") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host process command line is unavailable");
|
|
1311
|
+
const entry = cmdline.split("\0").filter((part) => part !== "")[1];
|
|
1312
|
+
if (entry === void 0 || !entry.endsWith("/dist/local-host.mjs")) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the live process is not the product Host entry");
|
|
1313
|
+
}
|
|
1314
|
+
/** Bounded read-to-EOF for procfs text files: `/proc` entries report
|
|
1315
|
+
* `st_size = 0` even when the content is readable, so the length must come
|
|
1316
|
+
* from reading until EOF under an explicit byte cap, never from `fstat.size`. */
|
|
1317
|
+
function readFileString(path) {
|
|
1318
|
+
const fd = openSync(path, constants.O_RDONLY);
|
|
1319
|
+
try {
|
|
1320
|
+
const chunks = [];
|
|
1321
|
+
let total = 0;
|
|
1322
|
+
for (;;) {
|
|
1323
|
+
const chunk = Buffer.alloc(4096);
|
|
1324
|
+
const read = readSync(fd, chunk, 0, chunk.length, null);
|
|
1325
|
+
if (read <= 0) break;
|
|
1326
|
+
total += read;
|
|
1327
|
+
if (total > 65536) throw new Error("unexpected process command line size");
|
|
1328
|
+
chunks.push(read === chunk.length ? chunk : chunk.subarray(0, read));
|
|
1329
|
+
}
|
|
1330
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
1331
|
+
} finally {
|
|
1332
|
+
closeSync(fd);
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
/** Stop one live independent authenticated Host through exactly one verified
|
|
1336
|
+
* POSIX SIGTERM (Linux procfs identity or Darwin schema-2 kernel identity). */
|
|
1337
|
+
async function stopIndependentHost(snapshot, deps) {
|
|
1338
|
+
const record = snapshot.record;
|
|
1339
|
+
if (record === void 0) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host registry disappeared before the stop");
|
|
1340
|
+
const authenticate = deps.authenticate ?? authenticateLocalHost;
|
|
1341
|
+
try {
|
|
1342
|
+
await authenticate(record, snapshot.scope);
|
|
1343
|
+
} catch (error) {
|
|
1344
|
+
throw toDaemonControlError(error);
|
|
1345
|
+
}
|
|
1346
|
+
if (platformOf(deps) === "darwin") try {
|
|
1347
|
+
assertRecordedHostKernelIdentityCurrent(record, deps.readKernel ?? readKernelProcess, "darwin");
|
|
1348
|
+
} catch (error) {
|
|
1349
|
+
throw toDaemonControlError(error);
|
|
1350
|
+
}
|
|
1351
|
+
else {
|
|
1352
|
+
assertProcessHostOwnership(record, deps);
|
|
1353
|
+
const readStarttime = deps.readStarttime ?? ((pid) => {
|
|
1354
|
+
try {
|
|
1355
|
+
return readLinuxStarttime(pid);
|
|
1356
|
+
} catch {
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
});
|
|
1360
|
+
if (record.schema !== 1 || readStarttime(record.hostPid) !== record.hostStarttime) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host process start identity changed before the signal");
|
|
1361
|
+
}
|
|
1362
|
+
assertNotAborted(deps.signal);
|
|
1363
|
+
const kill = deps.kill ?? process.kill;
|
|
1364
|
+
try {
|
|
1365
|
+
kill(record.hostPid, "SIGTERM");
|
|
1366
|
+
} catch (error) {
|
|
1367
|
+
throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "the verified Host process could not be signalled", error);
|
|
1368
|
+
}
|
|
1369
|
+
try {
|
|
1370
|
+
await waitForHostStopped(record, record.hostPid, deps);
|
|
1371
|
+
} catch (error) {
|
|
1372
|
+
throw afterCommittedAction(toDaemonControlError(error), "Host stop");
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Stop the snapshot's Host and prove the original instance is gone.
|
|
1377
|
+
*
|
|
1378
|
+
* Linux routing follows the authenticated attribution, never the mere presence
|
|
1379
|
+
* of a systemd user bus:
|
|
1380
|
+
* - a loaded active/activating unit whose MainPID IS the authenticated Host is
|
|
1381
|
+
* stopped through that unit and its exit is awaited;
|
|
1382
|
+
* - an independent authenticated Host (no unit, or a loaded unit that systemd
|
|
1383
|
+
* reports as inactive/failed/not-found) is re-authenticated, its platform
|
|
1384
|
+
* ownership proof (Linux procfs starttime + Host entry command shape, Darwin
|
|
1385
|
+
* schema-2 kernel identity) is re-checked, and exactly that PID receives one
|
|
1386
|
+
* SIGTERM;
|
|
1387
|
+
* - a live Host beside an active unit with a different MainPID, a unit in flux,
|
|
1388
|
+
* or an unreadable manager is refused WITHOUT trying the other stop method.
|
|
1389
|
+
*
|
|
1390
|
+
* Darwin routing uses the verified LaunchAgent instead of a systemd unit: a
|
|
1391
|
+
* loaded job whose fixed launch facts match this profile and whose real PID is
|
|
1392
|
+
* the authenticated Host is stopped only through `bootout`; a job that is
|
|
1393
|
+
* loaded but not running is booted out without a signal; anything transitional,
|
|
1394
|
+
* foreign or unreadable is refused.
|
|
1395
|
+
*/
|
|
1396
|
+
async function stopFromSnapshot(snapshot, deps) {
|
|
1397
|
+
if (platformOf(deps) === "win32") return await stopWin32FromSnapshot(snapshot, deps);
|
|
1398
|
+
if (platformOf(deps) === "darwin") return await stopDarwinFromSnapshot(snapshot, deps);
|
|
1399
|
+
const { unit, unitState, unitActiveState, unitMainPid, record, processAlive } = snapshot;
|
|
1400
|
+
const systemctl = deps.systemctl ?? runSystemctl;
|
|
1401
|
+
const liveHost = processAlive && record !== void 0;
|
|
1402
|
+
const loaded = unit !== void 0 && unitState !== "not-found";
|
|
1403
|
+
const running = loaded && (unitActiveState === "active" || unitActiveState === "activating");
|
|
1404
|
+
const ended = loaded && (unitActiveState === "inactive" || unitActiveState === "failed");
|
|
1405
|
+
if (snapshot.userManager === "error") throw snapshot.unitQueryFailure ?? new DaemonControlError("MANAGER_OR_OS_FAILURE", "the user manager cannot verify the profile unit");
|
|
1406
|
+
if (liveHost) {
|
|
1407
|
+
if (running) {
|
|
1408
|
+
if (unit === void 0 || unitMainPid !== record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the unit MainPID is not the authenticated Host; refusing to signal an unknown process");
|
|
1409
|
+
assertNotAborted(deps.signal);
|
|
1410
|
+
await stopOwnedProfileUnit(unit, runtimeDirOf(deps), systemctl, deps.stopTimeoutMs);
|
|
1411
|
+
try {
|
|
1412
|
+
await waitForHostStopped(record, unitMainPid, deps);
|
|
1413
|
+
} catch (error) {
|
|
1414
|
+
throw afterCommittedAction(toDaemonControlError(error), "Host stop");
|
|
1415
|
+
}
|
|
1416
|
+
return;
|
|
1417
|
+
}
|
|
1418
|
+
if (loaded && !ended) throw new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState}); refusing to signal the Host`);
|
|
1419
|
+
if (!running) {
|
|
1420
|
+
await stopIndependentHost(snapshot, deps);
|
|
1421
|
+
return;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
if (loaded) {
|
|
1425
|
+
if (!ended && !running) throw new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${unitActiveState === "" ? "unknown" : unitActiveState}); refusing to change supervision`);
|
|
1426
|
+
if (unit === void 0) return;
|
|
1427
|
+
assertNotAborted(deps.signal);
|
|
1428
|
+
await stopOwnedProfileUnit(unit, runtimeDirOf(deps), systemctl, deps.stopTimeoutMs);
|
|
1429
|
+
try {
|
|
1430
|
+
await waitForHostStopped(void 0, unitMainPid, deps);
|
|
1431
|
+
} catch (error) {
|
|
1432
|
+
throw afterCommittedAction(toDaemonControlError(error), "Host stop");
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* The Windows stop route: one exact held process handle and one exact
|
|
1438
|
+
* per-instance Event. The original handle is the terminal authority; the
|
|
1439
|
+
* Event only delivers the existing stop(0) request to the Host entry.
|
|
1440
|
+
*/
|
|
1441
|
+
async function stopWin32FromSnapshot(snapshot, deps) {
|
|
1442
|
+
const record = snapshot.record;
|
|
1443
|
+
if (!snapshot.processAlive || record === void 0) return;
|
|
1444
|
+
if (record.schema !== 3) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host registry is not a Windows kernel identity");
|
|
1445
|
+
const authenticated = snapshot.authenticated;
|
|
1446
|
+
if (authenticated === void 0 || authenticated.identity.instanceId !== record.instanceId || authenticated.identity.hostPid !== record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the authenticated Host is not the recorded instance");
|
|
1447
|
+
const opened = openWin32Process(record.hostPid);
|
|
1448
|
+
if (opened.kind === "gone") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the recorded Host process is no longer alive");
|
|
1449
|
+
if (opened.kind === "unknown") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the recorded Host process identity cannot be verified");
|
|
1450
|
+
const capture = opened.capture;
|
|
1451
|
+
try {
|
|
1452
|
+
if (capture.identity.ownerSid !== record.hostKernelIdentity.ownerSid || capture.identity.creationFiletime !== record.hostKernelIdentity.creationFiletime) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the opened process is not the recorded Host instance");
|
|
1453
|
+
const currentRecord = (deps.readRecord ?? readLocalRecord)(snapshot.scope);
|
|
1454
|
+
if (currentRecord === void 0 || !sameLocalInstanceRecord(currentRecord, record)) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Host registry changed before the stop dispatch");
|
|
1455
|
+
if ((await waitWin32Handle(capture.handle, 0)).kind !== "timeout") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the recorded Host process is not alive for the stop dispatch");
|
|
1456
|
+
assertNotAborted(deps.signal);
|
|
1457
|
+
let event;
|
|
1458
|
+
try {
|
|
1459
|
+
event = openWin32StopSignal(snapshot.scope.scopeId, record.instanceId);
|
|
1460
|
+
} catch (error) {
|
|
1461
|
+
throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the per-instance stop event is unavailable", error);
|
|
1462
|
+
}
|
|
1463
|
+
try {
|
|
1464
|
+
event.setOnce();
|
|
1465
|
+
} finally {
|
|
1466
|
+
event.close();
|
|
1467
|
+
}
|
|
1468
|
+
if ((await waitWin32Handle(capture.handle, deps.stopTimeoutMs ?? 2e4)).kind !== "terminal") throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", "the old Host process did not reach its original handle terminal within the bounded window"), "Host stop");
|
|
1469
|
+
try {
|
|
1470
|
+
const postRecord = (deps.readRecord ?? readLocalRecord)(snapshot.scope);
|
|
1471
|
+
if (postRecord !== void 0 && (deps.inspectProcess ?? inspectHostProcess)(postRecord) === "alive") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the Host registry still reports a live process after stop");
|
|
1472
|
+
} catch (error) {
|
|
1473
|
+
if (error instanceof DaemonControlError) throw afterCommittedAction(error, "Host stop");
|
|
1474
|
+
throw afterCommittedAction(toDaemonControlError(error), "Host stop");
|
|
1475
|
+
}
|
|
1476
|
+
} finally {
|
|
1477
|
+
closeWin32Handle(capture.handle);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
/** The Darwin stop route: verified LaunchAgent bootout or one verified SIGTERM. */
|
|
1481
|
+
async function stopDarwinFromSnapshot(snapshot, deps) {
|
|
1482
|
+
const { launchdUnit, launchdFacts, launchdService, record, processAlive } = snapshot;
|
|
1483
|
+
if (snapshot.launchdInspectionFailure !== void 0) throw snapshot.launchdInspectionFailure;
|
|
1484
|
+
if (snapshot.launchdQueryFailure !== void 0) throw snapshot.launchdQueryFailure;
|
|
1485
|
+
const loaded = launchdService?.kind === "loaded" ? launchdService.service : void 0;
|
|
1486
|
+
if (launchdService?.kind === "unknown") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job state is not recognizable; refusing to change supervision");
|
|
1487
|
+
if (launchdUnit !== void 0 && launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job facts are unavailable; refusing to change supervision");
|
|
1488
|
+
if (launchdUnit !== void 0 && loaded !== void 0 && launchdFacts !== void 0 && !launchdServiceMatches(launchdFacts, launchdUnit, loaded)) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the loaded launchd job does not match the profile plist; refusing to signal an unknown process");
|
|
1489
|
+
const liveHost = processAlive && record !== void 0;
|
|
1490
|
+
if (liveHost && launchdUnit !== void 0 && launchdFacts !== void 0 && loaded !== void 0) {
|
|
1491
|
+
if (loaded.state === "running") {
|
|
1492
|
+
if (loaded.pid === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job reports running without a PID; refusing to signal the Host");
|
|
1493
|
+
if (loaded.pid !== record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job PID is not the authenticated Host; refusing to signal an unknown process");
|
|
1494
|
+
assertNotAborted(deps.signal);
|
|
1495
|
+
await stopLaunchdService(launchdFacts, launchdUnit, launchdDepsOf(deps), record.hostPid);
|
|
1496
|
+
try {
|
|
1497
|
+
await waitForHostStopped(record, loaded.pid, deps);
|
|
1498
|
+
} catch (error) {
|
|
1499
|
+
throw afterCommittedAction(toDaemonControlError(error), "Host stop");
|
|
1500
|
+
}
|
|
1501
|
+
return;
|
|
1502
|
+
}
|
|
1503
|
+
if (loaded.state === "spawn scheduled") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job is still starting beside the live Host; refusing to signal the Host");
|
|
1504
|
+
if (loaded.state !== "not running") throw new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${loaded.state === "" ? "unknown" : loaded.state}); refusing to signal the Host`);
|
|
1505
|
+
}
|
|
1506
|
+
if (liveHost) {
|
|
1507
|
+
await stopIndependentHost(snapshot, deps);
|
|
1508
|
+
return;
|
|
1509
|
+
}
|
|
1510
|
+
if (loaded !== void 0) {
|
|
1511
|
+
if (launchdUnit === void 0 || launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job facts are unavailable; refusing to change supervision");
|
|
1512
|
+
if (loaded.pid !== void 0 || loaded.state === "running" || loaded.state === "spawn scheduled") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job has a process but no authenticated Host record proves its identity; refusing to change supervision");
|
|
1513
|
+
if (loaded.state === "not running") {
|
|
1514
|
+
assertNotAborted(deps.signal);
|
|
1515
|
+
await stopLaunchdService(launchdFacts, launchdUnit, launchdDepsOf(deps));
|
|
1516
|
+
return;
|
|
1517
|
+
}
|
|
1518
|
+
throw new DaemonControlError("TRANSITION_UNCERTAIN", `the launchd job is in an unconfirmed state (${loaded.state === "" ? "unknown" : loaded.state}); refusing to change supervision`);
|
|
1519
|
+
}
|
|
1520
|
+
if (snapshot.launchdQueryFailure !== void 0) throw snapshot.launchdQueryFailure;
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* The public local endpoint of this profile scope: the POSIX UDS logical path or
|
|
1524
|
+
* the Windows Named Pipe (never the macOS private bind name). The value is a
|
|
1525
|
+
* single safe `key=value` line or it is omitted: a malformed path is never
|
|
1526
|
+
* sanitized into a fake connectable address.
|
|
1527
|
+
*/
|
|
1528
|
+
function acpSocketPathOf(scope, deps) {
|
|
1529
|
+
const platform = platformOf(deps);
|
|
1530
|
+
if (platform === "win32") return acpPipeAddress(scope.scopeId);
|
|
1531
|
+
const path = platform === "darwin" ? darwinAcpSocketPaths(scope, uidOf(deps)).publicPath : join(scope.dir, "acp.sock");
|
|
1532
|
+
if (!path.startsWith("/") || /[\u0000-\u001f\u007f]/u.test(path)) return void 0;
|
|
1533
|
+
return path;
|
|
1534
|
+
}
|
|
1535
|
+
/**
|
|
1536
|
+
* Derive the `acp` field from the ONE authenticated read-only observation. Only
|
|
1537
|
+
* an authenticated `host=ready` snapshot is read at all; every unprovable
|
|
1538
|
+
* outcome is `unavailable` and NEVER a guessed `disabled`. The ACP facts never
|
|
1539
|
+
* change the original exit code, stderr or manager/Host classification.
|
|
1540
|
+
*/
|
|
1541
|
+
async function observeAcpFacts(host, scope, deps) {
|
|
1542
|
+
if (host.authenticated === void 0 || host.host !== "ready") return { acp: "unavailable" };
|
|
1543
|
+
const status = await (deps.observeAcpStatus ?? observeAuthenticatedLocalAcpStatus)(host.authenticated);
|
|
1544
|
+
if (status === void 0) return { acp: "unavailable" };
|
|
1545
|
+
switch (status.state) {
|
|
1546
|
+
case "enabled": {
|
|
1547
|
+
const socket = acpSocketPathOf(scope, deps);
|
|
1548
|
+
return socket === void 0 ? { acp: "enabled" } : {
|
|
1549
|
+
acp: "enabled",
|
|
1550
|
+
acpSocket: socket
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
case "disabled": return { acp: "disabled" };
|
|
1554
|
+
case "changing":
|
|
1555
|
+
case "unavailable": return { acp: "unavailable" };
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* The ONE read-only target seam for the trusted-profile ACP stdio bridge. It
|
|
1560
|
+
* runs the same scope inspection, authenticated Host observation and ACP
|
|
1561
|
+
* listener observation as `daemon status` without querying the service manager,
|
|
1562
|
+
* then returns either the public local endpoint
|
|
1563
|
+
* (POSIX UDS path or Windows Named Pipe) plus the exact authenticated Host
|
|
1564
|
+
* instance identity, or one fixed rejection category. It never starts a Host, changes listener state or
|
|
1565
|
+
* persists a target.
|
|
1566
|
+
*/
|
|
1567
|
+
async function readAcpStdioTarget(profile, signal, deps = {}) {
|
|
1568
|
+
signal?.throwIfAborted();
|
|
1569
|
+
const effectiveDeps = signal === void 0 ? deps : {
|
|
1570
|
+
...deps,
|
|
1571
|
+
signal
|
|
1572
|
+
};
|
|
1573
|
+
const scope = inspectScope(profile, effectiveDeps);
|
|
1574
|
+
signal?.throwIfAborted();
|
|
1575
|
+
const host = await readHostFacts(scope, effectiveDeps);
|
|
1576
|
+
signal?.throwIfAborted();
|
|
1577
|
+
if (host.host !== "ready" || host.authenticated === void 0) return { kind: "host-unavailable" };
|
|
1578
|
+
const acp = await observeAcpFacts(host, scope, effectiveDeps);
|
|
1579
|
+
signal?.throwIfAborted();
|
|
1580
|
+
if (acp.acp === "disabled") return { kind: "acp-disabled" };
|
|
1581
|
+
if (acp.acp !== "enabled" || acp.acpSocket === void 0) return { kind: "acp-unavailable" };
|
|
1582
|
+
return {
|
|
1583
|
+
kind: "ready",
|
|
1584
|
+
socketPath: acp.acpSocket,
|
|
1585
|
+
instanceId: host.authenticated.identity.instanceId
|
|
1586
|
+
};
|
|
1587
|
+
}
|
|
1588
|
+
/** The `status` handler. */
|
|
1589
|
+
async function runStatus(profile, deps) {
|
|
1590
|
+
const snapshot = await readSnapshot(profile, deps, inspectScope(profile, deps));
|
|
1591
|
+
return statusResult(snapshot, await observeAcpFacts(snapshot, snapshot.scope, deps));
|
|
1592
|
+
}
|
|
1593
|
+
/** The `start` handler. */
|
|
1594
|
+
async function runStart(profile, deps) {
|
|
1595
|
+
const inspected = inspectScope(profile, deps);
|
|
1596
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1597
|
+
const hostFacts = await readHostFacts(inspected, deps);
|
|
1598
|
+
if (hostFacts.host === "ready" && hostFacts.authenticated !== void 0) {
|
|
1599
|
+
if (hostFacts.failure !== void 0) throw hostFacts.failure;
|
|
1600
|
+
return {
|
|
1601
|
+
code: 0,
|
|
1602
|
+
stdout: `profile=${profile.name.replace(/[\u0000-\u001f\u007f]/gu, "")}\nhost=ready\ncompatibility=compatible\npid=${String(hostFacts.authenticated.record.hostPid)}\ninstance=${hostFacts.authenticated.identity.instanceId.slice(0, 8)}\n`,
|
|
1603
|
+
stderr: ""
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
if (hostFacts.failure !== void 0) throw hostFacts.failure;
|
|
1607
|
+
if (hostFacts.host !== "stopped" && hostFacts.host !== "starting") throw refuseHostState(hostFacts);
|
|
1608
|
+
const pre = await readSnapshot(profile, deps, inspected, hostFacts);
|
|
1609
|
+
if (pre.failure !== void 0) throw pre.failure;
|
|
1610
|
+
assertNotAborted(deps.signal);
|
|
1611
|
+
const startScope = pre.unit !== void 0 || pre.launchdUnit !== void 0 ? ensureInstalledProfileScopeDirectory(inspected) : ensureInstalledProfileScopeDirectory(materializeBuild(inspected, profile.packageRoot));
|
|
1612
|
+
assertNotAborted(deps.signal);
|
|
1613
|
+
const ensureHost = deps.ensureHost ?? ensureLocalHost;
|
|
1614
|
+
try {
|
|
1615
|
+
await ensureHost({
|
|
1616
|
+
scope: startScope,
|
|
1617
|
+
hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
|
|
1618
|
+
dshAnchor: profile.installAnchor,
|
|
1619
|
+
profile: profile.name,
|
|
1620
|
+
hostStartPolicy: "public"
|
|
1621
|
+
});
|
|
1622
|
+
} catch (error) {
|
|
1623
|
+
throw toDaemonControlError(error);
|
|
1624
|
+
}
|
|
1625
|
+
try {
|
|
1626
|
+
const post = await readSnapshot(profile, deps, startScope);
|
|
1627
|
+
if (post.failure !== void 0) throw post.failure;
|
|
1628
|
+
if (post.status.host !== "ready") throw refuseHostState(post.status);
|
|
1629
|
+
return statusResult(post, {}, { commandSuccess: true });
|
|
1630
|
+
} catch (error) {
|
|
1631
|
+
throw afterCommittedAction(toDaemonControlError(error), "Host start");
|
|
1632
|
+
}
|
|
1633
|
+
});
|
|
1634
|
+
}
|
|
1635
|
+
/** The `stop` handler. */
|
|
1636
|
+
async function runStop(profile, deps) {
|
|
1637
|
+
const inspected = inspectScope(profile, deps);
|
|
1638
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1639
|
+
const pre = await readSnapshot(profile, deps, inspected);
|
|
1640
|
+
if (pre.failure !== void 0 && !verifiedUnitManagementAdmitted(pre) && !verifiedLaunchdManagementAdmitted(pre)) throw pre.failure;
|
|
1641
|
+
assertNotAborted(deps.signal);
|
|
1642
|
+
await stopFromSnapshot(pre, deps);
|
|
1643
|
+
try {
|
|
1644
|
+
const post = await readSnapshot(profile, deps, inspected);
|
|
1645
|
+
if (post.failure !== void 0) throw post.failure;
|
|
1646
|
+
if (post.status.host !== "stopped") throw refuseHostState(post.status);
|
|
1647
|
+
return statusResult(post, {}, {
|
|
1648
|
+
commandSuccess: true,
|
|
1649
|
+
extraStderr: RUNNING_WORK_NOTICE
|
|
1650
|
+
});
|
|
1651
|
+
} catch (error) {
|
|
1652
|
+
throw afterCommittedAction(toDaemonControlError(error), "Host stop");
|
|
1653
|
+
}
|
|
1654
|
+
});
|
|
1655
|
+
}
|
|
1656
|
+
/** The `restart` handler: stop -> confirmed exit -> start. */
|
|
1657
|
+
async function runRestart(profile, deps) {
|
|
1658
|
+
const inspected = inspectScope(profile, deps);
|
|
1659
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1660
|
+
const pre = await readSnapshot(profile, deps, inspected);
|
|
1661
|
+
const launchdLoaded = pre.launchdService?.kind === "loaded" ? pre.launchdService.service : void 0;
|
|
1662
|
+
const launchdVerified = pre.launchdUnit !== void 0 && pre.launchdFacts !== void 0 && launchdLoaded !== void 0 && launchdServiceMatches(pre.launchdFacts, pre.launchdUnit, launchdLoaded);
|
|
1663
|
+
const unitFailureRecovery = verifiedUnitManagementAdmitted(pre) && (pre.record === void 0 || !pre.processAlive || pre.unitMainPid === pre.record.hostPid);
|
|
1664
|
+
const launchdFailureRecovery = launchdVerified && (pre.hostAuthenticationFailed || pre.hostCompatibilityFailed) && (pre.record === void 0 || !pre.processAlive || launchdLoaded?.pid === pre.record.hostPid);
|
|
1665
|
+
const verifiedUnitRestart = pre.unit !== void 0 && pre.userManager === "available" && (pre.unitActiveState === "active" || pre.unitActiveState === "activating") && (pre.record === void 0 || !pre.processAlive || pre.unitMainPid === pre.record.hostPid);
|
|
1666
|
+
const verifiedLaunchdRestart = launchdVerified && launchdLoaded !== void 0 && (launchdLoaded.state === "running" || launchdLoaded.state === "spawn scheduled" || launchdLoaded.state === "not running") && (pre.record === void 0 || !pre.processAlive || launchdLoaded.pid === pre.record.hostPid);
|
|
1667
|
+
const serviceFailureRecovery = unitFailureRecovery || launchdFailureRecovery;
|
|
1668
|
+
if (pre.failure !== void 0 && !serviceFailureRecovery) throw pre.failure;
|
|
1669
|
+
if (pre.status.host !== "ready" && pre.status.host !== "stopped" && !serviceFailureRecovery && !verifiedUnitRestart && !verifiedLaunchdRestart) throw refuseHostState(pre.status);
|
|
1670
|
+
const oldInstance = pre.record?.instanceId;
|
|
1671
|
+
const startScope = pre.unit !== void 0 || pre.launchdUnit !== void 0 ? inspected : materializeBuild(inspected, profile.packageRoot);
|
|
1672
|
+
assertNotAborted(deps.signal);
|
|
1673
|
+
await stopFromSnapshot(pre, deps);
|
|
1674
|
+
try {
|
|
1675
|
+
assertNotAborted(deps.signal);
|
|
1676
|
+
const scope = ensureInstalledProfileScopeDirectory(startScope);
|
|
1677
|
+
await (deps.ensureHost ?? ensureLocalHost)({
|
|
1678
|
+
scope,
|
|
1679
|
+
hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
|
|
1680
|
+
dshAnchor: profile.installAnchor,
|
|
1681
|
+
profile: profile.name,
|
|
1682
|
+
hostStartPolicy: "public"
|
|
1683
|
+
});
|
|
1684
|
+
const post = await readSnapshot(profile, deps, scope);
|
|
1685
|
+
if (post.failure !== void 0) throw post.failure;
|
|
1686
|
+
if (post.status.host !== "ready") throw refuseHostState(post.status);
|
|
1687
|
+
if (pre.unit !== void 0 && post.status.manager !== "systemd") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the restarted Host is not supervised by the verified profile unit");
|
|
1688
|
+
if (oldInstance !== void 0 && post.record?.instanceId === oldInstance) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the restart did not produce a new Host instance");
|
|
1689
|
+
return {
|
|
1690
|
+
code: 0,
|
|
1691
|
+
stdout: `previous=${oldInstance === void 0 ? "none" : oldInstance.slice(0, 8)}\n${formatDaemonStatus(post.status)}`,
|
|
1692
|
+
stderr: RUNNING_WORK_NOTICE
|
|
1693
|
+
};
|
|
1694
|
+
} catch (error) {
|
|
1695
|
+
throw afterCommittedAction(toDaemonControlError(error), "Host restart");
|
|
1696
|
+
}
|
|
1697
|
+
});
|
|
1698
|
+
}
|
|
1699
|
+
/** The `install` handler: explicit unit installation only, never host control. */
|
|
1700
|
+
async function runInstall(profile, intent, deps) {
|
|
1701
|
+
const autostart = intent.autostart === true;
|
|
1702
|
+
if (platformOf(deps) === "win32") return await runWindowsInstall(profile, deps);
|
|
1703
|
+
if (platformOf(deps) === "darwin") return await runDarwinInstall(profile, deps, autostart);
|
|
1704
|
+
const inspected = inspectScope(profile, deps);
|
|
1705
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1706
|
+
assertNotAborted(deps.signal);
|
|
1707
|
+
const installed = await installProfileHostUnit({
|
|
1708
|
+
scope: inspected,
|
|
1709
|
+
hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
|
|
1710
|
+
dshAnchor: profile.installAnchor,
|
|
1711
|
+
profile: profile.name
|
|
1712
|
+
}, managerDepsOf(deps));
|
|
1713
|
+
return {
|
|
1714
|
+
code: 0,
|
|
1715
|
+
stdout: `profile=${profile.name.replace(/[\u0000-\u001f\u007f]/gu, "")}\nunit=${installed.unitName}\n`,
|
|
1716
|
+
stderr: ""
|
|
1717
|
+
};
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1720
|
+
/** The Windows `install --autostart` handler: register the login-only task only. */
|
|
1721
|
+
async function runWindowsInstall(profile, deps) {
|
|
1722
|
+
const inspected = inspectScope(profile, deps);
|
|
1723
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1724
|
+
const profileName = profile.name.replace(/[\u0000-\u001f\u007f]/gu, "");
|
|
1725
|
+
const existing = await inspectWindowsLoginTask(inspected);
|
|
1726
|
+
switch (existing.kind) {
|
|
1727
|
+
case "owned": return {
|
|
1728
|
+
code: 0,
|
|
1729
|
+
stdout: `profile=${profileName}\ntask=${existing.taskName}\n`,
|
|
1730
|
+
stderr: WINDOWS_EXISTING_DEFINITION_NOTE
|
|
1731
|
+
};
|
|
1732
|
+
case "foreign": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the existing Windows login task is not owned by this profile");
|
|
1733
|
+
case "refused": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Windows login task cannot be managed in this user context");
|
|
1734
|
+
case "os-failure": throw new DaemonControlError("MANAGER_OR_OS_FAILURE", existing.reason);
|
|
1735
|
+
}
|
|
1736
|
+
assertNotAborted(deps.signal);
|
|
1737
|
+
const created = await createWindowsLoginTask(inspected, profile);
|
|
1738
|
+
switch (created.kind) {
|
|
1739
|
+
case "created": return {
|
|
1740
|
+
code: 0,
|
|
1741
|
+
stdout: `profile=${profileName}\ntask=${created.taskName}\n`,
|
|
1742
|
+
stderr: ""
|
|
1743
|
+
};
|
|
1744
|
+
case "reused": return {
|
|
1745
|
+
code: 0,
|
|
1746
|
+
stdout: `profile=${profileName}\ntask=${created.taskName}\n`,
|
|
1747
|
+
stderr: WINDOWS_EXISTING_DEFINITION_NOTE
|
|
1748
|
+
};
|
|
1749
|
+
case "foreign": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "a foreign Windows login task already exists");
|
|
1750
|
+
case "refused": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Windows login task cannot be created in this user context");
|
|
1751
|
+
case "uncertain": throw new DaemonControlError("TRANSITION_UNCERTAIN", "the Windows login task creation may already have been committed; check the native Task Scheduler for the exact task");
|
|
1752
|
+
case "os-failure": throw new DaemonControlError("MANAGER_OR_OS_FAILURE", created.reason);
|
|
1753
|
+
}
|
|
1754
|
+
});
|
|
1755
|
+
}
|
|
1756
|
+
/** The Windows `uninstall` handler: remove only the login task; never the Host. */
|
|
1757
|
+
async function runWindowsUninstall(profile, deps) {
|
|
1758
|
+
const inspected = inspectScope(profile, deps);
|
|
1759
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1760
|
+
assertNotAborted(deps.signal);
|
|
1761
|
+
const result = await uninstallWindowsLoginTask(inspected, profile);
|
|
1762
|
+
const profileName = profile.name.replace(/[\u0000-\u001f\u007f]/gu, "");
|
|
1763
|
+
switch (result.kind) {
|
|
1764
|
+
case "absent":
|
|
1765
|
+
case "deleted": return {
|
|
1766
|
+
code: 0,
|
|
1767
|
+
stdout: `profile=${profileName}\ntask=none\n`,
|
|
1768
|
+
stderr: ""
|
|
1769
|
+
};
|
|
1770
|
+
case "refused": throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the Windows login task is not owned by this profile");
|
|
1771
|
+
case "busy":
|
|
1772
|
+
case "uncertain": throw new DaemonControlError("TRANSITION_UNCERTAIN", result.reason);
|
|
1773
|
+
case "os-failure": throw new DaemonControlError("MANAGER_OR_OS_FAILURE", result.reason);
|
|
1774
|
+
}
|
|
1775
|
+
});
|
|
1776
|
+
}
|
|
1777
|
+
/** The current user's real Linger setting, or undefined when it cannot be confirmed. */
|
|
1778
|
+
function queryLingerState(uid) {
|
|
1779
|
+
return new Promise((resolve) => {
|
|
1780
|
+
execFile("loginctl", [
|
|
1781
|
+
"show-user",
|
|
1782
|
+
String(uid),
|
|
1783
|
+
"-p",
|
|
1784
|
+
"Linger",
|
|
1785
|
+
"--value"
|
|
1786
|
+
], {
|
|
1787
|
+
timeout: 3e3,
|
|
1788
|
+
maxBuffer: 4096,
|
|
1789
|
+
encoding: "utf8"
|
|
1790
|
+
}, (error, stdout) => {
|
|
1791
|
+
if (error !== null) {
|
|
1792
|
+
resolve(void 0);
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
const value = stdout.trim();
|
|
1796
|
+
resolve(value === "yes" || value === "no" ? value : void 0);
|
|
1797
|
+
});
|
|
1798
|
+
});
|
|
1799
|
+
}
|
|
1800
|
+
/**
|
|
1801
|
+
* The Linux-only `enable`/`disable` handler. It acts on this Profile's already
|
|
1802
|
+
* installed and manager-verified unit through ONE native request; enablement
|
|
1803
|
+
* never starts, stops or rewrites the Host or its definition.
|
|
1804
|
+
*/
|
|
1805
|
+
async function runUnitEnablement(profile, verb, deps) {
|
|
1806
|
+
if (platformOf(deps) !== "linux") throw new DaemonControlError("UNSUPPORTED_PLATFORM", `daemon ${verb} requires Linux systemd`);
|
|
1807
|
+
const inspected = inspectScope(profile, deps);
|
|
1808
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1809
|
+
assertNotAborted(deps.signal);
|
|
1810
|
+
const systemctl = deps.systemctl ?? runSystemctl;
|
|
1811
|
+
const runtimeDir = runtimeDirOf(deps);
|
|
1812
|
+
let unit;
|
|
1813
|
+
try {
|
|
1814
|
+
unit = inspectOwnedProfileUnit(inspected, profile.name, deps.unitDir);
|
|
1815
|
+
} catch (error) {
|
|
1816
|
+
throw toDaemonControlError(error);
|
|
1817
|
+
}
|
|
1818
|
+
if (unit.kind === "none") throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "no owned unit for this profile; run daemon install first");
|
|
1819
|
+
let before;
|
|
1820
|
+
try {
|
|
1821
|
+
before = await queryOwnedProfileUnit(unit, runtimeDir, systemctl);
|
|
1822
|
+
} catch (error) {
|
|
1823
|
+
throw toDaemonControlError(error);
|
|
1824
|
+
}
|
|
1825
|
+
if (before.loadState === "not-found") throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "the installed unit is not loaded by the user manager; reload or reinstall it first");
|
|
1826
|
+
assertNotAborted(deps.signal);
|
|
1827
|
+
try {
|
|
1828
|
+
await setOwnedProfileUnitEnablement(unit, verb, runtimeDir, systemctl);
|
|
1829
|
+
} catch (error) {
|
|
1830
|
+
const failure = toDaemonControlError(error);
|
|
1831
|
+
if (failure.code === "IDENTITY_OR_OWNERSHIP_REFUSED") throw failure;
|
|
1832
|
+
throw afterCommittedAction(failure, `native ${verb}`);
|
|
1833
|
+
}
|
|
1834
|
+
let state = "not-found";
|
|
1835
|
+
let remaining;
|
|
1836
|
+
try {
|
|
1837
|
+
remaining = inspectOwnedProfileUnit(inspected, profile.name, deps.unitDir);
|
|
1838
|
+
} catch (error) {
|
|
1839
|
+
throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", toDaemonControlError(error).reason), `native ${verb}`);
|
|
1840
|
+
}
|
|
1841
|
+
if (remaining.kind === "owned") {
|
|
1842
|
+
try {
|
|
1843
|
+
state = (await queryOwnedProfileUnit(remaining, runtimeDir, systemctl)).unitFileState;
|
|
1844
|
+
} catch (error) {
|
|
1845
|
+
throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", toDaemonControlError(error).reason), `native ${verb}`);
|
|
1846
|
+
}
|
|
1847
|
+
if (state === "") throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", "the user manager reported no unit-file-state after the native request"), `native ${verb}`);
|
|
1848
|
+
}
|
|
1849
|
+
const profileName = profile.name.replace(/[\u0000-\u001f\u007f]/gu, "");
|
|
1850
|
+
let stderr = "";
|
|
1851
|
+
if (verb === "enable") {
|
|
1852
|
+
const uid = uidOf(deps);
|
|
1853
|
+
const linger = deps.lingerState === void 0 ? await queryLingerState(uid) : await deps.lingerState(uid);
|
|
1854
|
+
if (linger === "no") stderr = "dsh-pi-tui daemon: note: Linger is disabled for the current user. To start at system boot and keep the user manager running after logout, run: loginctl enable-linger\n";
|
|
1855
|
+
else if (linger === void 0) stderr = "dsh-pi-tui daemon: note: Linger could not be confirmed; query loginctl show-user <uid> -p Linger --value manually\n";
|
|
1856
|
+
}
|
|
1857
|
+
if (verb === "enable" && state === "static") stderr += "dsh-pi-tui daemon: note: the native unit-file-state is static; no login enablement was established. If desired, adjust the definition (for example add [Install] with WantedBy=default.target and reload), then run daemon enable again\n";
|
|
1858
|
+
return {
|
|
1859
|
+
code: 0,
|
|
1860
|
+
stdout: `profile=${profileName}\nunit=${unit.unitName}\nunit-file-state=${state}\n`,
|
|
1861
|
+
stderr
|
|
1862
|
+
};
|
|
1863
|
+
});
|
|
1864
|
+
}
|
|
1865
|
+
/** The `uninstall` handler: remove this Profile's service definition only. */
|
|
1866
|
+
async function runUninstall(profile, deps) {
|
|
1867
|
+
if (platformOf(deps) === "win32") return await runWindowsUninstall(profile, deps);
|
|
1868
|
+
if (platformOf(deps) === "darwin") return await runDarwinUninstall(profile, deps);
|
|
1869
|
+
const inspected = inspectScope(profile, deps);
|
|
1870
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1871
|
+
const pre = await readSnapshot(profile, deps, inspected);
|
|
1872
|
+
if (pre.unitInspectionFailure !== void 0) throw pre.unitInspectionFailure;
|
|
1873
|
+
if (pre.unit === void 0) return statusResult(pre, {}, { commandSuccess: true });
|
|
1874
|
+
if (pre.failure !== void 0 && !verifiedUnitManagementAdmitted(pre)) throw pre.failure;
|
|
1875
|
+
if (pre.userManager !== "available") throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "the user manager cannot verify the profile unit");
|
|
1876
|
+
const loaded = pre.unitState !== "not-found";
|
|
1877
|
+
const running = loaded && (pre.unitActiveState === "active" || pre.unitActiveState === "activating");
|
|
1878
|
+
const ended = loaded && (pre.unitActiveState === "inactive" || pre.unitActiveState === "failed");
|
|
1879
|
+
const liveHost = pre.processAlive && pre.record !== void 0;
|
|
1880
|
+
if (loaded && !running && !ended) throw new DaemonControlError("TRANSITION_UNCERTAIN", `the profile unit is in an unconfirmed state (${pre.unitActiveState === "" ? "unknown" : pre.unitActiveState}); refusing to uninstall`);
|
|
1881
|
+
if (running) {
|
|
1882
|
+
if (liveHost && pre.unitMainPid !== pre.record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the profile unit MainPID is not the live Host; refusing to uninstall");
|
|
1883
|
+
const systemctl = deps.systemctl ?? runSystemctl;
|
|
1884
|
+
assertNotAborted(deps.signal);
|
|
1885
|
+
await stopOwnedProfileUnit(pre.unit, runtimeDirOf(deps), systemctl, deps.stopTimeoutMs);
|
|
1886
|
+
const ownHost = liveHost && pre.record !== void 0 && pre.record.hostPid === pre.unitMainPid ? pre.record : void 0;
|
|
1887
|
+
try {
|
|
1888
|
+
await waitForHostStopped(ownHost, pre.unitMainPid, deps);
|
|
1889
|
+
} catch (error) {
|
|
1890
|
+
throw afterCommittedAction(toDaemonControlError(error), "Host stop for uninstall");
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
const systemctl = deps.systemctl ?? runSystemctl;
|
|
1894
|
+
assertNotAborted(deps.signal);
|
|
1895
|
+
try {
|
|
1896
|
+
await setOwnedProfileUnitEnablement(pre.unit, "disable", runtimeDirOf(deps), systemctl);
|
|
1897
|
+
} catch (error) {
|
|
1898
|
+
const failure = toDaemonControlError(error);
|
|
1899
|
+
if (failure.code === "IDENTITY_OR_OWNERSHIP_REFUSED") throw failure;
|
|
1900
|
+
throw afterCommittedAction(failure, "native disable for uninstall");
|
|
1901
|
+
}
|
|
1902
|
+
let removalNeeded = true;
|
|
1903
|
+
try {
|
|
1904
|
+
removalNeeded = inspectOwnedProfileUnit(inspected, profile.name, deps.unitDir).kind === "owned";
|
|
1905
|
+
} catch (error) {
|
|
1906
|
+
throw afterCommittedAction(new DaemonControlError("TRANSITION_UNCERTAIN", toDaemonControlError(error).reason), "native disable for uninstall");
|
|
1907
|
+
}
|
|
1908
|
+
if (removalNeeded) {
|
|
1909
|
+
assertNotAborted(deps.signal);
|
|
1910
|
+
uninstallOwnedProfileUnit(pre.unit);
|
|
1911
|
+
}
|
|
1912
|
+
try {
|
|
1913
|
+
if (removalNeeded) {
|
|
1914
|
+
const reload = await systemctl([
|
|
1915
|
+
"--user",
|
|
1916
|
+
"--no-pager",
|
|
1917
|
+
"--no-ask-password",
|
|
1918
|
+
"daemon-reload"
|
|
1919
|
+
], runtimeDirOf(deps));
|
|
1920
|
+
if (reload.kind !== "exited" || reload.code !== 0) throw new DaemonControlError("MANAGER_OR_OS_FAILURE", "daemon-reload failed after removing the profile unit");
|
|
1921
|
+
}
|
|
1922
|
+
const post = await readSnapshot(profile, deps, inspected);
|
|
1923
|
+
if (post.unitInspectionFailure !== void 0) throw post.unitInspectionFailure;
|
|
1924
|
+
if (post.unitQueryFailure !== void 0) throw post.unitQueryFailure;
|
|
1925
|
+
if (post.unit !== void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the profile unit could not be confirmed removed");
|
|
1926
|
+
return statusResult(post, {}, {
|
|
1927
|
+
commandSuccess: true,
|
|
1928
|
+
extraStderr: running ? RUNNING_WORK_NOTICE : ""
|
|
1929
|
+
});
|
|
1930
|
+
} catch (error) {
|
|
1931
|
+
throw afterCommittedAction(toDaemonControlError(error), "profile unit removal");
|
|
1932
|
+
}
|
|
1933
|
+
});
|
|
1934
|
+
}
|
|
1935
|
+
/** The Darwin `install` handler: explicit LaunchAgent plist only, never host control. */
|
|
1936
|
+
async function runDarwinInstall(profile, deps, autostart) {
|
|
1937
|
+
const inspected = inspectScope(profile, deps);
|
|
1938
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1939
|
+
assertNotAborted(deps.signal);
|
|
1940
|
+
const installed = await installLaunchdUnit(launchdFactsOf(inspected, profile), launchdDepsOf(deps), () => collectLaunchdUnitFacts({
|
|
1941
|
+
scope: autostart ? ensureInstalledProfileScopeDirectory(inspected) : inspected,
|
|
1942
|
+
hostEntryPath: join(profile.packageRoot, "dist", "local-host.mjs"),
|
|
1943
|
+
dshAnchor: profile.installAnchor,
|
|
1944
|
+
profile: profile.name
|
|
1945
|
+
}), { autostart });
|
|
1946
|
+
const profileName = profile.name.replace(/[\u0000-\u001f\u007f]/gu, "");
|
|
1947
|
+
const preserved = autostart && !installed.created ? "dsh-pi-tui daemon: note: existing definition preserved; --autostart applies only to a new installation\n" : "";
|
|
1948
|
+
return {
|
|
1949
|
+
code: 0,
|
|
1950
|
+
stdout: `profile=${profileName}\nunit=${installed.label}\n`,
|
|
1951
|
+
stderr: preserved
|
|
1952
|
+
};
|
|
1953
|
+
});
|
|
1954
|
+
}
|
|
1955
|
+
/** The Darwin `uninstall` handler: remove this Profile's LaunchAgent only. */
|
|
1956
|
+
async function runDarwinUninstall(profile, deps) {
|
|
1957
|
+
const inspected = inspectScope(profile, deps);
|
|
1958
|
+
return await withAdminSeat(inspected, deps, async () => {
|
|
1959
|
+
const pre = await readSnapshot(profile, deps, inspected);
|
|
1960
|
+
if (pre.launchdInspectionFailure !== void 0) throw pre.launchdInspectionFailure;
|
|
1961
|
+
if (pre.launchdUnit === void 0) return statusResult(pre, {}, { commandSuccess: true });
|
|
1962
|
+
if (pre.launchdQueryFailure !== void 0) throw pre.launchdQueryFailure;
|
|
1963
|
+
if (pre.launchdFacts === void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd plist facts are unavailable; refusing to uninstall");
|
|
1964
|
+
const service = pre.launchdService;
|
|
1965
|
+
if (service?.kind === "unknown") throw new DaemonControlError("TRANSITION_UNCERTAIN", "the launchd job state is not recognizable; refusing to uninstall");
|
|
1966
|
+
const loadedService = service?.kind === "loaded" ? service.service : void 0;
|
|
1967
|
+
const liveHost = pre.processAlive && pre.record !== void 0;
|
|
1968
|
+
const running = loadedService !== void 0 && (loadedService.pid !== void 0 || loadedService.state === "running" || loadedService.state === "spawn scheduled");
|
|
1969
|
+
if (running && liveHost && pre.record !== void 0 && loadedService?.pid !== pre.record.hostPid) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job PID is not the live Host; refusing to uninstall");
|
|
1970
|
+
if (running && !liveHost) throw new DaemonControlError("IDENTITY_OR_OWNERSHIP_REFUSED", "the launchd job has a process but no authenticated Host record proves its identity; refusing to uninstall");
|
|
1971
|
+
assertNotAborted(deps.signal);
|
|
1972
|
+
try {
|
|
1973
|
+
const expectedPid = liveHost && pre.record !== void 0 ? pre.record.hostPid : void 0;
|
|
1974
|
+
await uninstallLaunchdUnit(pre.launchdFacts, pre.launchdUnit, launchdDepsOf(deps), expectedPid);
|
|
1975
|
+
if (running && liveHost && pre.record !== void 0) await waitForHostStopped(pre.record, loadedService?.pid ?? pre.record.hostPid, deps);
|
|
1976
|
+
} catch (error) {
|
|
1977
|
+
throw afterCommittedAction(toDaemonControlError(error), "launchd plist removal");
|
|
1978
|
+
}
|
|
1979
|
+
try {
|
|
1980
|
+
const post = await readSnapshot(profile, deps, inspected);
|
|
1981
|
+
if (post.launchdInspectionFailure !== void 0) throw post.launchdInspectionFailure;
|
|
1982
|
+
if (post.launchdUnit !== void 0) throw new DaemonControlError("TRANSITION_UNCERTAIN", "the profile LaunchAgent could not be confirmed removed");
|
|
1983
|
+
return statusResult(post, {}, {
|
|
1984
|
+
commandSuccess: true,
|
|
1985
|
+
extraStderr: running ? RUNNING_WORK_NOTICE : ""
|
|
1986
|
+
});
|
|
1987
|
+
} catch (error) {
|
|
1988
|
+
throw afterCommittedAction(toDaemonControlError(error), "launchd plist removal");
|
|
1989
|
+
}
|
|
1990
|
+
});
|
|
1991
|
+
}
|
|
1992
|
+
/**
|
|
1993
|
+
* Run one fixed `journalctl --user-unit <name>` invocation. `--unit` filters the
|
|
1994
|
+
* SYSTEM unit field, while `--user-unit` selects `_SYSTEMD_USER_UNIT`. The `-n`
|
|
1995
|
+
* value selects recent journal records; display-line limiting happens only
|
|
1996
|
+
* after the captured bytes are sanitized.
|
|
1997
|
+
*/
|
|
1998
|
+
function journalctlArgs(unit, lines) {
|
|
1999
|
+
return [
|
|
2000
|
+
"--user-unit",
|
|
2001
|
+
unit,
|
|
2002
|
+
"--no-pager",
|
|
2003
|
+
"-o",
|
|
2004
|
+
"cat",
|
|
2005
|
+
"-n",
|
|
2006
|
+
String(lines)
|
|
2007
|
+
];
|
|
2008
|
+
}
|
|
2009
|
+
function runJournalctl(unit, lines) {
|
|
2010
|
+
return new Promise((resolve, reject) => {
|
|
2011
|
+
execFile(JOURNALCTL, journalctlArgs(unit, lines), {
|
|
2012
|
+
encoding: "buffer",
|
|
2013
|
+
timeout: JOURNALCTL_TIMEOUT_MS,
|
|
2014
|
+
maxBuffer: JOURNAL_MAX_OUTPUT_BYTES,
|
|
2015
|
+
killSignal: "SIGKILL"
|
|
2016
|
+
}, (error, stdout) => {
|
|
2017
|
+
if (error === null) {
|
|
2018
|
+
resolve({ stdout: stdout.toString("utf8") });
|
|
2019
|
+
return;
|
|
2020
|
+
}
|
|
2021
|
+
const code = error.code;
|
|
2022
|
+
if (code === "ENOENT") {
|
|
2023
|
+
resolve(void 0);
|
|
2024
|
+
return;
|
|
2025
|
+
}
|
|
2026
|
+
if (code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" && error.message === "stdout maxBuffer length exceeded") {
|
|
2027
|
+
resolve({ stdout: `${stdout.toString("utf8")}\n${LOG_TRUNCATION_MARKER}\n` });
|
|
2028
|
+
return;
|
|
2029
|
+
}
|
|
2030
|
+
reject(new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host journal could not be read"));
|
|
2031
|
+
});
|
|
2032
|
+
});
|
|
2033
|
+
}
|
|
2034
|
+
/**
|
|
2035
|
+
* Read a bounded tail of a fixed log. POSIX never follows a final symlink and
|
|
2036
|
+
* opens non-blocking; Windows rejects an identifiable final symlink/non-file
|
|
2037
|
+
* before an ordinary read. Both paths admit only the opened regular file.
|
|
2038
|
+
*/
|
|
2039
|
+
async function tailHostLog(path) {
|
|
2040
|
+
let fd;
|
|
2041
|
+
if (process.platform === "win32") {
|
|
2042
|
+
try {
|
|
2043
|
+
const info = lstatSync(path);
|
|
2044
|
+
if (info.isSymbolicLink() || !info.isFile()) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log is not a regular file");
|
|
2045
|
+
} catch (error) {
|
|
2046
|
+
if (error.code === "ENOENT") return void 0;
|
|
2047
|
+
if (error instanceof DaemonControlError) throw error;
|
|
2048
|
+
throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be inspected");
|
|
2049
|
+
}
|
|
2050
|
+
try {
|
|
2051
|
+
fd = openSync(path, constants.O_RDONLY);
|
|
2052
|
+
} catch (error) {
|
|
2053
|
+
if (error.code === "ENOENT") return void 0;
|
|
2054
|
+
throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be opened");
|
|
2055
|
+
}
|
|
2056
|
+
} else try {
|
|
2057
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
2058
|
+
} catch (error) {
|
|
2059
|
+
if (error.code === "ENOENT") return void 0;
|
|
2060
|
+
throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be opened");
|
|
2061
|
+
}
|
|
2062
|
+
let readFailure;
|
|
2063
|
+
try {
|
|
2064
|
+
const info = fstatSync(fd);
|
|
2065
|
+
if (!info.isFile()) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log is not a regular file");
|
|
2066
|
+
const length = Math.min(info.size, HOST_LOG_MAX_BYTES);
|
|
2067
|
+
const start = info.size - length;
|
|
2068
|
+
const buffer = Buffer.alloc(length);
|
|
2069
|
+
let offset = 0;
|
|
2070
|
+
while (offset < buffer.length) {
|
|
2071
|
+
const read = readSync(fd, buffer, offset, buffer.length - offset, start + offset);
|
|
2072
|
+
if (read <= 0) break;
|
|
2073
|
+
offset += read;
|
|
2074
|
+
}
|
|
2075
|
+
const text = buffer.toString("utf8", 0, offset);
|
|
2076
|
+
return `${start > 0 ? `${LOG_TRUNCATION_MARKER}\n` : ""}${text}`;
|
|
2077
|
+
} catch (error) {
|
|
2078
|
+
readFailure = error instanceof DaemonControlError ? error : new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be read");
|
|
2079
|
+
throw readFailure;
|
|
2080
|
+
} finally {
|
|
2081
|
+
try {
|
|
2082
|
+
closeSync(fd);
|
|
2083
|
+
} catch {
|
|
2084
|
+
if (readFailure === void 0) throw new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "the Host log could not be closed");
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
}
|
|
2088
|
+
/** Remove terminal control sequences and best-effort secret material. */
|
|
2089
|
+
function sanitizeLogText(text) {
|
|
2090
|
+
return stripVTControlCharacters(text).replace(/\r\n/gu, "\n").replace(/\r/gu, " ").replace(/\t/gu, " ").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/gu, "").split("\n").map((line) => line.replace(/\b((?:proxy-)?authorization|x-api-key|x-auth-token|cookie|set-cookie|secret|password)\s*[:=]\s*.*$/gimu, "$1=[redacted]").replace(/\b(token|access_token|refresh_token|api[_-]?key)\s*[:=]\s*[^\s&]+/gimu, "$1=[redacted]").replace(/([?&](?:token|key|secret|password)=)[^&\s]+/gimu, "$1[redacted]").replace(/https?:\/\/[^\s"']*(?:token=|key=|secret=|password=)[^\s"']*/giu, "[redacted-url]").replace(/\bconnectUrl\b[^\s]*/giu, "connectUrl=[redacted]").slice(0, MAX_LOG_LINE_LENGTH)).join("\n");
|
|
2091
|
+
}
|
|
2092
|
+
/**
|
|
2093
|
+
* Read the Profile's fixed historical diagnostic sources without asserting
|
|
2094
|
+
* which Host instance produced them. A source failure is a safe warning, never
|
|
2095
|
+
* a reason to discard another source's real content.
|
|
2096
|
+
*/
|
|
2097
|
+
async function runLogs(profile, intent, deps) {
|
|
2098
|
+
const scope = inspectScope(profile, deps);
|
|
2099
|
+
const platform = platformOf(deps);
|
|
2100
|
+
const lines = intent.lines ?? 100;
|
|
2101
|
+
const sections = [];
|
|
2102
|
+
const warnings = [];
|
|
2103
|
+
const tail = deps.hostLogTail ?? tailHostLog;
|
|
2104
|
+
const warn = (source, reason) => {
|
|
2105
|
+
warnings.push(`dsh-pi-tui daemon: warning: ${source} unavailable (${reason})\n`);
|
|
2106
|
+
};
|
|
2107
|
+
const append = (label, raw) => {
|
|
2108
|
+
const rawRecords = raw.split("\n");
|
|
2109
|
+
while (rawRecords.length > 0 && rawRecords[rawRecords.length - 1] === "") rawRecords.pop();
|
|
2110
|
+
let truncated = false;
|
|
2111
|
+
if (rawRecords[0] === "[dsh-pi-tui daemon: log output truncated]") {
|
|
2112
|
+
truncated = true;
|
|
2113
|
+
rawRecords.shift();
|
|
2114
|
+
}
|
|
2115
|
+
if (rawRecords[rawRecords.length - 1] === "[dsh-pi-tui daemon: log output truncated]") {
|
|
2116
|
+
truncated = true;
|
|
2117
|
+
rawRecords.pop();
|
|
2118
|
+
}
|
|
2119
|
+
const records = sanitizeLogText(rawRecords.join("\n")).split("\n");
|
|
2120
|
+
while (records.length > 0 && records[records.length - 1] === "") records.pop();
|
|
2121
|
+
if (records.length > lines) {
|
|
2122
|
+
records.splice(0, records.length - lines);
|
|
2123
|
+
truncated = true;
|
|
2124
|
+
}
|
|
2125
|
+
const body = records.join("\n");
|
|
2126
|
+
if (body.trim() === "") return false;
|
|
2127
|
+
sections.push(`[dsh-pi-tui daemon: ${label}]\n${body}\n${truncated ? `${LOG_TRUNCATION_MARKER}\n` : ""}`);
|
|
2128
|
+
return true;
|
|
2129
|
+
};
|
|
2130
|
+
const readFile = async (label, source, path) => {
|
|
2131
|
+
let value;
|
|
2132
|
+
try {
|
|
2133
|
+
value = await tail(path);
|
|
2134
|
+
} catch (error) {
|
|
2135
|
+
if (!(error instanceof DaemonControlError) || error.code !== "LOG_SOURCE_UNAVAILABLE") throw error;
|
|
2136
|
+
warn(source, "file could not be read");
|
|
2137
|
+
return;
|
|
2138
|
+
}
|
|
2139
|
+
if (value !== void 0) append(label, value);
|
|
2140
|
+
};
|
|
2141
|
+
await readFile("host.log", "host.log", join(scope.dir, "host.log"));
|
|
2142
|
+
if (platform === "darwin") {
|
|
2143
|
+
const fixed = launchdLogPaths(scope.dir);
|
|
2144
|
+
await readFile("launchd stdout", "launchd stdout", fixed.stdout);
|
|
2145
|
+
await readFile("launchd stderr", "launchd stderr", fixed.stderr);
|
|
2146
|
+
} else if (platform === "linux") try {
|
|
2147
|
+
const result = await (deps.journal ?? runJournalctl)(buildUnitName(profile.name, scope.scopeId), lines);
|
|
2148
|
+
if (result !== void 0 && !append("systemd user-unit journal", result.stdout) && result.stdout.includes("[dsh-pi-tui daemon: log output truncated]")) warn("systemd user-unit journal", "journal produced no readable content");
|
|
2149
|
+
} catch (error) {
|
|
2150
|
+
if (!(error instanceof DaemonControlError) || error.code !== "LOG_SOURCE_UNAVAILABLE") throw error;
|
|
2151
|
+
warn("systemd user-unit journal", "journal could not be read");
|
|
2152
|
+
}
|
|
2153
|
+
if (sections.length === 0) {
|
|
2154
|
+
const failure = new DaemonControlError("LOG_SOURCE_UNAVAILABLE", "no Host log content is available for this profile");
|
|
2155
|
+
return {
|
|
2156
|
+
code: 4,
|
|
2157
|
+
stdout: "",
|
|
2158
|
+
stderr: `${warnings.join("")}${formatDaemonControlError(failure)}`
|
|
2159
|
+
};
|
|
2160
|
+
}
|
|
2161
|
+
return {
|
|
2162
|
+
code: 0,
|
|
2163
|
+
stdout: sections.join("\n"),
|
|
2164
|
+
stderr: `${warnings.join("")}${LOG_SANITIZATION_NOTICE}`
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* Run ONE daemon management command for ONE official Profile. Every failure is
|
|
2169
|
+
* mapped to the fixed stable code/exit taxonomy; no raw Error message, command
|
|
2170
|
+
* argv, Host URL, Cookie or private path reaches stdout/stderr.
|
|
2171
|
+
*/
|
|
2172
|
+
async function runDaemonControl(intent, profile, deps = {}) {
|
|
2173
|
+
try {
|
|
2174
|
+
const platform = platformOf(deps);
|
|
2175
|
+
if (intent.verb === "install" && intent.autostart === true && platform !== "darwin" && platform !== "win32") throw new DaemonControlError("UNSUPPORTED_PLATFORM", "daemon install --autostart is supported on macOS and Windows only; use daemon install (and daemon enable on Linux)");
|
|
2176
|
+
if (platform === "win32" && intent.verb === "install" && intent.autostart !== true) throw new DaemonControlError("UNSUPPORTED_PLATFORM", "Windows has no service manager; use daemon install --autostart to register the login-only task");
|
|
2177
|
+
switch (intent.verb) {
|
|
2178
|
+
case "status": return await runStatus(profile, deps);
|
|
2179
|
+
case "start": return await runStart(profile, deps);
|
|
2180
|
+
case "stop": return await runStop(profile, deps);
|
|
2181
|
+
case "restart": return await runRestart(profile, deps);
|
|
2182
|
+
case "logs": return await runLogs(profile, intent, deps);
|
|
2183
|
+
case "install": return await runInstall(profile, intent, deps);
|
|
2184
|
+
case "uninstall": return await runUninstall(profile, deps);
|
|
2185
|
+
case "enable": return await runUnitEnablement(profile, "enable", deps);
|
|
2186
|
+
case "disable": return await runUnitEnablement(profile, "disable", deps);
|
|
2187
|
+
}
|
|
2188
|
+
} catch (error) {
|
|
2189
|
+
const failure = toDaemonControlError(error);
|
|
2190
|
+
const notice = intent.verb === "stop" || intent.verb === "restart" ? RUNNING_WORK_NOTICE : "";
|
|
2191
|
+
return {
|
|
2192
|
+
code: failure.exitCode,
|
|
2193
|
+
stdout: "",
|
|
2194
|
+
stderr: `${formatDaemonControlError(failure)}${notice}`
|
|
2195
|
+
};
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
//#endregion
|
|
2199
|
+
export { readAcpStdioTarget, runDaemonControl };
|