The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
/**
* The two Windows scripts behind guest sharing (docs/superpowers/specs/2026-11-05-windows-guests-design.md):
*
* - the elevated installer, run once behind UAC, which makes the **Harness Guests** group, the guest tree
* (`C:\ProgramData\HarnessGuests`, never under the Users-readable Team folder), the privacy sentinel and the
* `\Harness\Harness Guests Setup` SYSTEM task;
* - the processor that task runs, which accepts exactly one validated request file and performs one of
* `ensure`, `share`, `unshare`, `remove`. It is the only code that creates an account, changes an ACL or deletes a
* profile, and it never takes a command line from the owner or a guest.
*
* Values go in single-quoted (`ps`), assigned once. The processor reads its request as JSON at run time, so no value
* from a person is ever interpolated into PowerShell source. Account passwords are made inside the processor and handed
* only to Task Scheduler's COM call, as the Team setup does.
*/
import { ps } from '../../team/windowsScript.js'
import { WINDOWS_GUEST_ANSWERS, WINDOWS_GUEST_RECORDS, WINDOWS_GUEST_REQUESTS, WINDOWS_GUEST_ROOT,
WINDOWS_GUEST_SCRIPTS, WINDOWS_GUEST_SETUP_VERSION, WINDOWS_GUEST_VERSION_FILE } from './guestRequests.js'
import { WINDOWS_GUEST_TASK, WINDOWS_GUEST_TASK_NAME, WINDOWS_GUEST_TASK_PATH } from './guestSetupClient.js'
export { WINDOWS_GUEST_SETUP_VERSION, WINDOWS_GUEST_VERSION_FILE }
export const WINDOWS_GUEST_GROUP = 'Harness Guests'
export const WINDOWS_GUEST_SENTINEL = '.harness-guest-privacy'
/** The guest tree, as SDDL: SYSTEM/Administrators full; guests read/execute only where a harness needs it. */
export const GUEST_SDDL = {
root: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x20;;;$guestSid)(A;OICI;0x1200a9;;;$OWNER_SID)"',
requests: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;$OWNER_SID)"',
answers: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;$OWNER_SID)"',
records: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;$OWNER_SID)"',
runtime: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;$OWNER_SID)(A;OICI;0x1200a9;;;$guestSid)"',
} as const
const PRELUDE = [
"$ErrorActionPreference = 'Stop'",
"$ProgressPreference = 'SilentlyContinue'",
'[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)',
'function say([string]$m) { [Console]::Out.Write("harness: $m`n") }',
'function die([string]$m, [int]$code = 1) { [Console]::Error.Write("harness: $m`n"); exit $code }',
'trap { die ($_.Exception.Message + " at " + $_.InvocationInfo.PositionMessage) 1 }',
"$ADMINS = 'S-1-5-32-544'",
"$USERS = 'S-1-5-32-545'",
"$SYSTEM_SID = 'S-1-5-18'",
"$ICACLS = Join-Path $env:SystemRoot 'System32\\icacls.exe'",
"$POWERSHELL = Join-Path $env:SystemRoot 'System32\\WindowsPowerShell\\v1.0\\powershell.exe'",
"$CMD = Join-Path $env:SystemRoot 'System32\\cmd.exe'",
'$REPARSE = [IO.FileAttributes]::ReparsePoint',
'function Owner-Of([string]$path) { (Get-Acl -LiteralPath $path).GetOwner([Security.Principal.SecurityIdentifier]).Value }',
'function Item-At([string]$path) { Get-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue }',
'function Set-Folder([string]$path, [string]$sddl) {',
' $item = Item-At $path',
' if ($item) {',
' if (-not $item.PSIsContainer -or ($item.Attributes -band $REPARSE)) { die "$path is not a plain folder" 6 }',
' $owner = Owner-Of $path',
' if ($owner -ne $ADMINS -and $owner -ne $SYSTEM_SID) { die "$path does not belong to Administrators" 6 }',
' } else {',
' $made = New-Object Security.AccessControl.DirectorySecurity',
' $made.SetSecurityDescriptorSddlForm($sddl)',
' [void][IO.Directory]::CreateDirectory($path, $made)',
' }',
' $acl = New-Object Security.AccessControl.DirectorySecurity',
" $acl.SetSecurityDescriptorSddlForm($sddl, 'Access')",
' (Item-At $path).SetAccessControl($acl)',
'}',
"if ($env:OS -ne 'Windows_NT') { die 'guest sharing is for Windows' 3 }",
'if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {',
" die 'run as an administrator (User Account Control)' 3",
'}',
"if ($env:ProgramData -ne 'C:\\ProgramData') { die \"guest sharing needs C:\\ProgramData (this computer's is $env:ProgramData)\" 3 }",
]
export interface WindowsGuestInstallInput {
owner: string
ownerHome: string
ownerSid: string
/** The processor text, staged next to the installer. */
processor: string
version: string
/** The signed harness-pty.exe to stage for guests; null when this build has none. */
ptySrc?: string | null
/** The Node runtime's folder (node.exe and npm) to stage so a guest can install its engine; null when this build has none. */
nodeSrc?: string | null
}
/**
* One elevated run. It creates the group and the tree with their ACLs in one step, writes the processor and the version,
* makes the owner's privacy sentinel if it is missing, and registers the SYSTEM task with a security descriptor that
* lets the owner start it **without elevation** and gives every signed-in account only read access. It never creates a
* guest account: that is the processor's job, one request at a time.
*/
export function buildWindowsGuestInstallScript(input: WindowsGuestInstallInput): string {
if (!/^[A-Za-z0-9_.-]{1,20}$/.test(input.owner)) throw new Error('not an owner account')
if (!/^S-1-\d+(-\d+)+$/.test(input.ownerSid)) throw new Error('not an owner SID')
if (!/^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/.test(input.version) || input.version === '.' || input.version === '..') throw new Error('not a version')
return [
'# Harness guest sharing install (cli/src/lib/windows/guestScript.ts), run once elevated behind User Account Control.',
'# Running it again repairs the group, tree, sentinel and task; it never removes a guest.',
...PRELUDE,
`$OWNER = ${ps(input.owner)}`,
`$OWNER_HOME = ${ps(input.ownerHome)}`,
`$OWNER_SID = ${ps(input.ownerSid)}`,
`$GROUP = ${ps(WINDOWS_GUEST_GROUP)}`,
`$ROOT = ${ps(WINDOWS_GUEST_ROOT)}`,
`$REQ = ${ps(WINDOWS_GUEST_REQUESTS)}`,
`$ANS = ${ps(WINDOWS_GUEST_ANSWERS)}`,
`$REC = ${ps(WINDOWS_GUEST_RECORDS)}`,
`$SCRIPTS = ${ps(WINDOWS_GUEST_SCRIPTS)}`,
`$BIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin`)}`,
`$HOSTS = ${ps(`${WINDOWS_GUEST_ROOT}\\hosts`)}`,
`$PTY_SRC = ${ps(input.ptySrc ?? '')}`,
`$NODE_SRC = ${ps(input.nodeSrc ?? '')}`,
`$VERSION_FILE = ${ps(WINDOWS_GUEST_VERSION_FILE)}`,
`$TASK_PATH = ${ps(WINDOWS_GUEST_TASK_PATH)}`,
`$HOST_TASK_PATH = ${ps('\\Harness\\Guests\\')}`,
`$TASK_NAME = ${ps(WINDOWS_GUEST_TASK_NAME)}`,
`$TASK = ${ps(WINDOWS_GUEST_TASK)}`,
`$SENTINEL = ${ps(`${input.ownerHome}\\${WINDOWS_GUEST_SENTINEL}`)}`,
`$PROCESSOR = ${ps(`${WINDOWS_GUEST_SCRIPTS}\\process.ps1`)}`,
`$VERSION = ${ps(input.version)}`,
// The staged runtime's folder, named for the setup version the installer wrote: the daemon computes the same one
// (lib/windows/guestEngine.ts `guestNodeDir`).
`$NODEBIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin\\node-${input.version}`)}`,
'',
'# 1. The group. Guests join it; it is never Administrators.',
'$existingGroup = Get-LocalGroup -Name $GROUP -ErrorAction SilentlyContinue',
'if (-not $existingGroup) { New-LocalGroup -Name $GROUP -Description "People this computer is shared with" | Out-Null }',
'$guestSid = (Get-LocalGroup -Name $GROUP).SID.Value',
'say "the group $GROUP is $guestSid"',
'',
'# 2. The tree. Its own root, never under C:\\ProgramData\\Harness: that folder is Users-readable for the Team account.',
// SDDL must be built at run time: a single-quoted string would pass "$guestSid" to the ACL parser literally.
'Set-Folder $ROOT ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x20;;;" + $guestSid + ")(A;OICI;0x1200a9;;;" + $OWNER_SID + ")")',
'Set-Folder $REQ ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;" + $OWNER_SID + ")")',
'Set-Folder $ANS ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;" + $OWNER_SID + ")")',
'Set-Folder $REC ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;" + $OWNER_SID + ")")',
// The hosts root is listable by guests, as the macOS guests' home root is: npm stats its way up from a guest's own
// engines folder (`hosts\<user>\engines`), and a list of `hg_<hex>` names is all it may see — each home inside keeps
// its own guest-only ACL (`Set-GuestHost`).
'Set-Folder $HOSTS ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;" + $OWNER_SID + ")(A;OICI;0x1200a9;;;" + $guestSid + ")")',
'Set-Folder $SCRIPTS ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;" + $OWNER_SID + ")(A;OICI;0x1200a9;;;" + $guestSid + ")")',
'',
'# 3. The processor. Base64, so no here-string inside the processor can end this script\'s. Written new, then renamed.',
`$next = $PROCESSOR + '.next-' + [guid]::NewGuid().ToString('N')`,
`$processorB64 = ${ps(Buffer.from(input.processor, 'utf8').toString('base64'))}`,
'[IO.File]::WriteAllText($next, [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($processorB64)))',
'Move-Item -LiteralPath $next -Destination $PROCESSOR -Force',
// The guest runs this file, not a quoted -Command: cmd.exe was mangling braces and quotes, and a parse error
// looked exactly like "the guest read the sentinel".
"$probe = Join-Path $SCRIPTS 'probe.ps1'",
"$probeNext = $probe + '.next-' + [guid]::NewGuid().ToString('N')",
`$probeText = "try { [IO.File]::ReadAllText('$SENTINEL') | Out-Null; exit 9 } catch { exit 0 }"`,
'[IO.File]::WriteAllText($probeNext, $probeText)',
'Move-Item -LiteralPath $probeNext -Destination $probe -Force',
"if ($PTY_SRC) {",
" Set-Folder $BIN (\"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;\" + $OWNER_SID + \")(A;OICI;0x1200a9;;;\" + $guestSid + \")\")",
// A setup re-run after an update stages the new host beside the old one (a running host keeps its file open) and
// ends every guest's host first, so the next harness starts the new build. A version already staged and in use is
// the same file: it stays (a re-run of one version never replaces a running binary with itself).
` $PTYBIN = Join-Path $BIN ('pty-' + $VERSION)`,
' Set-Folder $PTYBIN ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;" + $OWNER_SID + ")(A;OICI;0x1200a9;;;" + $guestSid + ")")',
' Get-ScheduledTask -TaskPath $HOST_TASK_PATH -ErrorAction SilentlyContinue | ForEach-Object { try { Stop-ScheduledTask -TaskName $_.TaskName -TaskPath $_.TaskPath -ErrorAction Stop } catch {} }',
' Get-LocalUser | Where-Object { $_.Name -like \'hg_*\' } | ForEach-Object {',
' & (Join-Path $env:SystemRoot "System32\\taskkill.exe") /F /IM harness-pty.exe /FI ("USERNAME eq " + $env:COMPUTERNAME + "\\" + $_.Name) 2>$null | Out-Null',
' }',
' try { Copy-Item -LiteralPath $PTY_SRC -Destination (Join-Path $PTYBIN "harness-pty.exe") -Force -ErrorAction Stop }',
' catch { if (-not (Test-Path -LiteralPath (Join-Path $PTYBIN "harness-pty.exe"))) { die "the terminal host could not be staged: $($_.Exception.Message)" 9 } }',
'}',
// The Node runtime guests' engines are installed with (node.exe beside npm), in a folder named for this setup version
// so a host running from an older one is never overwritten under it. The marker says the copy finished; a copy that
// stopped part-way is made again. It inherits $BIN's guest read/execute.
"if ($NODE_SRC) {",
" $nodeMark = Join-Path $NODEBIN '.complete'",
" if (-not (Test-Path -LiteralPath $nodeMark)) {",
" if (Test-Path -LiteralPath $NODEBIN) { Remove-Item -LiteralPath $NODEBIN -Recurse -Force }",
" try { Copy-Item -LiteralPath $NODE_SRC -Destination $NODEBIN -Recurse -Force } catch { die \"could not stage the Node runtime for guests: $($_.Exception.Message)\" 7 }",
" [IO.File]::WriteAllText($nodeMark, \"ok`r`n\")",
' }',
'}',
// Guests that were here before this setup version: their task still runs the wrapper written for the old host and
// Node. The task path and its password do not change, and their hosts were stopped above, so the wrapper is rewritten
// in place with this version's binary and PATH. Only when a host was staged: a build with no pty (a dev bundle) must
// never rewrite a working wrapper to name nothing.
"if ($PTYBIN -and (Test-Path -LiteralPath (Join-Path $PTYBIN 'harness-pty.exe'))) {",
" Get-ChildItem -LiteralPath $HOSTS -Directory -Filter 'hg_*' -ErrorAction SilentlyContinue | ForEach-Object {",
" $wrapper = Join-Path $_.FullName 'host.cmd'",
' if (-not (Test-Path -LiteralPath $wrapper)) { return }',
" $tag = 'gu' + $_.Name.Substring(3)",
' $text = "@echo off`r`nset `"HARNESS_PTY_SHARE_SID=$OWNER_SID`"`r`nset `"HARNESS_PTY_INSTANCE_TAG=$tag`"`r`nset `"PATH=$($_.FullName)\\engines;%USERPROFILE%\\.local;$NODEBIN;%PATH%`"`r`n`"$PTYBIN\\harness-pty.exe`" serve --home `"$($_.FullName)`"`r`n"',
' [IO.File]::WriteAllText($wrapper, $text)',
' }',
'}',
'',
'# 4. The privacy sentinel: inherited ACL, owned by the owner, checked as a guest on every ensure.',
'$old = Item-At $SENTINEL',
'if ($old) { if ($old.PSIsContainer -or ($old.Attributes -band $REPARSE)) { die "$SENTINEL is not a plain file" 6 } }',
'else {',
' $rights = [Security.AccessControl.FileSystemRights]::Write',
' $f = New-Object IO.FileStream($SENTINEL, [IO.FileMode]::CreateNew, $rights, [IO.FileShare]::None, 4096, [IO.FileOptions]::None)',
' try { $b = [Text.Encoding]::UTF8.GetBytes("Harness guest privacy check. A guest must not read this file.`r`n"); $f.Write($b, 0, $b.Length) } finally { $f.Dispose() }',
'}',
'',
'# 5. The SYSTEM setup task. Its SD lets the owner start it unelevated (FRFX on the owner SID) and lets any signed-in',
'# account read it; a guest has neither. It cannot run twice at once, and it has no trigger: only the owner starts it.',
"$sddl = 'D:(A;;FA;;;SY)(A;;FA;;;BA)(A;;FRFX;;;' + $OWNER_SID + ')'",
'$taskXml = @\'',
'<?xml version="1.0" encoding="UTF-16"?>',
'<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
' <RegistrationInfo><Description>Harness guest setup: one validated request at a time, as SYSTEM.</Description>',
' <SecurityDescriptor>D:(A;;FA;;;SY)(A;;FA;;;BA)(A;;FRFX;;;__OWNER_SID__)</SecurityDescriptor></RegistrationInfo>',
' <Principals><Principal id="Setup"><RunLevel>HighestAvailable</RunLevel></Principal></Principals>',
' <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>',
' <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled>',
' <Hidden>true</Hidden><ExecutionTimeLimit>PT15M</ExecutionTimeLimit><Priority>4</Priority></Settings>',
' <Actions Context="Setup"><Exec><Command>__POWERSHELL__</Command>',
' <Arguments>-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "__PROCESSOR__"</Arguments></Exec></Actions>',
'</Task>',
"'@",
'$taskXml = $taskXml.Replace("__OWNER_SID__", $OWNER_SID).Replace("__POWERSHELL__", $POWERSHELL).Replace("__PROCESSOR__", $PROCESSOR)',
'$scheduler = New-Object -ComObject Schedule.Service',
'$scheduler.Connect()',
"$folderName = $TASK_PATH.Trim('\\')",
"try { $folder = $scheduler.GetFolder(\"\\$folderName\") } catch { $folder = $scheduler.GetFolder('\\').CreateFolder($folderName) }",
"try { [void]$folder.RegisterTask($TASK_NAME, $taskXml, 6, 'SYSTEM', $null, 5, $sddl) }",
'catch { die "Task Scheduler would not take the guest setup task ($($_.Exception.Message))" 8 }',
// Last: a tree that failed to stage must read as "not set up", never as ready.
'[IO.File]::WriteAllText($VERSION_FILE, "$VERSION`r`n")',
'say "the guest setup task $TASK runs as SYSTEM; $OWNER can start it without elevation"',
'exit 0',
'',
].join('\n')
}
/** The processor's PowerShell. Kept as one function so its text can be tested without a Windows machine. */
export function buildWindowsGuestProcessorScript(input: { owner: string; ownerHome: string; ownerSid: string; version?: string }): string {
if (!/^[A-Za-z0-9_.-]{1,20}$/.test(input.owner)) throw new Error('not an owner account')
if (!input.ownerHome.startsWith('C:\\Users\\')) throw new Error('not an owner profile')
if (!/^S-1-\d+(-\d+)+$/.test(input.ownerSid)) throw new Error('not an owner SID')
const version = input.version ?? String(WINDOWS_GUEST_SETUP_VERSION)
if (!/^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/.test(version) || version === '.' || version === '..') throw new Error('not a version')
return [
'# Harness guest setup processor (cli/src/lib/windows/guestScript.ts), run by the SYSTEM task. No arguments: it',
'# accepts exactly one request file, checks it, performs one operation, writes one answer and deletes the request.',
...PRELUDE,
`$OWNER = ${ps(input.owner)}`,
`$OWNER_HOME = ${ps(input.ownerHome)}`,
`$OWNER_SID = ${ps(input.ownerSid)}`,
`$BIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin`)}`,
`$PTY_BIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin\\pty-${version}\\harness-pty.exe`)}`,
`$NODEBIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin\\node-${version}`)}`,
`$HOSTS = ${ps(`${WINDOWS_GUEST_ROOT}\\hosts`)}`,
`$HOST_TASK_PATH = ${ps('\\Harness\\Guests\\')}`,
`$SENTINEL = ${ps(`${input.ownerHome}\\${WINDOWS_GUEST_SENTINEL}`)}`,
`$ROOT = ${ps(WINDOWS_GUEST_ROOT)}`,
`$REQ = ${ps(WINDOWS_GUEST_REQUESTS)}`,
`$ANS = ${ps(WINDOWS_GUEST_ANSWERS)}`,
`$REC = ${ps(WINDOWS_GUEST_RECORDS)}`,
`$GROUP = ${ps(WINDOWS_GUEST_GROUP)}`,
"$MAX_FOLDERS = 20",
"$REPARSE = [IO.FileAttributes]::ReparsePoint",
'function Answer($id, $ok, $detail, $user, $guestHome, $workspace) {',
' $body = [ordered]@{ id = $id; ok = [bool]$ok }',
' if ($ok) { $body.user = $user; $body.home = $guestHome; $body.workspace = $workspace; if ($detail) { $body.detail = $detail } } else { $body.detail = $detail }',
' $next = Join-Path $ANS ($id + ".next")',
' [IO.File]::WriteAllText($next, ($body | ConvertTo-Json -Compress))',
' Move-Item -LiteralPath $next -Destination (Join-Path $ANS ($id + ".json")) -Force',
'}',
'function Refuse($id, [string]$detail) { Answer $id $false $detail $null $null $null; exit 0 }',
'function Guest-Sid([string]$user) { (Get-LocalUser -Name $user -ErrorAction Stop).SID.Value }',
'function Guest-Exists([string]$user) { [bool](Get-LocalUser -Name $user -ErrorAction SilentlyContinue) }',
'function Guest-Home([string]$user) { "C:\\Users\\$user" }',
'function Guest-Workspace([string]$user) { (Guest-Home $user) + "\\work" }',
'function Guest-Name([string]$email) {',
' $sha = [Security.Cryptography.SHA256]::Create()',
' try { $hex = -join ($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($email)) | ForEach-Object { $_.ToString("x2") }) } finally { $sha.Dispose() }',
' return "hg_" + $hex.Substring(0, 12)',
'}',
'function Check-Path([string]$path) {',
' if ($path -notmatch \'^[A-Za-z]:\\\\\' -or $path.Length -gt 259 -or $path.Substring(3) -match \'[<>:"|?*]\' -or $path -match \'\\\\$\') { throw "not a plain absolute Windows path" }',
' $full = [IO.Path]::GetFullPath($path)',
' if ($full -ne $path) { throw "not a normalized path: $path" }',
' $parts = $path.Substring(3).Split("\\")',
' if ($parts.Count -eq 0 -or ($parts | Where-Object { $_ -eq "" -or $_ -eq "." -or $_ -eq ".." -or $_ -match \'[. ]$\' -or $_ -match \'^(?i:con|prn|aux|nul|com[1-9]|lpt[1-9])(\\.|$)\' })) { throw "not a plain folder name" }',
' $lower = $path.ToLowerInvariant()',
' foreach ($root in @("c:\\windows", "c:\\program files", "c:\\program files (x86)", "c:\\programdata", "c:\\`$recycle.bin", "c:\\system volume information", "c:\\recovery", "c:\\boot", "c:\\perflogs")) {',
' if ($lower -eq $root -or $lower.StartsWith($root + "\\")) { throw "$path cannot be shared" }',
' }',
' if ($parts.Count -eq 1 -and $parts[0] -ieq "Users") { throw "the folder that holds every profile cannot be shared" }',
' if ($parts[0] -ieq "Users" -and $parts.Count -ge 2 -and $parts[1] -ine $OWNER -and $parts[1] -notin @("Public", "Default", "Default User", "All Users")) { throw "another user profile cannot be shared" }',
' $at = $path',
' while ($at -and $at.Length -gt 3) {',
' $item = Item-At $at',
' if ($item -and ($item.Attributes -band $REPARSE)) { throw "$at is a junction or another reparse point" }',
' $at = Split-Path -Parent $at',
' }',
' return $full',
'}',
'function Ancestors([string]$path) {',
' $parts = $path.Substring(3).Split("\\")',
' $out = @()',
' for ($i = 1; $i -lt $parts.Count; $i++) { $out += ($path.Substring(0, 2) + "\\" + (($parts[0..($i - 1)]) -join "\\")) }',
' return $out',
'}',
'function Ace([string]$level) { if ($level -eq "read") { "(OI)(CI)(RX)" } elseif ($level -eq "edit") { "(OI)(CI)M" } else { "(X)" } }',
'function Apply-Ace([string]$user, [string]$sid, [string]$path, [string]$level) {',
' & $ICACLS $path /grant:r ("*" + $sid + ":" + (Ace $level)) /L /q | Out-Null',
' if ($LASTEXITCODE -ne 0) { throw "icacls could not grant $level on $path" }',
'}',
'function Remove-Ace([string]$sid, [string]$path) {',
' & $ICACLS $path /remove:g ("*" + $sid) /L /q | Out-Null',
' if ($LASTEXITCODE -ne 0) { throw "icacls could not remove access on $path" }',
'}',
'function Record-Of([string]$user) {',
' $file = Join-Path $REC ($user + ".json")',
' if (-not (Test-Path -LiteralPath $file)) { return @() }',
' return @(Get-Content -LiteralPath $file -Raw | ConvertFrom-Json)',
'}',
'function Save-Record([string]$user, $entries) {',
' $next = Join-Path $REC ($user + ".next")',
' [IO.File]::WriteAllText($next, (ConvertTo-Json -InputObject @($entries) -Compress))',
' Move-Item -LiteralPath $next -Destination (Join-Path $REC ($user + ".json")) -Force',
'}',
'function Share([string]$user, $folders) {',
' $sid = Guest-Sid $user',
' if (-not $sid) { throw "the guest account $user is not here" }',
' if (@($folders).Count -gt $MAX_FOLDERS) { throw "at most $MAX_FOLDERS folders can be shared" }',
' $desired = [ordered]@{}',
' foreach ($folder in @($folders)) {',
' $path = Check-Path ([string]$folder.path)',
' if ($folder.write -isnot [bool]) { throw "a folder needs write true or false" }',
' $level = if ($folder.write) { "edit" } else { "read" }',
' $key = $path.ToLowerInvariant()',
' if ($desired.Contains($key)) { throw "the folder $path is named twice" }',
' $desired[$key] = @{ path = $path; level = $level }',
' }',
'# Windows Bypass traverse checking: no parent ACE. Only the folder itself is granted.',
' $before = @{}',
' foreach ($entry in @(Record-Of $user)) { $before[[string]$entry.path.ToLowerInvariant()] = $entry }',
' $changed = $false',
' foreach ($key in $desired.Keys) {',
' $want = $desired[$key]',
' $had = $before[$key]',
' if (-not $had -or [string]$had.level -ne $want.level) { Apply-Ace $user $sid $want.path $want.level; $changed = $true }',
' }',
' foreach ($key in $before.Keys) { if (-not $desired.Contains($key)) { Remove-Ace $sid ([string]$before[$key].path); $changed = $true } }',
' Save-Record $user @($desired.Values)',
' return $changed',
'}',
'# The guest must be refused the owner\'s sentinel: exit 0 means refused, exit 9 means it read the file.',
'function Probe([string]$user, [string]$password) {',
" $probe = Join-Path $ROOT 'scripts\\probe.ps1'",
" $probeLine = 'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"' + $probe + '\"'",
' $code = Run-As $user $password $probeLine 1',
' if ($code -eq 0) { return $true }',
' if ($code -eq 9) { return $false }',
' throw "the guest privacy probe did not run (result $code)"',
'}',
'function Run-As([string]$user, [string]$password, [string]$line, [int]$minutes) {',
' $scheduler = New-Object -ComObject Schedule.Service',
' $scheduler.Connect()',
' $arguments = [System.Security.SecurityElement]::Escape("/d /s /c `"$line`"")',
' $xml = @\'',
'<?xml version="1.0" encoding="UTF-16"?>',
'<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
' <Principals><Principal id="G"><LogonType>Password</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>',
' <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><ExecutionTimeLimit>PT__MINUTES__M</ExecutionTimeLimit></Settings>',
' <Actions Context="G"><Exec><Command>cmd.exe</Command><Arguments>__ARGS__</Arguments></Exec></Actions>',
'</Task>',
"'@",
' $xml = $xml.Replace("__ARGS__", $arguments).Replace("__MINUTES__", [string]$minutes)',
' $name = "Harness guest probe " + [guid]::NewGuid().ToString("N")',
' $task = $scheduler.GetFolder("\\").RegisterTask($name, $xml, 6, $user, $password, 1)',
' try { [void]$task.Run($null); $deadline = (Get-Date).AddMinutes($minutes); do { Start-Sleep -Milliseconds 300 } while (($task.State -in @(2, 4) -or $task.LastTaskResult -eq 0x41301) -and (Get-Date) -lt $deadline); return [int]$task.LastTaskResult }',
' finally { $scheduler.GetFolder("\\").DeleteTask($name, 0) }',
'}',
'# Task Scheduler gives a password logon only when the right is granted; New-LocalUser does not grant it.',
'function Set-BatchLogon([string]$sid, [bool]$grant) {',
' $inf = Join-Path $env:TEMP ("harness-guest-rights-" + [guid]::NewGuid().ToString("N") + ".inf")',
' & (Join-Path $env:SystemRoot "System32\\secedit.exe") /export /areas USER_RIGHTS /cfg $inf /quiet | Out-Null',
' if ($LASTEXITCODE -ne 0) { throw "could not read the batch logon right" }',
' try {',
' $line = @(Get-Content -LiteralPath $inf | Where-Object { $_ -like "SeBatchLogonRight*" })',
' $listed = if ($line.Count) { @(($line[0] -split "=", 2)[1].Split(",") | ForEach-Object { $_.Trim() } | Where-Object { $_ }) } else { @() }',
' $now = @(foreach ($e in $listed) { if ($e.StartsWith("*")) { $e } else { try { "*" + (New-Object Security.Principal.NTAccount($e)).Translate([Security.Principal.SecurityIdentifier]).Value } catch { $e } } })',
' $entry = "*$sid"',
' if ($grant -eq ($now -contains $entry)) { return }',
' $next = @($now | Where-Object { $_ -ne $entry })',
' if ($grant) { $next += $entry }',
' $text = @\'',
'[Unicode]',
'Unicode=yes',
'[Version]',
'signature="$CHICAGO$"',
'Revision=1',
'[Privilege Rights]',
'SeBatchLogonRight = __RIGHTS__',
"'@",
' $text = $text.Replace("__RIGHTS__", ($next -join ","))',
' Set-Content -LiteralPath $inf -Encoding Unicode -Value $text',
' & (Join-Path $env:SystemRoot "System32\\secedit.exe") /configure /db (Join-Path $env:TEMP "harness-guest-rights.sdb") /cfg $inf /areas USER_RIGHTS /quiet | Out-Null',
' if ($LASTEXITCODE -ne 0) { throw "could not change the batch logon right" }',
' } finally { Remove-Item -LiteralPath $inf -Force -ErrorAction SilentlyContinue }',
'}',
'# The guest\'s own terminal host: it runs as the guest, its discovery token and pipe are shared with the owner\'s',
'# SID only, and the owner starts/stops the task without elevation. No trigger: the owner\'s daemon starts it.',
'function Set-GuestHost([string]$user, [string]$pw, [string]$sid) {',
' if (-not (Test-Path -LiteralPath $PTY_BIN)) { throw "the terminal host is not staged; turn sharing on again" }',
' $hostHome = Join-Path $HOSTS $user',
' if (-not (Test-Path -LiteralPath $hostHome)) { [void][IO.Directory]::CreateDirectory($hostHome) }',
' & $ICACLS $hostHome /inheritance:r /grant:r ("*" + $sid + ":(OI)(CI)F") ("*" + $SYSTEM_SID + ":(OI)(CI)F") ("*" + $ADMINS + ":(OI)(CI)F") ("*" + $OWNER_SID + ":(OI)(CI)(RX)") /L /q | Out-Null',
' if ($LASTEXITCODE -ne 0) { throw "could not secure the guest host folder $hostHome" }',
' $wrapper = Join-Path $hostHome "host.cmd"',
// The tag keeps this account\'s host instance (and every pane route keyed by it) apart from the owner\'s, which
// runs the same binary: lib/../pty/src/instance.rs `INSTANCE_TAG_VAR`. `hg_<hex>` -> `gu<hex>`.
' $instanceTag = "gu" + $user.Substring(3)',
' $text = "@echo off`r`nset `"HARNESS_PTY_SHARE_SID=$OWNER_SID`"`r`nset `"HARNESS_PTY_INSTANCE_TAG=$instanceTag`"`r`nset `"PATH=$hostHome\\engines;%USERPROFILE%\\.local;$NODEBIN;%PATH%`"`r`n`"$PTY_BIN`" serve --home `"$hostHome`"`r`n"',
' [IO.File]::WriteAllText($wrapper, $text)',
' $line = "/d /s /c `"" + $wrapper + "`""',
' $arguments = [System.Security.SecurityElement]::Escape($line)',
' $xml = @\'',
'<?xml version="1.0" encoding="UTF-16"?>',
'<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
' <Principals><Principal id="Guest"><LogonType>Password</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>',
// A laptop on battery must keep the guest's host, and a start on battery must be allowed: the defaults stop it.
' <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><AllowStartOnDemand>true</AllowStartOnDemand><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><Enabled>true</Enabled><Hidden>true</Hidden><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><Priority>4</Priority></Settings>',
' <Actions Context="Guest"><Exec><Command>cmd.exe</Command><Arguments>__ARGS__</Arguments></Exec></Actions>',
'</Task>',
"'@",
' $xml = $xml.Replace("__ARGS__", $arguments)',
' $sddl = "D:(A;;FA;;;SY)(A;;FA;;;BA)(A;;FRFX;;;" + $OWNER_SID + ")"',
' $scheduler = New-Object -ComObject Schedule.Service',
' $scheduler.Connect()',
" $folderName = $HOST_TASK_PATH.Trim('\\')",
" try { $folder = $scheduler.GetFolder(\"\\$folderName\") } catch { $folder = $scheduler.GetFolder('\\').CreateFolder($folderName) }",
// A setup re-run registers a new wrapper with a new instance tag and PATH: an instance still running would keep the
// old one and never publish the tag the new daemon waits for, so it is stopped first (state 4 is Running).
' try { $running = $folder.GetTask($user); if ($running.State -eq 4) { $running.Stop() } } catch {}',
' [void]$folder.RegisterTask($user, $xml, 6, $user, $pw, 1, $sddl)',
'}',
'function Ensure([string]$email, [string]$id) {',
' if ($email -notmatch \'^[^\\s@]{1,64}@[^\\s@]{1,253}$\') { Refuse $id "the email is not a plain address" }',
' $user = Guest-Name $email.ToLowerInvariant()',
' $guestHome = Guest-Home $user',
' $workspace = Guest-Workspace $user',
' $account = Get-LocalUser -Name $user -ErrorAction SilentlyContinue',
' if ($account) {',
' $profiles = @(Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $account.SID.Value })',
' if ($profiles.Count -ne 1 -or $profiles[0].LocalPath -ne $guestHome) { Refuse $id "the account $user does not have the profile Windows must make" }',
' Answer $id $true $null $user $guestHome $workspace; return',
' }',
' $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"',
' $rng = [Security.Cryptography.RandomNumberGenerator]::Create()',
' try { $byte = New-Object byte[] 1; do { $chars = New-Object char[] 40; for ($i = 0; $i -lt 40;) { $rng.GetBytes($byte); if ($byte[0] -lt 248) { $chars[$i] = $alphabet[$byte[0] % 62]; $i++ } }; $pw = New-Object string (, $chars) } until ($pw -cmatch "[A-Z]" -and $pw -cmatch "[a-z]" -and $pw -match "[0-9]") } finally { $rng.Dispose() }',
' $sec = New-Object Security.SecureString; foreach ($c in $pw.ToCharArray()) { $sec.AppendChar($c) }; $sec.MakeReadOnly()',
' try { New-LocalUser -Name $user -FullName $user -Description "Harness guest (sharing)" -Password $sec -PasswordNeverExpires -AccountNeverExpires -UserMayNotChangePassword | Out-Null } catch { Refuse $id ("Windows would not make a local account: " + $_.Exception.Message) }',
' Add-LocalGroupMember -SID $USERS -Member $user',
' Add-LocalGroupMember -Group $GROUP -Member $user',
' $sid = Guest-Sid $user',
' $admin = @(Get-LocalGroupMember -SID $ADMINS | Where-Object { $_.SID.Value -eq $sid })',
' if ($admin.Count -ne 0) { Refuse $id "Windows put the guest in Administrators; sharing is off" }',
' New-Item -Path "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" -Force | Out-Null',
' New-ItemProperty -LiteralPath "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" -Name $user -Value 0 -PropertyType DWord -Force | Out-Null',
' Set-BatchLogon $sid $true',
// A folder left by an earlier account of the same name makes Windows suffix the new profile (`…DESKTOP-0TFH0OJ.001`),
// which is not the path a guest's harness may use. This account is new, so nothing in that folder is anyone's now;
// refusing is only right when it cannot be removed (another process holds it).
' if (Test-Path -LiteralPath $guestHome) {',
' try { Remove-Item -LiteralPath $guestHome -Recurse -Force -ErrorAction Stop } catch { Refuse $id ("Windows still holds an earlier guest\'s profile at " + $guestHome + "; restart this PC, then share with them again (" + $_.Exception.Message + ")") }',
' }',
' foreach ($stale in @(Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $sid -and $_.LocalPath -ne $guestHome })) {',
' try { Remove-CimInstance -InputObject $stale -ErrorAction Stop } catch { Refuse $id ("Windows still holds an earlier guest\'s profile for " + $user + "; restart this PC, then share with them again (" + $_.Exception.Message + ")") }',
' }',
' $code = Run-As $user $pw "exit 0" 5',
' if ($code -ne 0) { Refuse $id ("Windows did not sign the guest in to make its profile (result " + $code + ")") }',
' $profiles = @(Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $sid })',
' if ($profiles.Count -ne 1 -or $profiles[0].LocalPath -ne $guestHome) { Refuse $id "Windows did not make the guest profile at $guestHome" }',
' [void][IO.Directory]::CreateDirectory($workspace)',
' & $ICACLS $workspace /inheritance:r /grant:r ("*" + $sid + ":(OI)(CI)F") ("*" + $SYSTEM_SID + ":(OI)(CI)F") ("*" + $ADMINS + ":(OI)(CI)F") /L /q | Out-Null',
' if (-not (Probe $user $pw)) { Refuse $id "the guest can read the owner\'s privacy sentinel; sharing is off" }',
' Set-GuestHost $user $pw $sid',
' Answer $id $true $null $user $guestHome $workspace',
'}',
'function Remove-Guest([string]$user, [string]$id) {',
' if (-not (Guest-Exists $user)) { Refuse $id "the guest account $user is not here" }',
' $sid = Guest-Sid $user',
' foreach ($entry in @(Record-Of $user)) { try { Remove-Ace $sid ([string]$entry.path) } catch { } }',
' Remove-Item -LiteralPath (Join-Path $REC ($user + ".json")) -Force -ErrorAction SilentlyContinue',
// No per-process WMI: an owner-side loop over every process is what hung the PC during the spike. taskkill filters by
// the account name in the kernel and stops the whole tree.
' & (Join-Path $env:SystemRoot "System32\\schtasks.exe") /end /tn ($HOST_TASK_PATH + $user) 2>$null | Out-Null',
' & (Join-Path $env:SystemRoot "System32\\schtasks.exe") /delete /tn ($HOST_TASK_PATH + $user) /f 2>$null | Out-Null',
' Remove-Item -LiteralPath (Join-Path $HOSTS $user) -Recurse -Force -ErrorAction SilentlyContinue',
' & (Join-Path $env:SystemRoot "System32\\taskkill.exe") /FI ("USERNAME eq " + $user) /F /T 2>$null | Out-Null',
' Set-BatchLogon $sid $false',
' $profiles = @(Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $sid })',
' $pending = $null',
' if ($profiles.Count -eq 1) {',
' try { Remove-CimInstance -InputObject $profiles[0] -ErrorAction Stop } catch { $pending = "Windows keeps the guest profile until the next restart: " + $_.Exception.Message }',
' }',
// The account goes even when Windows holds its profile: no SID means no access, and the restart releases the files.
' try { Remove-LocalUser -Name $user -ErrorAction Stop } catch { Refuse $id ("Windows would not delete the guest account: " + $_.Exception.Message) }',
' try { Remove-LocalGroupMember -Group $GROUP -Member $user -ErrorAction SilentlyContinue } catch { }',
' Remove-ItemProperty -LiteralPath "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" -Name $user -ErrorAction SilentlyContinue',
' Remove-Item -LiteralPath (Join-Path $REC ($user + ".json")) -Force -ErrorAction SilentlyContinue',
' if ($pending) { Answer $id $true $pending $user (Guest-Home $user) (Guest-Workspace $user) } else { Answer $id $true $null $user (Guest-Home $user) (Guest-Workspace $user) }',
'}',
'',
'# Exactly one request. Two at once is a client bug, not something to guess between.',
'$files = @(Get-ChildItem -LiteralPath $REQ -Filter "*.json" -File)',
'if ($files.Count -eq 0) { exit 0 }',
'if ($files.Count -ne 1) { die "more than one guest setup request is waiting" 4 }',
'$request = Get-Content -LiteralPath $files[0].FullName -Raw | ConvertFrom-Json',
'$id = [string]$request.id',
'if ($id -notmatch \'^[0-9a-f]{32}$\') { Remove-Item -LiteralPath $files[0].FullName -Force; exit 4 }',
// The SYSTEM task is the privileged side: never trust the JSON shape. Mirror parseGuestSetupRequest.ts.
'$names = @($request.PSObject.Properties.Name | Sort-Object)',
'$op = [string]$request.op',
'$guest = \'^hg_[0-9a-f]{12}$\'',
'if ($op -eq "ensure") {',
' if (($names -join ",") -ne "email,id,op" -or [string]$request.email -notmatch \'^[^\\s@]{1,64}@[^\\s@]{1,253}$\') { Refuse $id "the ensure request is not valid" }',
'} elseif ($op -in @("remove", "unshare")) {',
' if (($names -join ",") -ne "id,op,user" -or [string]$request.user -notmatch $guest) { Refuse $id "the $op request is not valid" }',
'} elseif ($op -eq "share") {',
' if (($names -join ",") -ne "folders,id,op,user" -or [string]$request.user -notmatch $guest -or @($request.folders).Count -gt $MAX_FOLDERS) { Refuse $id "the share request is not valid" }',
'} else { Refuse $id "the request names no operation" }',
'try {',
' switch ([string]$request.op) {',
' "ensure" { Ensure ([string]$request.email).ToLowerInvariant().Trim() $id }',
' "remove" { Remove-Guest ([string]$request.user) $id }',
' "share" { $changed = Share ([string]$request.user) @($request.folders); Answer $id $true $null ([string]$request.user) (Guest-Home ([string]$request.user)) (Guest-Workspace ([string]$request.user)) }',
' "unshare" { $changed = Share ([string]$request.user) @(); Answer $id $true $null ([string]$request.user) (Guest-Home ([string]$request.user)) (Guest-Workspace ([string]$request.user)) }',
' default { Refuse $id "the request names no operation" }',
' }',
'} catch { Refuse $id $_.Exception.Message } finally { Remove-Item -LiteralPath $files[0].FullName -Force -ErrorAction SilentlyContinue }',
'exit 0',
'',
].join('\n')
}