# Brokkr 0.2.0 - the SourceLess node installer for Windows. # # GENERATED by scripts/brokkr.mjs, written and checked by scripts/pharos.mjs. Do not edit this # file; edit the generator. # # powershell -ExecutionPolicy Bypass -File brokkr.ps1 -Network dev # powershell -ExecutionPolicy Bypass -File brokkr.ps1 -Network dev -DryRun # powershell -ExecutionPolicy Bypass -File brokkr.ps1 -Network dev -Verify # # The one-liner equivalent of curl | sh on this platform is # irm https://.../brokkr.ps1 | iex # and it carries the same objection and the same answer as the POSIX script: read the file, # run -DryRun first, and note that nothing is downloaded without a checksum. See the header of # deploy/install/brokkr.sh for the argument in full; it is not repeated here because a security # argument that exists in two versions is a security argument that will drift. # # One difference from the POSIX script, said here rather than discovered: file permissions. # chmod is very nearly a no-op on Windows - Node maps it onto the read-only attribute and # nothing else, which src/node/keystore.ts says out loud - so the passphrase file is locked # down with an ACL instead, before the secret is in it: inheritance broken, one ACE for the # installing account's SID, read back. See New-PrivateFile. [CmdletBinding()] param( [string]$Network = '', [string]$Genesis = '', [string]$Prefix = '', [string]$Dir = '', [ValidateSet('auto','source','binary','docker')][string]$Channel = 'auto', [string]$SourceDir = '', [string]$Repo = '', [string]$Ref = '', [string]$BinaryUrl = '', [string]$Sha256 = '', [string]$Image = 'strblk:local', [int]$OpsPort = 0, [int]$RpcPort = 0, [int]$DashboardPort = 0, [int]$P2pPort = 0, [switch]$AutoPorts, [string]$Peers = '', [int]$BlockInterval = 0, # NOT a ValidateSet, deliberately. PowerShell enforces one at parameter BINDING, before a line # of this script runs, so an unknown class produced a binding error and exit 1 - while the # POSIX installer printed the class register and exited 2. Exit 2 is this project's code for # "you typed something wrong, the command never ran"; exit 1 is a refusal after running. The # check is below, against the register, and it prints the three classes and what each costs. [string]$Class = '', # The address peers should dial this node on. It was parsed nowhere on this platform until # 2026-09-17: the POSIX script has carried it since 2026-09-12, and without it a node bound to a # wildcard returns null from advertisedEndpoint, so no peer it talks to can pass its address on # and a Windows seed can only ever be reached by whoever already knew where it was. [string]$Advertise = '', [ValidateSet('file','prompt','env','none')][string]$Seal = 'file', # 'task' is the Windows service equivalent: a Scheduled Task whose action is the supervisor. # See the Service step for what that is and is not equivalent to. [ValidateSet('auto','task','none')][string]$Service = 'auto', # Print the STARW class table and exit. Answered before -Network is required, because "what # does a mini node cost" is asked before anybody has chosen a chain. [switch]$Classes, [switch]$NoStart, [switch]$Verify, [switch]$Json, [switch]$Strict, [switch]$DryRun, [switch]$Help ) $ErrorActionPreference = 'Stop' # --------------------------------------------------------------------------------------------- # Registry values. Generated; every one has a source in the tree. # --------------------------------------------------------------------------------------------- $BrokkrVersion = '0.2.0' $BinName = 'strblk.exe' $RepoUrl = 'https://github.com/alexccoin/strblkv1.git' $OpsPortDefault = 8081 # ASTROLABE_DEFAULT_PORT, src/ops/astrolabe.ts $DashPortDefault = 8082 # GUNGNIR_DEFAULT_PORT, src/gungnir/server.ts $RpcPortDefault = 8083 # IRIS_DEFAULT_PORT, src/network/iris.ts $Loopback = '127.0.0.1' $KeyEnv = 'SOURCELESS_KEY_PASSPHRASE' # class|minRamMib|minDiskMib|retentionBudgetBytes|maxPeers|retainedBlocks|produces|servesSync|keepsFullState|portOffset # From STARW_CLASSES in src/network/mnemosyne.ts, except the two resource figures: those are a # MEASURED idle resident set (scripts/brokkr.mjs MEASURED_IDLE) plus the class's retention budget # plus 64 MiB of headroom. The budget ALONE is not a machine requirement and is not used as one. $ClassRows = @( 'pulsar|192|64|716800|24|0|no|no|no|0', 'quasar|448|2048|268435456|128|4096|yes|yes|yes|10', 'supernova|4288|20480|4294967296|512|all|yes|yes|yes|20' ) # key|chainId|mode|launched|genesisSource|keyProvenance|genesisHash, from NETWORKS in snotra.ts $Realms = @( 'dev|31337|development|yes|built-in|published|8ee28b94b15c1db6cfb7e052d2ade53b5e1a8be5d8698e17a679f4b567a576ea', 'midgard|131313|production|yes|built-in|published|e88a8753925935b0c003961f7988fe3df6f466cf648584a7bf39c486c4772d37', 'asgard|1313|production|yes|operator|custody|1cf8655125cc1bbbc0ca06a491f53775499785c349b4d0f5748d5ea170e517bf' ) $script:Failures = 0 $script:Warnings = 0 function Say { param([string]$m) Write-Host $m } function Step { param([string]$m) Write-Host ''; Write-Host "== $m" } function Ok { param([string]$m) Write-Host " ok $m" } function Note { param([string]$m) Write-Host " . $m" } function Warn { param([string]$m) Write-Host " WARN $m"; $script:Warnings++ } function Bad { param([string]$m) Write-Host " FAIL $m"; $script:Failures++ } function Die { param([string]$m) Write-Host ''; Write-Host "brokkr: $m"; exit 2 } # Every mutation goes through this, so -DryRun is total rather than best-effort. function Invoke-Step { param([string]$Description, [scriptblock]$Action) if ($DryRun) { Write-Host " would $Description"; return $null } return & $Action } function Have { param([string]$n) return [bool](Get-Command $n -ErrorAction SilentlyContinue) } # The env file's value form, the same one the POSIX installer writes (ENV_QUOTE_SH in # scripts/brokkr.mjs): bare when every character is one neither systemd nor sh treats specially, # otherwise ONE double-quoted string with a backslash before each backslash, double quote, # backtick and dollar - the four escapes systemd honours inside double quotes, and sh too. So this # file and a Linux one are interchangeable in fact and not only in the comment that says so, and a # Windows path, which carries backslashes, reads back as itself on either side. Not single quotes # with an embedded quote written '\'': MEASURED, systemd 252 honours a quote only where a value # begins, so that form reaches it altered. The backtick is a [char] because this file is # generated from a JavaScript template, where a literal one would end the template. $EnvEscapable = '([\\"$' + [char]96 + '])' function ConvertTo-EnvValue { param([string]$v, [string]$Name = 'a value') # The KEY is named and the value never is: the value may be the console secret or a passphrase, # and this message is printed to a console and very often to a log. if ($v -match "[\r\n]") { Die "$Name carries a newline, which an env file cannot hold. Nothing was written." } if ($v -cmatch '^[A-Za-z0-9_./:,@%+=-]*$') { return $v } return ('"' + ($v -replace $EnvEscapable, '\$1') + '"') } function New-EnvLine { param([string]$Name, [string]$Value) return ($Name + '=' + (ConvertTo-EnvValue $Value $Name)) } function ConvertTo-CommandLine { param([string[]]$Argv) $parts = foreach ($arg in $Argv) { $v = [string]$arg if ($v.Length -gt 0 -and $v -notmatch '[\s"]') { $v; continue } $sb = New-Object System.Text.StringBuilder [void]$sb.Append('"') $slashes = 0 foreach ($ch in $v.ToCharArray()) { if ($ch -eq [char]92) { $slashes++; continue } if ($ch -eq [char]34) { [void]$sb.Append((New-Object string ([char]92, (2 * $slashes + 1)))) } elseif ($slashes -gt 0) { [void]$sb.Append((New-Object string ([char]92, $slashes))) } [void]$sb.Append($ch) $slashes = 0 } if ($slashes -gt 0) { [void]$sb.Append((New-Object string ([char]92, (2 * $slashes)))) } [void]$sb.Append('"') $sb.ToString() } return ($parts -join ' ') } function Invoke-Argv { param([string]$Exe, [string[]]$Argv, [switch]$Capture) $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $Exe $psi.Arguments = ConvertTo-CommandLine $Argv $psi.UseShellExecute = $false if ($Capture) { $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.StandardOutputEncoding = New-Object System.Text.UTF8Encoding($false) } $proc = [System.Diagnostics.Process]::Start($psi) if ($Capture) { $errText = $proc.StandardError.ReadToEndAsync() $outText = $proc.StandardOutput.ReadToEnd() $proc.WaitForExit() [void]$errText.Result $global:LASTEXITCODE = $proc.ExitCode return @($outText -split '\r?\n' | Where-Object { $_ -ne '' }) } $proc.WaitForExit() $global:LASTEXITCODE = $proc.ExitCode } function Write-EnvText { param([string]$Path, [string[]]$Lines) [System.IO.File]::WriteAllText($Path, (($Lines -join [string][char]10) + [char]10), (New-Object System.Text.UTF8Encoding($false))) } function Read-EnvText { param([string]$Path) # The comma keeps a one-line file an array: PowerShell unrolls a returned array of one into a string. return ,[System.IO.File]::ReadAllLines($Path, (New-Object System.Text.UTF8Encoding($false))) } $InstallerElevated = (New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) function Get-TrustedSids { $sids = @([System.Security.Principal.WindowsIdentity]::GetCurrent().User) if ($script:InstallerElevated) { $sids += New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18') $sids += New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544') } return ,$sids } function Test-TrustedSid { param($Sid, $Trusted) foreach ($t in $Trusted) { if ($t.Value -eq $Sid.Value) { return $true } } return $false } function New-PrivateFile { param([string]$Path, $Sids = $null) if ($null -eq $Sids) { $Sids = Get-TrustedSids } if (Test-Path -LiteralPath $Path) { Remove-Item -LiteralPath $Path -Force } $sec = New-Object System.Security.AccessControl.FileSecurity $sec.SetAccessRuleProtection($true, $false) foreach ($sid in $Sids) { $sec.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'Allow'))) } $mode = [System.IO.FileMode]::CreateNew $rights = [System.Security.AccessControl.FileSystemRights]::FullControl $share = [System.IO.FileShare]::None try { if ($PSVersionTable.PSEdition -eq 'Core') { $fs = [System.IO.FileSystemAclExtensions]::Create((New-Object System.IO.FileInfo($Path)), $mode, $rights, $share, 4096, [System.IO.FileOptions]::None, $sec) } else { $fs = New-Object System.IO.FileStream($Path, $mode, $rights, $share, 4096, [System.IO.FileOptions]::None, $sec) } $fs.Dispose() } catch { Die "$Path could not be created afresh with an owner-only ACL, so no secret was written to it." } $check = Get-Acl -LiteralPath $Path $rules = @($check.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) $foreign = @($rules | Where-Object { -not (Test-TrustedSid $_.IdentityReference $Sids) }) if (-not $check.AreAccessRulesProtected -or $rules.Count -lt 1 -or $foreign.Count -gt 0) { Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue Die "$Path could not be made readable by this account only, so no secret was written to it." } } # The first account outside $Trusted that may write $Path or what is created in it - an allowing # rule with any write, delete or ACL right, inherit-only ones included - or its owner when that is # outside $Trusted (an owner can always rewrite the ACL). Nothing when there is none. # CREATOR OWNER is not an account: it grants only whoever creates a child, which needs a right of # its own. GENERIC_ALL and GENERIC_WRITE are counted: an inherit-only rule is stored that way. function Get-ForeignWriter { param([string]$Path, $Trusted) $acl = Get-Acl -LiteralPath $Path $owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]) if (-not (Test-TrustedSid $owner $Trusted)) { return $owner.Value } $write = 0x500D0156 foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) { if ($rule.AccessControlType -ne 'Allow') { continue } if ($rule.IdentityReference.Value -eq 'S-1-3-0') { continue } if (Test-TrustedSid $rule.IdentityReference $Trusted) { continue } if (([int]$rule.FileSystemRights -band $write) -ne 0) { return $rule.IdentityReference.Value } } return $null } # The accounts an install directory is given, elevated or not: this account, SYSTEM and # Administrators - the three a user profile directory already grants. NOT only when elevated: a # non-elevated install with -Prefix C:\SourceLess inherited "Authenticated Users: Modify" too, and # any local account could rewrite the launcher the logon task runs as the installing user. function Get-DirSids { return ,@([System.Security.Principal.WindowsIdentity]::GetCurrent().User, (New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18')), (New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544'))) } # A path made absolute against PowerShell's location and with every '.' and '..' collapsed, so a # comparison between two paths compares where they are and not how they were typed: # 'C:\SourceLess\..\Users\Public\x' is not inside C:\SourceLess. function Resolve-FullPath { param([string]$Path) return [System.IO.Path]::GetFullPath($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)) } function Test-InsidePath { param([string]$Child, [string]$Parent) $c = (Resolve-FullPath $Child).TrimEnd('\') $p = (Resolve-FullPath $Parent).TrimEnd('\') return ($c.Equals($p, [System.StringComparison]::OrdinalIgnoreCase) -or $c.StartsWith($p + '\', [System.StringComparison]::OrdinalIgnoreCase)) } # Asked before anything is written: may this install take $Path? One that does not exist yet, one # no outside account can write, or an EMPTY one outside accounts could write but do not own. One # holding files another account could have put there is refused, and the refusal says how to take # it back: the files in it are code a scheduled task runs, so they are not adopted unread. function Assert-InstallDirUsable { param([string]$Path, [string]$Flag, $Trusted) if (-not (Test-Path -LiteralPath $Path)) { return } $full = Resolve-FullPath $Path $aside = (Split-Path -Leaf $full) + '.old' $me = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value $acl = Get-Acl -LiteralPath $Path $owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]) if (-not (Test-TrustedSid $owner $Trusted)) { Die ("$Flag $full belongs to $($owner.Value), which can rewrite its ACL whatever this installer sets, and a scheduled task runs code from it. To use this path, have an administrator move it aside - Rename-Item -LiteralPath '$full' '$aside' - and re-run: it is then created afresh, writable only by you, SYSTEM and Administrators.") } $writer = Get-ForeignWriter $Path $Trusted if ($writer -and @(Get-ChildItem -LiteralPath $Path -Force).Count -gt 0) { Die ("$Flag $full already holds files, and $writer can write there, so any of them may have been put there by another account - and a scheduled task runs code from it. To take it back, move it aside and re-run: Rename-Item -LiteralPath '$full' '$aside' - the install creates it afresh, protected; copy back only a data directory you have checked. Or, if you have checked every file in it yourself, take it over in place and re-run: icacls '$full' /inheritance:r /grant:r '*" + $me + ":(OI)(CI)F' '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' /T") } } # The node.exe an elevated install's SYSTEM task runs, found on PATH or in SOURCELESS_NODE_BIN. # If another account can write it or the directory it sits in, that account chooses what SYSTEM # runs at every boot. function Assert-NodeExeTrusted { param([string]$NodeExe, $Trusted) if ($NodeExe -eq '' -or -not (Test-Path -LiteralPath $NodeExe)) { return } foreach ($nodePath in @($NodeExe, (Split-Path -Parent $NodeExe))) { $nodeWriter = Get-ForeignWriter $nodePath $Trusted if ($nodeWriter) { Die "node.exe at $NodeExe would run as SYSTEM at every boot, and $nodeWriter can write $nodePath - so that account would choose what SYSTEM runs. Install Node.js where only administrators can write (its installer puts it under C:\Program Files\nodejs), or set SOURCELESS_NODE_BIN to such a node.exe, and re-run." } } } # Make $Path - creating it if needed - writable by $Trusted alone, inheritance off, every child # inheriting that. Read back. A directory this created is checked to be still empty afterwards. function Protect-InstallDir { param([string]$Path, $Trusted) $sec = New-Object System.Security.AccessControl.DirectorySecurity $sec.SetAccessRuleProtection($true, $false) foreach ($sid in $Trusted) { $sec.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow'))) } $created = -not (Test-Path -LiteralPath $Path) if ($created) { if ($PSVersionTable.PSEdition -eq 'Core') { [void][System.IO.FileSystemAclExtensions]::Create((New-Object System.IO.DirectoryInfo($Path)), $sec) } else { [void][System.IO.Directory]::CreateDirectory($Path, $sec) } } else { Set-Acl -LiteralPath $Path -AclObject $sec } $writer = Get-ForeignWriter $Path $Trusted if ($writer) { Die "$Path is still writable by $writer after its ACL was set. Nothing was written to it." } if ($created -and @(Get-ChildItem -LiteralPath $Path -Force).Count -gt 0) { Die "something was created in $Path before it could be protected. Nothing was written to it." } } # A string as a PowerShell single-quoted literal: every character PowerShell reads as a single # quote, the typographic ones included, doubled. function ConvertTo-PsLiteral { param([string]$v) return ("'" + ($v -replace "['\u2018\u2019\u201A\u201B]", '$0$0') + "'") } function ConvertFrom-EnvValue { param([string]$v) if ($v.Length -ge 2 -and $v.StartsWith('"') -and $v.EndsWith('"')) { return ($v.Substring(1, $v.Length - 2) -replace ('\\' + $EnvEscapable), '$1') } if ($v.Length -ge 2 -and $v.StartsWith("'") -and $v.EndsWith("'")) { return $v.Substring(1, $v.Length - 2) } return $v } # Runs a native command and returns its stdout lines, with a non-zero exit and anything on stderr # treated as data rather than as a fault. # # $ErrorActionPreference = 'Stop' is right for cmdlets and wrong for processes: PowerShell turns # ANY line a native command writes to stderr into a terminating error under it. MEASURED three # times on the docker channel of this script - "No such container" from docker rm on a first # install, and "can't connect to remote host" from wget probing an endpoint that was not up yet. # Both are answers to the question being asked, not failures of the asking. The exit code is # what callers read; ErrorRecords are dropped so a merged stderr line cannot end up inside a # response body being parsed. function Invoke-Native { param([scriptblock]$Block) $prev = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { $out = & $Block 2>&1 return @($out | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) } finally { $ErrorActionPreference = $prev } } function Show-Usage { Say 'brokkr - install and verify a SourceLess node' Say '' Say ' brokkr.ps1 -Network [options]' Say ' brokkr.ps1 -Network -Verify' Say ' brokkr.ps1 -Network -DryRun' Say '' Say 'Realm' Say ' -Network KEY REQUIRED. There is no default: a node refuses to start without one' Say ' of --network, --genesis or --dev, because the old default silently' Say ' started the development chain, where any producer is accepted.' Say ' -Genesis FILE A genesis file, checked against -Network when both are given.' Say '' Say 'Where -Prefix, -Dir' Say 'How obtained -Channel source|binary|docker|auto, -SourceDir, -Repo, -Ref,' Say ' -BinaryUrl, -Sha256 (the binary channel REFUSES without it), -Image' Say 'Sockets -OpsPort, -RpcPort, -DashboardPort, -P2pPort, -AutoPorts' Say 'Chain -Peers, -BlockInterval, -Advertise' Say 'Keys -Seal file|prompt|env|none' Say '' Say 'Class' Say ' -Class C pulsar | quasar | supernova. Selects an INSTANCE: its own data' Say ' directory, env file, runner, port block and service, so one of every' Say ' class can stand on one machine. Without it the paths are what they' Say ' have always been.' Say ' -Classes Print what each class keeps and what each one costs, and exit.' Say '' Say 'Service' Say ' -Service task A Scheduled Task whose action is the SUPERVISOR (default). Elevated:' Say ' at STARTUP as SYSTEM, which is the systemd guarantee. Unelevated: at' Say ' logon as you, which is not. The supervisor restarts the node on every' Say ' exit, code 0 included, with a burst limit - which a task alone does' Say ' not do, because a node that exits 0 has not FAILED by its definition.' Say ' -Service none Print the command and let you run it. That is a foreground process' Say ' and not a service: nothing restarts it and nothing says why it died.' Say '' Say 'Other -NoStart, -Verify, -Json, -Strict, -DryRun, -Help' Say '' Say 'One of every class on this machine, which is three installs and three services:' Say '' Say ' brokkr.ps1 -Network dev -Class supernova -BlockInterval 3000 -P2pPort 43321' Say ' brokkr.ps1 -Network dev -Class quasar -Peers 127.0.0.1:43321 -P2pPort 43311' Say ' brokkr.ps1 -Network dev -Class pulsar -Peers 127.0.0.1:43321 -P2pPort 43301' Say '' Say 'Each takes its own port block from the register, so the three do not collide. The' Say 'repository has a script that does exactly this and then reports on it:' Say ' node deploy/local/orion.mjs up' } if ($Help) { Show-Usage; exit 0 } if ($Repo -eq '') { $Repo = $RepoUrl } # --------------------------------------------------------------------------------------------- # The register # --------------------------------------------------------------------------------------------- # The key is compared ORDINALLY and whole. String.StartsWith with no comparison is culture-aware, # and a culture-aware comparison ignores characters such as the soft hyphen: 'de'+U+00AD+'v' # matched dev (MEASURED by review) and went on into paths, unit names and container names. function Get-RealmRow { param([string]$key) if ($key -match '[|]') { return $null } foreach ($row in $Realms) { if ([string]::Equals($row.Split('|')[0], $key, [System.StringComparison]::Ordinal)) { return $row } } return $null } function Show-RealmTable { foreach ($row in $Realms) { $f = $row.Split('|') $state = if ($f[3] -eq 'yes') { 'launched' } else { 'NOT LAUNCHED - a node refuses to start on it' } Say (" {0,-9} chain id {1,-8} {2,-12} {3}" -f $f[0], $f[1], $f[2], $state) } } # --------------------------------------------------------------------------------------------- # The STARW class register, read the way the realm register is read # --------------------------------------------------------------------------------------------- function Get-ClassRow { param([string]$c) if ($c -match '[|]') { return $null } foreach ($row in $ClassRows) { if ([string]::Equals($row.Split('|')[0], $c, [System.StringComparison]::Ordinal)) { return $row } } return $null } function Show-ClassTable { foreach ($row in $ClassRows) { $f = $row.Split('|') Say (" {0,-10} {1,5} MiB RAM {2,6} MiB disk peers {3,-4} blocks {4,-5} produces {5,-4} serves-sync {6,-4} full-state {7,-4} ports +{8}" -f $f[0], $f[1], $f[2], $f[4], $f[5], $f[6], $f[7], $f[8], $f[9]) } } # Answered before -Network is required, because "what does a mini node cost" is a question # somebody asks BEFORE they have decided which chain to join. if ($Classes) { Say 'STARW node classes, from STARW_CLASSES in src/network/mnemosyne.ts' Say '' Show-ClassTable Say '' Say " RAM is a MEASURED idle resident set plus the class's retention budget plus 64 MiB of" Say ' headroom. The measurement was taken on THIS platform: a node of each class started from' Say ' the shipped entry point, alone on the host, no peers, empty queue, WorkingSetSize read' Say ' from Win32_Process 15 s later.' Say '' Say ' The retention budget is NOT the machine requirement and is not used as one. A pulsar' Say ' reported 0 accounted retained bytes against a 716,800-byte budget while its process' Say ' held 76,103,680 - two true numbers about different quantities. mnemosyne.ts says so.' Say '' Say ' Disk for a pulsar is MEASURED and constant: it retains no blocks, so its directory is' Say ' key material and a lock file and does not grow with height. For the other two the' Say ' figure is a REASONED floor: they retain blocks, and no bound has been measured at' Say ' production block sizes.' Say '' Say ' Bandwidth is UNMEASURED. Nothing in this repository has metered a node socket.' Say '' Say ' A pulsar also serves no JSON-RPC, whatever -RpcPort says: Iris needs full state and a' Say ' pulsar keeps none. The node prints that at start and it is not a fault.' exit 0 } if ($Class -ne '') { $classRow = Get-ClassRow $Class if ($null -eq $classRow) { Say "brokkr: '$Class' is not a STARW class this build knows." Show-ClassTable exit 2 } $cf = $classRow.Split('|') $ClassMinRam = [int]$cf[1] $ClassMinDisk = [int]$cf[2] $ClassBudget = $cf[3] $ClassMaxPeers = $cf[4] $ClassBlocks = $cf[5] $ClassProduces = $cf[6] $ClassServesSync = $cf[7] $ClassFullState = $cf[8] $ClassPortOffset = [int]$cf[9] } else { $ClassMinRam = 0; $ClassMinDisk = 0; $ClassBudget = ''; $ClassMaxPeers = '' $ClassBlocks = ''; $ClassProduces = ''; $ClassServesSync = ''; $ClassFullState = '' $ClassPortOffset = 0 } # A class that cannot seal, told to seal. The chain already decides this - planNode clamps the # interval to 0 for a class whose policy says producesBlocks: false - so this is the same rule # said at the point of typing rather than discovered as a timer that never fires. if ($Class -ne '' -and $ClassProduces -eq 'no' -and $BlockInterval -ne 0) { Say "brokkr: -BlockInterval $BlockInterval with -Class $Class has no effect." Say '' Say " A $Class has producesBlocks: false in src/network/mnemosyne.ts. planNode clamps the" Say ' interval to 0 before the node is built, so the timer would never have anything to seal' Say ' from. Installing with 0 instead, which is what the node would have run anyway.' $BlockInterval = 0 } if ($Network -eq '' -and $Genesis -eq '') { Say 'brokkr: -Network is required, and there is no default.' Say '' Say ' The node itself refuses to start without one of --network, --genesis or --dev, and' Say ' this installer refuses for the same reason. Omitting the flag used to start the' Say ' DEVELOPMENT chain in development mode, where a block from any well-signed producer is' Say ' accepted. An installer that supplied a default would put that silent open door back,' Say ' one layer above where the node can see it.' Say '' Say ' Realms this build knows (src/core/snotra.ts):' Show-RealmTable Say '' Say ' brokkr.ps1 -Network dev -DryRun' exit 2 } if ($Network -ne '') { $row = Get-RealmRow $Network if ($null -eq $row) { Say "brokkr: '$Network' is not a realm this build knows."; Show-RealmTable; exit 2 } $f = $row.Split('|') $RealmChainId = $f[1] $RealmMode = $f[2] $RealmLaunched = $f[3] $RealmGenSrc = $f[4] $RealmKeys = $f[5] } else { $Network = 'custom'; $RealmChainId = '-'; $RealmMode = 'production' $RealmLaunched = 'yes'; $RealmGenSrc = 'operator'; $RealmKeys = 'custody' } # --------------------------------------------------------------------------------------------- # Values that are written into the runner's command line, checked for what they are. # # The runner is a .cmd file with the node's arguments written into it as text, so a -Peers value # of '127.0.0.1:7801&calc' would be cmd.exe running calc at every start of the task - the POSIX # installer's sh runner had the same hole through its own --peers. A peer list is host:port pairs # (an IPv6 literal in brackets, or a str:// address) and a host is a name or an address; anything # else is refused before a file is written. No percent sign on this platform: in a .cmd file it # is cmd's own expansion syntax. The ports are [int] parameters and cannot carry text at all. # --------------------------------------------------------------------------------------------- # A value handed to git, docker, the download or the node as a positional argument is read as an # OPTION when it starts with '-' ('-Repo --upload-pack=CMD' is git running CMD), and a newline in # a path, URL or name is a second line in every file it is written to. Refused here, before # anything runs. The value is not printed: a URL can carry a token. foreach ($valueArg in @(@('-Repo', $Repo), @('-Ref', $Ref), @('-BinaryUrl', $BinaryUrl), @('-Image', $Image), @('-Prefix', $Prefix), @('-Dir', $Dir), @('-SourceDir', $SourceDir), @('-Genesis', $Genesis))) { if ([string]$valueArg[1] -like '-*') { Die ($valueArg[0] + " cannot start with '-': git, docker and the node would read it as an option, not as a value. A relative path that starts with a dash can be written .\-name.") } if ([string]$valueArg[1] -match "[\r\n]") { Die ($valueArg[0] + ' carries a newline, which no path, URL or name this installer writes can hold. Nothing was written.') } } # The console secret, when it is supplied, is checked HERE and not where it is used, which is after # the directories and the passphrase file exist. Refused by NAME; the value is never printed. $suppliedDashSecret = [Environment]::GetEnvironmentVariable('SOURCELESS_DASHBOARD_SECRET') if (-not [string]::IsNullOrEmpty($suppliedDashSecret) -and $suppliedDashSecret -match "[\r\n]") { Die 'SOURCELESS_DASHBOARD_SECRET carries a newline, which an env file cannot hold. Set it without one. Nothing was written.' } # Any other control character, or half of a surrogate pair (text that is not valid Unicode, so not # valid UTF-8 once written): an env file and an HTTP header do not carry either intact. if (-not [string]::IsNullOrEmpty($suppliedDashSecret) -and $suppliedDashSecret -match '\p{Cc}|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?@tcp/: - it APPENDS the port it is # bound to, because that is the only port it can honestly name. Given 92.205.25.236:47002 the # endpoint becomes tcp/92.205.25.236:47002:47002, which parseStrAddress refuses, so every peer that # receives the record discards it and no third node can ever be told this one exists. Nothing logs # anything: the node that writes the bad address never parses it. # # Refused rather than normalised. Stripping the port would be a guess about which of the two numbers # was meant, on the one flag that decides how the world reaches this node. if ($Advertise -ne '') { if ($Advertise -match '://') { $bare = ($Advertise -replace '^.*://', '') -replace '[:/].*$', '' Die "-Advertise takes a bare HOST, not a URL. Drop the scheme: -Advertise $bare" } # A bracketed or bare IPv6 literal is several colons and is fine: the node appends the port after # it exactly as it does for a name. Only a single colon is the host:port mistake. $isV6 = ($Advertise.StartsWith('[')) -or (([regex]::Matches($Advertise, ':')).Count -gt 1) if (-not $isV6 -and $Advertise.Contains(':')) { $hostPart = $Advertise.Split(':')[0] $portPart = $Advertise.Split(':')[1] Say 'brokkr: -Advertise takes a HOST, and you gave host:port.' Say '' Say " You passed $Advertise" Say " It must be $hostPart" Say '' Say ' The node appends the port it is actually listening on, because that is the only port it' Say ' can honestly name. With a port here the advertised address becomes' # Built by concatenation and not by interpolation: this file is generated from a JavaScript # template, where a dollar followed by a brace is the template's own syntax and never reaches # the output. The generator refuses one, which is why this reads the long way round. Say (' tcp/' + $hostPart + ':' + $portPart + ':') Say ' which parseStrAddress refuses, so every peer that receives this node record discards it' Say ' and no third node can ever be told this node exists. It happened on mainnet and went' Say ' unnoticed for two weeks.' Say '' Say ' If you meant to change the port the node LISTENS on, that is -P2pPort.' exit 2 } } # --------------------------------------------------------------------------------------------- # Paths # --------------------------------------------------------------------------------------------- if ($Prefix -eq '') { $Prefix = Join-Path $env:LOCALAPPDATA 'SourceLess' } # One INSTANCE per class. Without -Class every path is what it always was, so an existing install # keeps every name it had; with it, each name carries the class, because "one of every class on # this machine" is the requirement "three data directories, three env files, three runners and # three services" - and Cerberus refuses a second process on one directory, so sharing is not an # option that merely performs badly. $Instance = if ($Class -ne '') { "$Network-$Class" } else { $Network } if ($Dir -eq '') { $Dir = Join-Path (Join-Path $Prefix 'data') $Instance } $EtcDir = Join-Path $Prefix 'etc' $BinDir = Join-Path $Prefix 'bin' $SrcDir = if ($SourceDir -ne '') { $SourceDir } else { Join-Path $Prefix 'src' } $EnvFile = Join-Path $EtcDir "strblk-$Instance.env" $PassFile = Join-Path $EtcDir "strblk-$Instance.pass" # The console's shared secret. Beside the passphrase because it is the same kind of thing and # gets the same ACL, and separate from it because they protect different attacks: the passphrase # is theft of the keystore at rest, this one is an anonymous request reaching the console port. $DashSecretFile = Join-Path $EtcDir "strblk-$Instance.dashboard-secret" $IdentFile = Join-Path $EtcDir "strblk-$Instance.identity" $Runner = Join-Path $BinDir "strblk-node-$Instance.cmd" # The launcher the .cmd shim starts: same directory, same name, .ps1 - the shim finds it as %~dpn0.ps1. $Launcher = Join-Path $BinDir "strblk-node-$Instance.ps1" $DockerEnvFile = Join-Path $EtcDir "strblk-$Instance.docker.env" # The launcher's body and the .cmd shim, from windowsLauncherPs1 and WINDOWS_RUNNER_CMD in # scripts/brokkr.mjs. Literal text: no install value is in either. $LauncherBody = @' # Read as data: SOURCELESS_ names only, values in the env-file grammar ENV_QUOTE_SH writes. function ConvertTo-CommandLine { param([string[]]$Argv) $parts = foreach ($arg in $Argv) { $v = [string]$arg if ($v.Length -gt 0 -and $v -notmatch '[\s"]') { $v; continue } $sb = New-Object System.Text.StringBuilder [void]$sb.Append('"') $slashes = 0 foreach ($ch in $v.ToCharArray()) { if ($ch -eq [char]92) { $slashes++; continue } if ($ch -eq [char]34) { [void]$sb.Append((New-Object string ([char]92, (2 * $slashes + 1)))) } elseif ($slashes -gt 0) { [void]$sb.Append((New-Object string ([char]92, $slashes))) } [void]$sb.Append($ch) $slashes = 0 } if ($slashes -gt 0) { [void]$sb.Append((New-Object string ([char]92, (2 * $slashes)))) } [void]$sb.Append('"') $sb.ToString() } return ($parts -join ' ') } function Invoke-Argv { param([string]$Exe, [string[]]$Argv, [switch]$Capture) $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $Exe $psi.Arguments = ConvertTo-CommandLine $Argv $psi.UseShellExecute = $false if ($Capture) { $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.StandardOutputEncoding = New-Object System.Text.UTF8Encoding($false) } $proc = [System.Diagnostics.Process]::Start($psi) if ($Capture) { $errText = $proc.StandardError.ReadToEndAsync() $outText = $proc.StandardOutput.ReadToEnd() $proc.WaitForExit() [void]$errText.Result $global:LASTEXITCODE = $proc.ExitCode return @($outText -split '\r?\n' | Where-Object { $_ -ne '' }) } $proc.WaitForExit() $global:LASTEXITCODE = $proc.ExitCode } function Write-EnvText { param([string]$Path, [string[]]$Lines) [System.IO.File]::WriteAllText($Path, (($Lines -join [string][char]10) + [char]10), (New-Object System.Text.UTF8Encoding($false))) } function Read-EnvText { param([string]$Path) # The comma keeps a one-line file an array: PowerShell unrolls a returned array of one into a string. return ,[System.IO.File]::ReadAllLines($Path, (New-Object System.Text.UTF8Encoding($false))) } $EnvEscapable = '([\\"$' + [char]96 + '])' function ConvertFrom-EnvValue { param([string]$v) if ($v.Length -ge 2 -and $v.StartsWith('"') -and $v.EndsWith('"')) { return ($v.Substring(1, $v.Length - 2) -replace ('\\' + $EnvEscapable), '$1') } if ($v.Length -ge 2 -and $v.StartsWith("'") -and $v.EndsWith("'")) { return $v.Substring(1, $v.Length - 2) } return $v } $e = @{} foreach ($line in (Read-EnvText $EnvFile)) { if ($line -cmatch '^(SOURCELESS_[A-Za-z0-9_]+)=(.*)$') { $e[$Matches[1]] = ConvertFrom-EnvValue $Matches[2] } } function V { param([string]$k) if ($e.ContainsKey($k)) { return [string]$e[$k] } return '' } # The secrets reach the node through ITS environment, set here in-process. Never an argument. if ((V 'SOURCELESS_DASHBOARD_SECRET') -ne '') { $env:SOURCELESS_DASHBOARD_SECRET = (V 'SOURCELESS_DASHBOARD_SECRET') } if ((V 'SOURCELESS_PASS_FILE') -ne '') { $env:SOURCELESS_KEY_PASSPHRASE = [string]((Read-EnvText (V 'SOURCELESS_PASS_FILE')) | Select-Object -First 1) } $channel = V 'SOURCELESS_CHANNEL' $a = @('node') if ($channel -eq 'docker') { $a += @('--dir', '/data') } else { $a += @('--dir', (V 'SOURCELESS_DATA_DIR')) } $genesis = V 'SOURCELESS_GENESIS' $network = V 'SOURCELESS_NETWORK' if ($genesis -ne '' -and $network -ne 'custom') { $a += @('--network', $network, '--genesis', $genesis) } elseif ($genesis -ne '') { $a += @('--genesis', $genesis) } else { $a += @('--network', $network) } if ($channel -ne 'docker') { $a += @('--ops-port', (V 'SOURCELESS_OPS_PORT'), '--rpc-port', (V 'SOURCELESS_RPC_PORT'), '--dashboard-port', (V 'SOURCELESS_DASHBOARD_PORT')) } $a += @('--block-interval', (V 'SOURCELESS_BLOCK_INTERVAL_MS')) if ((V 'SOURCELESS_PEERS') -ne '') { $a += @('--peers', (V 'SOURCELESS_PEERS')) } if ((V 'SOURCELESS_CLASS') -ne '') { $a += @('--class', (V 'SOURCELESS_CLASS')) } $p2p = V 'SOURCELESS_P2P_PORT' if ($p2p -ne '' -and $p2p -ne '0') { $a += @('--port', $p2p) } if ((V 'SOURCELESS_ADVERTISE') -ne '') { $a += @('--advertise', (V 'SOURCELESS_ADVERTISE')) } switch ($channel) { 'source' { Invoke-Argv (V 'SOURCELESS_NODE_BIN') (@((V 'SOURCELESS_ENTRY')) + $a); exit $LASTEXITCODE } 'binary' { Invoke-Argv (V 'SOURCELESS_BIN') $a; exit $LASTEXITCODE } 'docker' { # The docker env-file was written at install, ACL'd to the installing account like the # passphrase file. A passphrase held only in this environment (-Seal env or prompt) is passed # by NAME, which docker resolves from this process's environment: no value on a command line. $container = V 'SOURCELESS_CONTAINER' & docker rm -f $container 2>$null | Out-Null $run = @('run', '-d', '--name', $container, '-v', ((V 'SOURCELESS_DATA_DIR') + ':/data'), '--env-file', (V 'SOURCELESS_DOCKER_ENV_FILE')) if ((V 'SOURCELESS_PASS_FILE') -eq '' -and $null -ne [Environment]::GetEnvironmentVariable('SOURCELESS_KEY_PASSPHRASE')) { $run += @('-e', 'SOURCELESS_KEY_PASSPHRASE') } Invoke-Argv 'docker' ($run + @((V 'SOURCELESS_IMAGE')) + $a) exit $LASTEXITCODE } default { Write-Host "strblk launcher: the env file $EnvFile names no channel this launcher knows"; exit 2 } } '@ $RunnerCmd = @('@echo off', 'setlocal DisableDelayedExpansion', 'rem Written by brokkr. A fixed shim: it starts the launcher beside it, which reads the env file.', 'rem No install value is written into this file, so cmd never parses one.', 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dpn0.ps1"', 'exit /b %ERRORLEVEL%') # Paths cmd still sees: the supervisor starts the .cmd shim through cmd /c with its path and the # log's on the line, and cmd expands %NAME% there before it parses. A space, an & or a ( is fine # inside the quotes it gets; a % or a double quote is not, so they are refused here, by name. foreach ($pathArg in @(@('-Prefix', $Prefix), @('-Dir', $Dir), @('-SourceDir', $SrcDir), @('-Genesis', $Genesis))) { if ($pathArg[1] -match '[%"\r\n]') { Die ($pathArg[0] + ' carries a %, a double quote or a newline, which the cmd line that starts the node cannot hold. Choose a path without them.') } } # Every install registers a task that runs code from these directories - as SYSTEM when elevated, # as the installing account when not - so it asks now, before anything is written, whether another # account could already have put code in them. See PS_PRIVATE_FILES in scripts/brokkr.mjs. # Inside-or-not is decided on full paths: '-Dir C:\SourceLess\..\Users\Public\x' is NOT inside. # A -SourceDir is code SYSTEM runs in place, so when elevated any outside writer is refused there. $DataDirInsidePrefix = Test-InsidePath $Dir $Prefix $trustedSids = Get-DirSids Assert-InstallDirUsable $Prefix '-Prefix' $trustedSids if (-not $DataDirInsidePrefix) { Assert-InstallDirUsable $Dir '-Dir' $trustedSids } if ($InstallerElevated) { if ($SourceDir -ne '' -and (Test-Path -LiteralPath $SourceDir)) { $sourceWriter = Get-ForeignWriter $SourceDir $trustedSids if ($sourceWriter) { Die "-SourceDir $SourceDir can be written by $sourceWriter, and an elevated install runs the code in it as SYSTEM. Build from a directory only administrators can write." } } } $Container = "strblk-$Instance" # The task name is per CLASS and not per instance, so that deploy/windows/strblk-service.ps1 - # which knows the class and not the realm - names the same task this installer registered. One # class, one service, one data directory. $TaskName = if ($Class -ne '') { "SourceLess strblk node ($Class)" } else { "SourceLess strblk node ($Network)" } $Supervisor = Join-Path $BinDir 'strblk-supervise.ps1' $ServiceTool = Join-Path $BinDir 'strblk-service.ps1' $NodeLog = Join-Path $Prefix "strblk-$Instance.log" # --------------------------------------------------------------------------------------------- # Ports. See the long note in brokkr.sh: an endpoint that cannot bind does not stop the node. # MEASURED on the machine this was generated on - a Windows 11 host - where an orphaned node # from an earlier run held two of the three default ports, and a fresh node started anyway with # both of those endpoints absent. # --------------------------------------------------------------------------------------------- function Test-PortFree { param([int]$Port) try { $l = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Parse($Loopback), $Port) $l.Start(); $l.Stop(); return $true } catch { return $false } } function Test-BlockFree { param([int]$Offset) return (Test-PortFree ($OpsPortDefault + $Offset)) -and (Test-PortFree ($DashPortDefault + $Offset)) -and (Test-PortFree ($RpcPortDefault + $Offset)) } # --------------------------------------------------------------------------------------------- # HTTP # --------------------------------------------------------------------------------------------- function Get-HttpStatus { param([string]$Url) if ($Channel -eq 'docker') { Invoke-Native { docker exec $Container wget -q -O /dev/null $Url } | Out-Null if ($LASTEXITCODE -eq 0) { return 200 } else { return 0 } } # The status of a refusal is an answer too: Invoke-WebRequest throws on 401, and the response it # throws with carries the code. 0 only when nothing answered at all. try { return (Invoke-WebRequest -Uri $Url -UseBasicParsing -TimeoutSec 10).StatusCode } catch { if ($null -ne $_.Exception.Response) { return [int]$_.Exception.Response.StatusCode } return 0 } } # The same probe carrying the console secret, as a header built in this process. In a container it # is node running CONSOLE_PROBE_JS from STDIN, taking the secret from the container's own # environment: the secret is on no command line - not docker's here, and not a probe program's # inside the container, whose processes the host's process list shows to every account. It was # wget with the header on its argv. See the POSIX script. $ConsoleProbe = 'fetch(process.argv[2],{headers:{authorization:"Bearer "+(process.env.SOURCELESS_DASHBOARD_SECRET||"")},signal:AbortSignal.timeout(10000)}).then((r)=>process.stdout.write(String(r.status)),()=>process.stdout.write("000"))' function Get-HttpStatusAuth { param([string]$Url) if ($Channel -eq 'docker') { $answer = ((Invoke-Native { $ConsoleProbe | docker exec -i $Container node - $Url }) -join '').Trim() if ($answer -match '^[0-9]{3}$') { return [int]$answer } else { return 0 } } $headers = @{ Authorization = ('Bearer ' + $script:DashSecret) } try { return (Invoke-WebRequest -Uri $Url -Headers $headers -UseBasicParsing -TimeoutSec 10).StatusCode } catch { if ($null -ne $_.Exception.Response) { return [int]$_.Exception.Response.StatusCode } return 0 } } function Get-HttpBody { param([string]$Url) if ($Channel -eq 'docker') { return (Invoke-Native { docker exec $Container wget -q -O - $Url }) -join '' } try { return (Invoke-WebRequest -Uri $Url -UseBasicParsing -TimeoutSec 10).Content } catch { return '' } } function Invoke-JsonRpc { param([string]$Url, [string]$Body) if ($Channel -eq 'docker') { # Every double quote escaped before it reaches docker.exe. Windows PowerShell 5.1 hands # native commands one flat command line and STRIPS the quotes inside an argument on the way, # so a JSON body arrives as {jsonrpc:2.0,...} - MEASURED: the endpoint answered 400 Bad # Request, and this script reported "the rpc endpoint answered but published no genesis # hash", which is a true statement about a request that was never valid. CommandLineToArgvW, # which docker.exe parses with, turns \" back into a quote. $escaped = $Body -replace '"', '\"' return (Invoke-Native { docker exec $Container wget -q -O - --header 'Content-Type: application/json' --post-data $escaped $Url }) -join '' } try { return (Invoke-WebRequest -Uri $Url -UseBasicParsing -TimeoutSec 10 -Method Post -ContentType 'application/json' -Body $Body).Content } catch { return '' } } # --------------------------------------------------------------------------------------------- # strblk for this install # --------------------------------------------------------------------------------------------- # The ABSOLUTE path to node.exe, resolved once and cached. # # A bare 'node' is right in the shell that runs this installer and not necessarily in the one the # service runs in. A Scheduled Task started as SYSTEM reads the MACHINE PATH from the registry, and # nvm-windows, a portable zip and a per-user MSI all put node on the USER path only - so the task # is created, reported installed, and fails at every start with a message no operator sees, because # Task Scheduler records a result code and not stderr. This is the Windows shape of the defect that # cost 371 macOS installs; it is resolved here for the same reason and in the same place. $script:NodeBinResolved = '' function Resolve-NodeBin { if ($script:NodeBinResolved -ne '') { return $script:NodeBinResolved } if ($env:SOURCELESS_NODE_BIN -and $env:SOURCELESS_NODE_BIN -ne '') { $script:NodeBinResolved = $env:SOURCELESS_NODE_BIN return $script:NodeBinResolved } # .Source is the resolved path on disk; .Name is the word 'node.exe', which is what a task would # have to look up again at start time - the thing being removed. $cmd = Get-Command node -ErrorAction SilentlyContinue if ($cmd -and $cmd.Source) { $script:NodeBinResolved = $cmd.Source return $script:NodeBinResolved } foreach ($candidate in @( (Join-Path $env:ProgramFiles 'nodejs\node.exe'), (Join-Path $env:LOCALAPPDATA 'Programs\nodejs\node.exe') )) { if ($candidate -and (Test-Path $candidate)) { $script:NodeBinResolved = $candidate; return $candidate } } return '' } function Get-StrblkParts { switch ($Channel) { 'source' { $exe = Resolve-NodeBin if ($exe -eq '') { Die 'the source channel needs node on PATH, or SOURCELESS_NODE_BIN set to the full path of node.exe. A bare node in a Scheduled Task is what produces a service that installs cleanly and never runs.' } return @{ Exe = $exe; Pre = @((Join-Path $SrcDir 'dist\src\cli\strblk.js')) } } 'binary' { return @{ Exe = (Join-Path $BinDir $BinName); Pre = @() } } 'docker' { return @{ Exe = 'docker'; Pre = @('run','--rm',$Image) } } } return @{ Exe = (Resolve-NodeBin); Pre = @() } } function Get-NetworkFlags { if ($Genesis -ne '' -and $Network -ne 'custom') { return @('--network', $Network, '--genesis', $Genesis) } if ($Genesis -ne '') { return @('--genesis', $Genesis) } return @('--network', $Network) } # NOT named $Args. $args is a PowerShell automatic variable holding a function's unbound # arguments, so a parameter of that name is silently shadowed: MEASURED on 2026-09-08, the first # real run of this script pinned the CLI's HELP TEXT as the chain identity, because strblk was # invoked with no arguments at all. The verification step caught it - the pinned genesis hash was # empty, so the wrong-chain check failed and the install reported VERIFICATION FAILED - which is # exactly what that check is for. The name is fixed here so it cannot happen again. function Invoke-Strblk { param([string[]]$CliArgs) $p = Get-StrblkParts $all = @() $all += $p.Pre $all += $CliArgs # Through Invoke-Argv: a -Dir or -Genesis ending in a backslash re-split everything after it. return (Invoke-Argv $p.Exe $all -Capture) } # --------------------------------------------------------------------------------------------- # Verification. The same six checks as the POSIX script, in the same order. # --------------------------------------------------------------------------------------------- function Invoke-Verification { Step "verify $Network" $vIdent = 'unknown'; $vOps = 'unknown'; $vRpc = 'unknown'; $vDash = 'unknown' $vChain = 'unknown'; $vPeers = 'unknown'; $vHolder = 'unknown' # 0. WHO HOLDS THE DATA DIRECTORY. # # First, because without it every check after it can pass against somebody else's node. # MEASURED, 2026-09-08, on debian:bookworm-slim with the POSIX script: a second install took # the default ports while the first node still held them, its own endpoints bound nothing, and # verification reported everything green - all of it read off the FIRST node. A verification a # different process can satisfy is not a verification. # # Cerberus writes .cerberus.lock into the data directory with the pid holding it and the # operator endpoint that node actually BOUND - null where the bind failed. That answers both # halves: is a node of ours running, and is this socket its socket. $opsBase = "http://$($Loopback):$OpsPort" if ($Channel -eq 'docker') { $opsBase = "http://$($Loopback):$OpsPortDefault" } $lockFile = Join-Path $Dir '.cerberus.lock' if (-not (Test-Path $lockFile)) { Bad "no .cerberus.lock in $Dir - nothing holds this data directory, so no node from this install is running" $vHolder = 'fail' } else { $lock = Get-Content $lockFile -Raw | ConvertFrom-Json if ($null -eq $lock.endpoint -or $lock.endpoint -eq '') { Bad "the node holding $Dir bound NO operator endpoint (.cerberus.lock records endpoint: null)." Note ' It is running and it cannot be read. The port it was given is held by' Note ' something else - most often another node on this same host. Reinstall' Note ' with -AutoPorts, or free the port.' $vHolder = 'fail' } elseif ($lock.endpoint -ne $opsBase) { Bad "the node holding $Dir is readable at $($lock.endpoint), not at $opsBase" Note " Anything answering at $opsBase belongs to a DIFFERENT node, and" Note " verifying against it would report on somebody else's chain." $vHolder = 'fail' } else { Ok "pid $($lock.pid) holds $Dir and bound $($lock.endpoint)" $vHolder = 'pass' } } $identNow = (Invoke-Strblk (@('genesis') + (Get-NetworkFlags) + @('--identity'))) -join "$([char]10)" if ([string]::IsNullOrWhiteSpace($identNow)) { Bad "identity: 'strblk genesis --identity' produced nothing - the build is not runnable" $vIdent = 'fail' } elseif ($identNow -notmatch '(?m)^genesisHash [0-9a-f]{64}$') { # The SHAPE, not just the presence. --identity prints five 'name value' lines and nothing # else, so output without a 64-hex genesisHash in it is not an identity: it is a usage # message, a stack trace, or a CLI whose output moved. Pinning it would pin nonsense. Bad 'identity: the output is not five name/value lines with a 64-hex genesisHash among them' Say $identNow $vIdent = 'fail' } elseif (Test-Path $IdentFile) { $pinned = (Get-Content $IdentFile) -join "$([char]10)" if ($pinned.Trim() -eq $identNow.Trim()) { Ok 'identity matches the pin taken at install'; $vIdent = 'pass' } else { Bad 'identity has MOVED from the pin taken at install - this build computes a different chain' Say ' pinned:'; Say $pinned; Say ' now:'; Say $identNow $vIdent = 'fail' } } else { Warn "no identity pin at $IdentFile; recording this one, nothing to compare against yet" if (-not $DryRun) { Set-Content -Path $IdentFile -Value $identNow -Encoding ascii } $vIdent = 'recorded' } foreach ($l in ($identNow -split "$([char]10)")) { if ($l.Trim() -ne '') { Say " $l" } } $pinnedGenesis = '' foreach ($l in ($identNow -split "$([char]10)")) { if ($l -match '^genesisHash (.+)$') { $pinnedGenesis = $Matches[1].Trim() } } $opsP = $OpsPort; $rpcP = $RpcPort; $dashP = $DashboardPort if ($Channel -eq 'docker') { $opsP = $OpsPortDefault; $rpcP = $RpcPortDefault; $dashP = $DashPortDefault } # The operator endpoint is asked at the address the LOCK names, so this check is about the node # holding the data directory and not about whatever happens to answer on the configured port. $code = Get-HttpStatus "$opsBase/health" if ($code -eq 200) { Ok "astrolabe /health 200 on $opsP"; $vOps = 'pass' } else { Bad "astrolabe /health returned '$code' on $opsP - the node cannot be read"; $vOps = 'fail' } $code = Get-HttpStatus "http://$($Loopback):$rpcP/health" if ($code -eq 200) { Ok "iris /health 200 on $rpcP"; $vRpc = 'pass' } else { Bad "iris /health returned '$code' on $rpcP - no wallet or explorer can reach this node"; $vRpc = 'fail' } # With a console secret: refused WITHOUT it (401) and served WITH it (200), or it is not this # install's console enforcing this install's secret. A 200 without it is a FAIL. See the POSIX # script. The secret travels in a request header built in-process, never on a command line. $dashUrl = "http://$($Loopback):$dashP/" $code = Get-HttpStatus $dashUrl if (-not [string]::IsNullOrEmpty($script:DashSecret)) { $codeAuth = Get-HttpStatusAuth $dashUrl if ($code -eq 200) { Bad "gungnir answered on $dashP WITHOUT the console secret - the secret this install configured is not enforced"; $vDash = 'fail' } elseif ($codeAuth -eq 200 -and ($code -eq 401 -or $Channel -eq 'docker')) { Ok "gungnir answers on $dashP with the console secret and refuses a request without it"; $vDash = 'pass' } else { Warn "gungnir returned '$code' without the console secret and '$codeAuth' with it on $dashP - no operating surface"; $vDash = 'warn' } } elseif ($code -eq 200) { Ok "gungnir answers on $dashP"; $vDash = 'pass' } else { Warn "gungnir returned '$code' on $dashP - no operating surface"; $vDash = 'warn' } if ($vRpc -eq 'pass') { $body = Invoke-JsonRpc "http://$($Loopback):$rpcP/rpc" '{"jsonrpc":"2.0","id":1,"method":"genesis","params":{}}' $served = '' if ($body -match '"genesisHashHex"\s*:\s*"([0-9a-fA-F]+)"') { $served = $Matches[1] } if ($served -eq '') { Warn 'the rpc endpoint answered but published no genesis hash'; $vChain = 'warn' } elseif ($served -eq $pinnedGenesis) { Ok "the running node serves genesis $served - the chain it is on is the chain installed"; $vChain = 'pass' } else { Bad "the running node is on genesis $served, the install pinned $pinnedGenesis - WRONG CHAIN"; $vChain = 'fail' } } if ($vOps -eq 'pass') { $body = Get-HttpBody "$opsBase/api/status" $peers = $null; $height = $null if ($body -match '"peers"\s*:\s*([0-9]+)') { $peers = [int]$Matches[1] } if ($body -match '"height"\s*:\s*([0-9]+)') { $height = [int]$Matches[1] } if ($null -eq $peers) { Warn 'the operator endpoint answered but published no peer count'; $vPeers = 'warn' } else { $vPeers = "$peers" if ($peers -eq 0 -and $Peers -ne '') { Bad "0 peers, and -Peers named $Peers - this node reached none of them" } elseif ($peers -eq 0) { Warn '0 peers. This node validates what it holds and has joined nothing.' Note ' Asgard has a built-in seed list: PUBLIC_SEED_PEERS in src/core/snotra.ts names the' Note ' seven seeds the Asgard download page publishes, so an Asgard node installed without' Note ' --peers dials them. Dev and Midgard have none, and rpcUrls and explorerUrls are empty' Note ' for every realm, so a dev or Midgard node installed without --peers has nobody to' Note ' dial. It still verifies everything it holds -- that is what makes the network' Note ' hostless -- but it joins nothing, and its height stays where the genesis put it.' Note ' ' Note ' Pass --peers host:port,... to name the mesh yourself; it always replaces the' Note ' built-in list. This installer will not fabricate a peer.' } else { Ok "$peers peer(s), height $height" } } } if ($Json) { $verdict = 'pass' if ($script:Failures -gt 0) { $verdict = 'fail' } elseif ($script:Warnings -gt 0 -and $Strict) { $verdict = 'fail' } elseif ($script:Warnings -gt 0) { $verdict = 'warn' } $o = [ordered]@{ network = $Network; chainId = $RealmChainId; genesisHash = $pinnedGenesis holder = $vHolder identity = $vIdent; astrolabe = $vOps; iris = $vRpc; gungnir = $vDash chain = $vChain; peers = $vPeers failures = $script:Failures; warnings = $script:Warnings; verdict = $verdict } Say ($o | ConvertTo-Json -Compress) } if ($script:Failures -gt 0) { return $false } if ($script:Warnings -gt 0 -and $Strict) { return $false } return $true } function Import-EnvFile { if (-not (Test-Path $EnvFile)) { Die "no install found at $EnvFile - run without -Verify first" } foreach ($line in (Read-EnvText $EnvFile)) { if ($line -cmatch '^(SOURCELESS_[A-Z0-9_]+)=(.*)$') { $k = $Matches[1]; $v = ConvertFrom-EnvValue $Matches[2] switch ($k) { 'SOURCELESS_DATA_DIR' { $script:Dir = $v } 'SOURCELESS_OPS_PORT' { $script:OpsPort = [int]$v } 'SOURCELESS_RPC_PORT' { $script:RpcPort = [int]$v } 'SOURCELESS_DASHBOARD_PORT' { $script:DashboardPort = [int]$v } 'SOURCELESS_CHANNEL' { $script:Channel = $v } 'SOURCELESS_SOURCE_DIR' { if ($v -ne '') { $script:SrcDir = $v } } 'SOURCELESS_PEERS' { $script:Peers = $v } 'SOURCELESS_GENESIS' { $script:Genesis = $v } 'SOURCELESS_IMAGE' { if ($v -ne '') { $script:Image = $v } } 'SOURCELESS_DASHBOARD_SECRET' { $script:DashSecret = $v } } } } } if ($Verify) { Import-EnvFile if (Invoke-Verification) { exit 0 } else { exit 1 } } # --------------------------------------------------------------------------------------------- # 1. The plan # --------------------------------------------------------------------------------------------- Say "brokkr $BrokkrVersion - SourceLess node installer" if ($DryRun) { Say '' Say 'DRY RUN. Nothing below is performed. Every line marked "would" is a command this' Say ' script would run, with its arguments as they would be passed.' } Step 'realm' Note "network $Network" Note "chain id $RealmChainId" Note "runtime mode $RealmMode" if ($RealmLaunched -ne 'yes') { Say '' Say "brokkr: '$Network' is not launched, and this installer will not pretend otherwise." Say '' Say " Snotra's record for it carries a refusal rather than a genesis, and" Say ' assertNetworkIsLaunched turns that into a non-zero exit before a socket opens. There' Say ' is nothing to install: a node started on this realm would stop at the same refusal.' Say '' Show-RealmTable exit 2 } if ($RealmMode -eq 'development') { Warn 'development mode: this node accepts a block from ANY well-signed producer.' Note ' Right for a local mesh. An open door anywhere a stranger can reach.' } if ($RealmKeys -eq 'published') { Warn "this realm's keys are PUBLISHED: every address on it derives from a string in this" Note ' repository. Anyone holding the repository can sign for every account and' Note ' every validator seat. No balance and no signature on it is evidence of' Note ' anything. Do not put value on it.' } if ($RealmGenSrc -eq 'operator' -and $Genesis -eq '') { Die "realm $Network carries no genesis in this build; pass -Genesis FILE" } # --------------------------------------------------------------------------------------------- # 2. Channel # --------------------------------------------------------------------------------------------- Step 'channel' function Test-NodeVersion { if (-not (Have 'node')) { return $false } $v = (& node --version) -replace '^v','' $parts = $v.Split('.') if ([int]$parts[0] -gt 22) { return $true } if ([int]$parts[0] -eq 22 -and [int]$parts[1] -ge 11) { return $true } return $false } if ($Channel -eq 'auto') { if ((Test-NodeVersion) -and ($SourceDir -ne '' -or (Have 'git'))) { $Channel = 'source' } elseif (Have 'docker') { $Channel = 'docker' } elseif ($BinaryUrl -ne '') { $Channel = 'binary' } else { Say 'brokkr: nothing on this machine can produce a node.' Say '' Say ' source needs node >= 22.11 and git' Say ' docker needs docker' Say ' binary needs -BinaryUrl and -Sha256, and there is no published release to take them' Say " from yet; see docs/INSTALL.md, 'the binary channel'." exit 3 } } Note "channel $Channel" if ($Channel -eq 'source' -and -not (Test-NodeVersion)) { Die 'the source channel needs node >= 22.11 on PATH' } if ($Channel -eq 'binary') { if ($BinaryUrl -eq '') { Die 'the binary channel needs -BinaryUrl' } if ($Sha256 -eq '') { Say 'brokkr: the binary channel refuses to install a download it has not checksummed.' Say '' Say ' Pass -Sha256 . There is no -Insecure and no fallback that skips the check,' Say ' because a fallback is what an attacker uses: an installer that verifies when it can' Say ' and proceeds when it cannot verifies nothing.' Say '' Say ' This project publishes no SHA256SUMS and no signing key today, so the digest has to' Say " reach you some other way, and 'verified' here means no more than 'matches the digest" Say " you supplied'. docs/INSTALL.md says what would have to be published for that to be" Say ' worth more.' exit 2 } } if ($Channel -eq 'docker' -and -not (Have 'docker')) { Die 'the docker channel needs docker on PATH' } # The node.exe an elevated install's SYSTEM task will run is the one found here, on PATH or in # SOURCELESS_NODE_BIN. If another account can write it or the directory it sits in, that account # chooses the program SYSTEM runs at every boot. Asked now, before anything is written. if ($InstallerElevated -and $Channel -eq 'source') { Assert-NodeExeTrusted (Resolve-NodeBin) (Get-DirSids) } # --------------------------------------------------------------------------------------------- # 3. Ports # --------------------------------------------------------------------------------------------- Step 'ports' # The docker channel binds nothing on this host: every endpoint listens on the CONTAINER's own # loopback, so the host's ports are not in the question and probing them would refuse an install # for a collision that cannot happen. MEASURED on 2026-09-08, on the machine this was generated # on, where exactly that refusal fired. if ($Channel -eq 'docker') { $OpsPort = $OpsPortDefault $DashboardPort = $DashPortDefault $RpcPort = $RpcPortDefault Note "container the three endpoints listen on the CONTAINER's loopback, at the registry" Note ' defaults. Nothing is published to this host and no host port is taken,' Note ' so nothing here was probed. Verification runs through docker exec.' } elseif ($OpsPort -eq 0 -and $RpcPort -eq 0 -and $DashboardPort -eq 0) { # The search STARTS at this class's own offset, so one of every class installs on one host # without an operator working out a port plan: pulsar takes the registry defaults, quasar +10, # supernova +20. The offsets are in the class register above, so they cannot drift away from # what the systemd units and the local network script use. Without -Class it starts at 0, # exactly as it always did. $offset = -1 $nStart = [int]($ClassPortOffset / 10) for ($n = $nStart; $n -lt ($nStart + 20); $n++) { if (Test-BlockFree ($n * 10)) { $offset = $n * 10; break } } if ($offset -lt 0) { Die 'no free block of three ports found within +190 of this class block' } if ($offset -ne $ClassPortOffset -and -not $AutoPorts) { Say "brokkr: this class's port block is not free on this machine." Say '' Say (" Something already listens on one of {0} / {1} / {2}." -f ($OpsPortDefault + $ClassPortOffset), ($DashPortDefault + $ClassPortOffset), ($RpcPortDefault + $ClassPortOffset)) Say ' This is refused rather than worked around, because a node whose endpoint fails to' Say ' bind STILL STARTS: it prints an alert, reports NOT LISTENING, and runs. That is a' Say ' service reporting healthy with a node nobody can read.' Say '' Say ' Either free those ports, or install into the next free block:' Say '' Say (" -OpsPort {0} -DashboardPort {1} -RpcPort {2}" -f ($OpsPortDefault + $offset), ($DashPortDefault + $offset), ($RpcPortDefault + $offset)) Say '' Say ' or let this script do it: -AutoPorts' exit 2 } $OpsPort = $OpsPortDefault + $offset $DashboardPort = $DashPortDefault + $offset $RpcPort = $RpcPortDefault + $offset if ($offset -ne $ClassPortOffset) { Warn "this class's block was taken; moved all three to +$offset so they stay a readable block" } elseif ($offset -ne 0) { Note "ports +$offset, this class's own block from the register" } } else { # The class's own offset for whichever of the three was not named, so naming one port does not # silently drop the other two onto another class's block. if ($OpsPort -eq 0) { $OpsPort = $OpsPortDefault + $ClassPortOffset } if ($DashboardPort -eq 0) { $DashboardPort = $DashPortDefault + $ClassPortOffset } if ($RpcPort -eq 0) { $RpcPort = $RpcPortDefault + $ClassPortOffset } foreach ($p in @($OpsPort, $DashboardPort, $RpcPort)) { if (-not (Test-PortFree $p)) { Bad "port $p is already in use; the endpoint on it will not bind" } } if ($script:Failures -gt 0) { Die "$script:Failures port(s) in use; pick others or free them" } } Note "ops $($Loopback):$OpsPort astrolabe, /health and /metrics" Note "rpc $($Loopback):$RpcPort iris, the public json-rpc endpoint" Note "dashboard $($Loopback):$DashboardPort gungnir, the operating surface" # --------------------------------------------------------------------------------------------- # 3b. What this class costs, against what this machine has # # **The check that decides whether a mini node is a mini node.** The pulsar class's whole claim # is that it runs on hardware that could not hold a chain, and a claim like that is worth nothing # unless something says so when the hardware cannot hold even the pulsar. # # It WARNS rather than refusing, and -Strict turns the warning into a failing verdict. Refusing # outright would be wrong - an operator knows their machine better than this script does - but # installing silently and finding out at the first out-of-memory kill is worse. # --------------------------------------------------------------------------------------------- if ($Class -ne '') { Step "resources for a $Class" Note "class budget $ClassBudget bytes retained, max peers $ClassMaxPeers, blocks kept $ClassBlocks" Note "requires $ClassMinRam MiB RAM, $ClassMinDisk MiB disk" Note ' RAM = the measured idle resident set + this class retention budget + 64' Note ' MiB headroom. The budget ALONE is not a machine requirement: a pulsar' Note ' reported 0 accounted bytes against 716,800 while its process held' Note ' 76,103,680. See src/network/mnemosyne.ts, which says so itself.' $ramMib = 0 try { $ramMib = [int]((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1MB) } catch { $ramMib = 0 } if ($ramMib -le 0) { Warn 'RAM UNCHECKED - Win32_ComputerSystem could not be read' } elseif ($ramMib -lt $ClassMinRam) { Warn "this machine has $ramMib MiB of RAM; a $Class is profiled at $ClassMinRam MiB" Note ' Nothing here reserves memory, so it will start. What it does under load' Note ' is unmeasured on hardware this size, and the first symptom of getting' Note ' it wrong is the OS killing the node, not a message.' if ($Class -ne 'pulsar') { $pulsarRam = (Get-ClassRow 'pulsar').Split('|')[1] Note (' -Class pulsar is the class for a machine this size: it keeps no chain, follows a constant-size checkpoint, and is profiled at ' + $pulsarRam + ' MiB.') } } else { Ok "RAM $ramMib MiB installed, $ClassMinRam MiB profiled for a $Class" } $freeMib = -1 try { $volumeRoot = [System.IO.Path]::GetPathRoot([System.IO.Path]::GetFullPath($Prefix)) $freeMib = [int]((New-Object System.IO.DriveInfo($volumeRoot)).AvailableFreeSpace / 1MB) } catch { $freeMib = -1 } if ($freeMib -lt 0) { Warn "disk UNCHECKED - the free space on the volume holding $Prefix could not be read" } elseif ($freeMib -lt $ClassMinDisk) { Warn "$freeMib MiB free on the volume holding $Prefix; a $Class is profiled at $ClassMinDisk MiB" } else { Ok "disk $freeMib MiB free, $ClassMinDisk MiB profiled for a $Class" } if ($ClassBlocks -eq 'all') { Note ' disk is a FLOOR and not a bound: this class retains every block, so its' Note ' directory grows with the chain for as long as it runs.' } elseif ($ClassBlocks -ne '0') { Note " disk is a FLOOR and not a bound: this class retains $ClassBlocks blocks." } else { Note ' disk does NOT grow with the chain for this class: it retains no blocks' Note ' at all, and its directory is key material and a lock file.' } Note ' bandwidth UNMEASURED. Nothing in this repository has metered a node' Note ' socket, so no figure is given for it. What IS bounded is the peer table:' Note " at most $ClassMaxPeers peers at 11,264 bytes a record and 8,192 a session." if ($ClassFullState -eq 'no') { Note ' this class serves NO JSON-RPC: Iris needs full state and this one keeps' Note ' none. The rpc port above is reserved and nothing will answer on it.' } } # --------------------------------------------------------------------------------------------- # 4. Directories # --------------------------------------------------------------------------------------------- Step 'directories' # Elevated or not: the prefix, and a data directory outside it, are taken to this account, SYSTEM # and Administrators BEFORE anything is created in them - see Protect-InstallDir. Everything below # inherits that. Invoke-Step "protect $Prefix" { Protect-InstallDir $Prefix (Get-DirSids) } | Out-Null if (-not $DataDirInsidePrefix) { Invoke-Step "protect $Dir" { Protect-InstallDir $Dir (Get-DirSids) } | Out-Null } Invoke-Step "mkdir $Prefix $EtcDir $BinDir $Dir" { foreach ($d in @($Prefix, $EtcDir, $BinDir, $Dir)) { New-Item -ItemType Directory -Force -Path $d | Out-Null } } | Out-Null Note "prefix $Prefix" Note "data $Dir" # --------------------------------------------------------------------------------------------- # 5. Keys at rest # --------------------------------------------------------------------------------------------- Step 'keys at rest' $Passphrase = '' switch ($Seal) { 'env' { $Passphrase = [Environment]::GetEnvironmentVariable($KeyEnv) if ([string]::IsNullOrEmpty($Passphrase)) { Die "-Seal env, but $KeyEnv is not set in this environment" } Ok "using the passphrase already in $KeyEnv; nothing written to disk" } 'prompt' { $secure = Read-Host -AsSecureString " passphrase for the node keystore" $Passphrase = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)) if ([string]::IsNullOrEmpty($Passphrase)) { Die 'empty passphrase' } Ok 'held for this run only; nothing written to disk. This node cannot restart unattended.' } 'file' { if ($DryRun) { Note "would generate 32 bytes from the OS CSPRNG and write $PassFile, ACL'd to this user only" } elseif (Test-Path $PassFile) { $Passphrase = (Get-Content $PassFile -Raw).Trim() Ok "reusing the passphrase at $PassFile - the existing keystore stays readable" } else { $bytes = New-Object byte[] 32 $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create() $rng.GetBytes($bytes) $Passphrase = ([Convert]::ToBase64String($bytes)) -replace '=','' New-PrivateFile $PassFile Set-Content -LiteralPath $PassFile -Value $Passphrase -NoNewline -Encoding ascii # chmod is nearly a no-op on Windows (src/node/keystore.ts says so), so the ACL is the # control: inheritance broken, one ACE for the installing user, nothing else. # (F) and not (R,W). The ACE is there to exclude OTHER accounts, not to restrict this one: # MEASURED on 2026-09-08, (R,W) with inheritance removed produced a file the installing # user could not delete - "Permission denied" on their own passphrase file - because delete # is its own right and (R,W) does not include it. An installer that leaves undeletable # files behind is worse than one that leaves none. Ok "generated 32 bytes from the OS CSPRNG, sealed the keystore, ACL'd $PassFile to this user" } } 'none' { Warn 'keys will be stored UNENCRYPTED at rest. And see the console secret below: it is' Note ' generated regardless of -Seal, because the two protect different things.' Note " Anyone who can read $Dir - a backup, an image layer, another user on" Note ' this host - can sign blocks and peer records as this node. The node' Note ' prints a full-width banner about it at every single start.' Note ' And if this host ever takes a VALIDATOR SEAT on a production realm it' Note ' will not start at all: a node holding a seat key in the clear is' Note ' refused before it opens a store or a socket. Re-run with -Seal file.' } } # --------------------------------------------------------------------------------------------- # 5b. The operating console's shared secret # --------------------------------------------------------------------------------------------- # # WHY THIS IS GENERATED AND NOT OFFERED. # # --dashboard-secret is optional in the node and no installer in this repository had ever set # one, so every brokkr install shipped an operating console whose ONLY perimeter was the # loopback bind. That perimeter is one reverse proxy away from nothing at all, and it fails # open rather than closed: an unauthenticated GET / hands out the session token the console # uses, and that token is everything a POST needs. It was reproduced - an operator action # executed from an anonymous GET carrying a scraped CSRF token. # # A generated secret costs an operator nothing on a loopback-only box and is the whole # difference on the day somebody puts a proxy in front, so it is generated always rather than # being a flag somebody has to know to reach for. Written to a file ACL'd to this account so a # re-run reuses it instead of locking out a proxy already configured with the old one. # # WHAT IT IS NOT. A bearer secret: whatever can read this file or the node's environment can act # as the console. Not TLS, and not an identity - the console still needs -DashboardKey to act at # all. It raises the cost of an anonymous request that reaches the port from zero. Step 'console secret' $DashSecretEnv = 'SOURCELESS_DASHBOARD_SECRET' $DashSecret = [Environment]::GetEnvironmentVariable($DashSecretEnv) if (-not [string]::IsNullOrEmpty($DashSecret)) { # Refused by NAME. The value is a secret and is never printed. if ($DashSecret -match "[\r\n]") { Die "$DashSecretEnv carries a newline, which an env file cannot hold. Set it without one." } Ok "using the secret already in $DashSecretEnv. It is kept in the env file, ACL'd to this user," Note ' which is how the node still has it after a reboot. The secret file is not written.' } elseif ($DryRun) { $DashSecret = '' Note "would generate 32 bytes from the OS CSPRNG and write $DashSecretFile, ACL'd to this user only" } elseif (Test-Path $DashSecretFile) { $DashSecret = (Get-Content $DashSecretFile -Raw).Trim() Ok "reusing the console secret at $DashSecretFile - anything already configured with it keeps working" } else { $dashBytes = New-Object byte[] 32 $dashRng = [System.Security.Cryptography.RandomNumberGenerator]::Create() $dashRng.GetBytes($dashBytes) $DashSecret = ([Convert]::ToBase64String($dashBytes)) -replace '=','' # The same rule as the passphrase file: ACL'd and checked before the secret is in it. New-PrivateFile $DashSecretFile Set-Content -LiteralPath $DashSecretFile -Value $DashSecret -NoNewline -Encoding ascii Ok "generated 32 bytes from the OS CSPRNG, ACL'd $DashSecretFile to this user" } if (-not [string]::IsNullOrEmpty($DashSecret)) { Note ' every request to the console must now carry it, as' Note ' "Authorization: Bearer SECRET" or ?secret=SECRET. Read it with:' Note " type $DashSecretFile" Note ' This does not make the console safe to expose. It makes a proxy in front' Note ' of it survivable. -DashboardHost is still loopback and should stay there.' } # --------------------------------------------------------------------------------------------- # 6. Obtain the runtime # --------------------------------------------------------------------------------------------- Step 'runtime' switch ($Channel) { 'source' { if ($SourceDir -ne '') { Note "building in place from $SrcDir" } elseif (Test-Path (Join-Path $SrcDir '.git')) { Invoke-Step "git -C $SrcDir fetch --tags" { Invoke-Argv 'git' @('-C', $SrcDir, 'fetch', '--tags', '--quiet') } | Out-Null if ($Ref -ne '') { Invoke-Step "git -C $SrcDir checkout $Ref" { Invoke-Argv 'git' @('-C', $SrcDir, 'checkout', '--quiet', $Ref) } | Out-Null } } else { Invoke-Step "git clone $Repo $SrcDir" { if ($Ref -ne '') { Invoke-Argv 'git' @('clone', '--quiet', '--branch', $Ref, $Repo, $SrcDir) } else { Invoke-Argv 'git' @('clone', '--quiet', $Repo, $SrcDir) } } | Out-Null } # --ignore-scripts for the reason CI and the Dockerfile both give: install hooks are where # the npm supply-chain worms of 2025-26 ran, and nothing here needs a build step on install. Invoke-Step 'npm ci --ignore-scripts' { Push-Location $SrcDir; try { & npm ci --ignore-scripts } finally { Pop-Location } } | Out-Null Invoke-Step 'npm run build' { Push-Location $SrcDir; try { & npm run build } finally { Pop-Location } } | Out-Null } 'binary' { $tmp = Join-Path $BinDir "$BinName.download" Invoke-Step "download $BinaryUrl" { Invoke-WebRequest -Uri $BinaryUrl -OutFile $tmp -UseBasicParsing } | Out-Null if (-not $DryRun) { $got = (Get-FileHash -Algorithm SHA256 -Path $tmp).Hash.ToLower() if ($got -ne $Sha256.ToLower()) { Remove-Item $tmp -Force Say 'brokkr: CHECKSUM MISMATCH - the download was deleted and nothing was installed.' Say " expected $Sha256" Say " got $got" exit 2 } Ok "sha256 $got matches" Move-Item -Force $tmp (Join-Path $BinDir $BinName) } } 'docker' { if ($SourceDir -ne '') { Invoke-Step "docker build -t $Image $SourceDir" { Invoke-Argv 'docker' @('build', '-t', $Image, $SourceDir) } | Out-Null } else { Invoke-Step "docker image inspect $Image" { Invoke-Argv 'docker' @('image', 'inspect', $Image) -Capture | Out-Null } | Out-Null } } } $parts = Get-StrblkParts Note ("strblk {0} {1}" -f $parts.Exe, ($parts.Pre -join ' ')) # --------------------------------------------------------------------------------------------- # 7. Pin the chain identity # --------------------------------------------------------------------------------------------- Step 'chain identity' if ($DryRun) { Note "would run: strblk genesis $((Get-NetworkFlags) -join ' ') --identity > $IdentFile" } else { $identNow = (Invoke-Strblk (@('genesis') + (Get-NetworkFlags) + @('--identity'))) -join "$([char]10)" if ($identNow -notmatch '(?m)^genesisHash [0-9a-f]{64}$') { Say $identNow Die 'strblk genesis --identity printed no 64-hex genesisHash. Refusing to pin that as the chain identity.' } Set-Content -Path $IdentFile -Value $identNow -Encoding ascii foreach ($l in ($identNow -split "$([char]10)")) { if ($l.Trim() -ne '') { Say " $l" } } Ok "pinned at $IdentFile" } # --------------------------------------------------------------------------------------------- # 8. Configuration # --------------------------------------------------------------------------------------------- Step 'configuration' # For the docker channel these are the CONTAINER's arguments: /data is the mount point inside # it, and the endpoint ports stay at the registry defaults because nothing else shares that # network namespace. Passing this host's paths into a container was MEASURED producing a runner # script that named a Windows directory the container could not see. if ($Channel -eq 'docker') { $nodeArgs = @('node', '--dir', '/data') + (Get-NetworkFlags) + @('--block-interval', "$BlockInterval") } else { $nodeArgs = @('node', '--dir', $Dir) + (Get-NetworkFlags) + @( '--ops-port', "$OpsPort", '--rpc-port', "$RpcPort", '--dashboard-port', "$DashboardPort", '--block-interval', "$BlockInterval") } if ($Peers -ne '') { $nodeArgs += @('--peers', $Peers) } if ($Class -ne '') { $nodeArgs += @('--class', $Class) } if ($P2pPort -ne 0) { $nodeArgs += @('--port', "$P2pPort") } # --advertise, which this platform had no flag for at all until 2026-09-17. The POSIX script has # carried it since 2026-09-12 and the cost of its absence is exactly what docs/RUNBOOK_VPS.md # names as the commonest first failure: advertisedEndpoint() returns null for a wildcard bind, so # a node that advertises nothing cannot be passed on by any peer it talks to, and a Windows seed # was reachable only by whoever already knew where it was. if ($Advertise -ne '') { $nodeArgs += @('--advertise', $Advertise) } if ($DryRun) { Note "would write $EnvFile" Note "would write $Runner" } else { $p = Get-StrblkParts $entry = '' $nodeBin = '' $binPath = '' if ($Channel -eq 'source') { $nodeBin = $p.Exe; $entry = $p.Pre[0] } if ($Channel -eq 'binary') { $binPath = $p.Exe } $passRef = if ($Seal -eq 'file') { $PassFile } else { '' } $dockerEnvRef = if ($Channel -eq 'docker') { $DockerEnvFile } else { '' } $envLines = @( "# Written by brokkr $BrokkrVersion. One node, one file.", "# The names are the ones deploy/systemd/strblk-node.env uses, so the two are interchangeable.", (New-EnvLine 'SOURCELESS_NETWORK' $Network), (New-EnvLine 'SOURCELESS_DATA_DIR' $Dir), (New-EnvLine 'SOURCELESS_OPS_PORT' "$OpsPort"), (New-EnvLine 'SOURCELESS_RPC_PORT' "$RpcPort"), (New-EnvLine 'SOURCELESS_DASHBOARD_PORT' "$DashboardPort"), (New-EnvLine 'SOURCELESS_BLOCK_INTERVAL_MS' "$BlockInterval"), (New-EnvLine 'SOURCELESS_PEERS' $Peers), (New-EnvLine 'SOURCELESS_ADVERTISE' $Advertise), (New-EnvLine 'SOURCELESS_CLASS' $Class), (New-EnvLine 'SOURCELESS_P2P_PORT' "$P2pPort"), (New-EnvLine 'SOURCELESS_INSTANCE' $Instance), "# The four flags a systemd unit interpolates. Written here too, resolved, so this file and", "# deploy/systemd/strblk-node-.env are interchangeable across platforms.", (New-EnvLine 'SOURCELESS_CLASS_FLAG' $(if ($Class -ne '') { "--class $Class" } else { '' })), (New-EnvLine 'SOURCELESS_P2P_PORT_FLAG' $(if ($P2pPort -ne 0) { "--port $P2pPort" } else { '' })), (New-EnvLine 'SOURCELESS_PEERS_FLAG' $(if ($Peers -ne '') { "--peers $Peers" } else { '' })), (New-EnvLine 'SOURCELESS_ADVERTISE_FLAG' $(if ($Advertise -ne '') { "--advertise $Advertise" } else { '' })), (New-EnvLine 'SOURCELESS_GENESIS' $Genesis), (New-EnvLine 'SOURCELESS_CHANNEL' $Channel), (New-EnvLine 'SOURCELESS_PREFIX' $Prefix), "# Where the compiled tree is. Not derivable from the prefix: -SourceDir builds in place.", (New-EnvLine 'SOURCELESS_SOURCE_DIR' $SrcDir), (New-EnvLine 'SOURCELESS_IMAGE' $Image), (New-EnvLine 'SOURCELESS_SEAL' $Seal), "# What the launcher starts, and from where: read by it as data, never pasted into a script.", (New-EnvLine 'SOURCELESS_NODE_BIN' $nodeBin), (New-EnvLine 'SOURCELESS_ENTRY' $entry), (New-EnvLine 'SOURCELESS_BIN' $binPath), (New-EnvLine 'SOURCELESS_CONTAINER' $Container), (New-EnvLine 'SOURCELESS_PASS_FILE' $passRef), (New-EnvLine 'SOURCELESS_DOCKER_ENV_FILE' $dockerEnvRef), "# The console's shared secret, read by the node from this name (src/cli/strblk.ts reads", "# process.env.SOURCELESS_DASHBOARD_SECRET before it reads --dashboard-secret). HERE and not", "# on the command line: an argument is in the process list of every account on this host.", "# It is also what keeps a secret supplied in the environment across a reboot.", (New-EnvLine $DashSecretEnv $DashSecret) ) New-PrivateFile $EnvFile Write-EnvText $EnvFile $envLines Ok "wrote $EnvFile" if ($Channel -eq 'docker') { # docker's --env-file is raw NAME=VALUE to the end of the line, so it is its own file rather # than the env file. Written HERE, by PowerShell, and ACL'd like the passphrase file: the # runner used to build it at every start with cmd's 'echo NAME=%NAME%', and cmd expands # %NAME% before it parses, so a secret carrying & | < > ^ ran as cmd syntax - REPRODUCED. # It does NOT hide either secret from 'docker inspect' - MEASURED, docker 27.5.1. $dockerEnvLines = @() if ($Seal -eq 'file') { $passValue = [string](Get-Content -LiteralPath $PassFile -TotalCount 1) $dockerEnvLines += ($KeyEnv + '=' + $passValue) $passValue = $null } if (-not [string]::IsNullOrEmpty($DashSecret)) { $dockerEnvLines += ($DashSecretEnv + '=' + $DashSecret) } New-PrivateFile $DockerEnvFile Write-EnvText $DockerEnvFile $dockerEnvLines Ok "wrote $DockerEnvFile" } # The runner: a fixed .cmd shim and the PowerShell launcher beside it, which reads the env file # above and starts the node with an argument array. The env file's path is the only install # value written into either, as a single-quoted PowerShell literal. See windowsLauncherPs1 in # scripts/brokkr.mjs for what it replaced and why. $launcherLines = @( "# Written by brokkr $BrokkrVersion. Every value below comes from the env file, read as data.", ('$EnvFile = ' + (ConvertTo-PsLiteral $EnvFile)) ) + $LauncherBody Set-Content -Path $Launcher -Value $launcherLines -Encoding utf8 Set-Content -Path $Runner -Value $RunnerCmd -Encoding ascii Ok "wrote $Runner and $Launcher" } if ($Channel -eq 'docker') { Note ("command docker run -d --name {0} -v {1}:/data {2} {3}" -f $Container, $Dir, $Image, ($nodeArgs -join ' ')) } else { Note ("command {0} {1}" -f $parts.Exe, (($parts.Pre + $nodeArgs) -join ' ')) } # --------------------------------------------------------------------------------------------- # 9. Service # # There is no systemd here, and a Windows SERVICE needs a binary that implements the service # control protocol - which strblk does not and should not. The honest options are a third-party # wrapper, which this installer will not download, or a Scheduled Task. So: a Scheduled Task # whose action is the SUPERVISOR, never the node directly. # # **The supervisor is the part that was missing, and its absence has a measured cost.** An earlier # deployment ran a block generator as a detached nohup; it died, nothing restarted it, nothing # said anything, and block production stopped. A Scheduled Task on its own does not close that: # RestartCount restarts a task whose action FAILED, and a node that exits 0 has not failed by that # definition. The supervisor restarts on every exit, code 0 included, keeps a rolling burst limit # so a node that cannot start is left STOPPED rather than looping, and appends every decision to # a journal. That is systemd's Restart=always, RestartSec, StartLimitBurst and # StartLimitIntervalSec, in the four places Windows leaves empty. # # Elevated, the task triggers AT STARTUP as SYSTEM, which is the systemd guarantee. Unelevated it # triggers at logon as the installing user, which is not - and the script says which one you got # rather than leaving it to be discovered during an incident. # --------------------------------------------------------------------------------------------- Step 'service' if ($Service -eq 'auto') { # A task when one can be registered, rather than falling to none. 'none' means the operator # starts the runner by hand, which is a detached background process under another name, and # that is the failure this whole step exists to prevent. $Service = 'task' } switch ($Service) { 'task' { if ($Channel -eq 'docker') { Note 'the docker channel manages its own restarts. -Service task is not wired for it:' Note ' a container runtime already has a restart policy, and two supervisors' Note ' over one container is how a container comes back while its data' Note ' directory is still held.' break } if ($DryRun) { Note "would write $Supervisor" Note "would write $ServiceTool" Note "would register the Scheduled Task '$TaskName', action: the supervisor running $Runner" Note ' at STARTUP as SYSTEM when elevated, at logon as you otherwise' break } # The two files are written from THIS script rather than copied out of the repository, # because an install from the binary channel has no repository on the machine. They are the # same bytes deploy/windows/ carries: one generator, two destinations, and # 'node scripts/pharos.mjs --check' fails if either drifts. $superviseLines = @( '# Brokkr 0.2.0 - the SourceLess node supervisor for Windows.', '#', '# GENERATED by scripts/brokkr.mjs, written and checked by scripts/pharos.mjs. Do not edit this', '# file; edit the generator.', '#', '# It is the thing a Scheduled Task runs. It is NOT something to start by hand from a console and', '# walk away from - that is the detached background process this file exists to replace. Register', '# it with deploy/windows/strblk-service.ps1, which gives it a trigger and a principal.', '#', '# powershell -NoProfile -ExecutionPolicy Bypass -File strblk-supervise.ps1 -Runner C:\path\strblk-node-dev.cmd', '#', '# Every restart, every exit code and every decision it takes is appended to the journal beside', '# the node log, because the failure this replaces was silent and silence is the defect.', '', '[CmdletBinding()]', 'param(', ' # The .cmd written by brokkr.ps1, which carries the node''s whole argument list. A runner rather', ' # than an argument list, so that the supervisor holds no opinion about how a node is started.', ' #', ' # NOT Parameter(Mandatory): PowerShell enforces that before the body runs, so -Help alone died', ' # with "Cannot process command because of one or more missing mandatory parameters: Runner" -', ' # which answers the one question that must never be answered by refusing. It is checked below', ' # instead, after the usage gate, and the refusal is the same either way.', ' [string]$Runner = '''',', ' # Where the node''s own stdout and stderr are appended. Default: beside the runner.', ' [string]$LogFile = '''',', ' # Where this supervisor records what it did. Default: beside the log.', ' [string]$Journal = '''',', ' [string]$Name = ''strblk'',', ' # systemd''s RestartSec.', ' [int]$RestartSeconds = 5,', ' # systemd''s StartLimitBurst and StartLimitIntervalSec.', ' [int]$MaxRestarts = 5,', ' [int]$WindowSeconds = 600,', ' [switch]$Help', ')', '', '$ErrorActionPreference = ''Stop''', '', 'if ($Help) {', ' Write-Host ''usage: strblk-supervise.ps1 -Runner [options]''', ' Write-Host ''''', ' Write-Host '' -Runner PATH REQUIRED. The .cmd brokkr wrote; it carries the node arguments.''', ' Write-Host '' -LogFile PATH Node stdout and stderr, appended. Default: beside the runner.''', ' Write-Host '' -Journal PATH What the supervisor did. Default: beside the log.''', ' Write-Host '' -Name NAME What it calls itself in the journal.''', ' Write-Host '' -RestartSeconds N Seconds between attempts (systemd RestartSec). Default 5.''', ' Write-Host '' -MaxRestarts N Attempts inside the window before it gives up. Default 5.''', ' Write-Host '' -WindowSeconds N The rolling window (systemd StartLimitIntervalSec). Default 600.''', ' Write-Host ''''', ' Write-Host '' It restarts the node on EVERY exit, code 0 included, because a node that exited''', ' Write-Host '' cleanly has still stopped being a node. When it exhausts the burst it exits''', ' Write-Host '' non-zero and stops, so that "cannot start" is a state and not a log flood.''', ' exit 0', '}', '', 'if ($Runner -eq '''') {', ' Write-Host ''strblk-supervise: -Runner is required. It is the node runner .cmd that brokkr wrote.''', ' Write-Host '' -Help prints the whole flag list and starts nothing.''', ' exit 2', '}', 'if (-not (Test-Path -LiteralPath $Runner)) {', ' Write-Host "strblk-supervise: no runner at $Runner"', ' exit 2', '}', '$Runner = (Resolve-Path -LiteralPath $Runner).Path', '$runnerDir = Split-Path -Parent $Runner', 'if ($LogFile -eq '''') { $LogFile = Join-Path $runnerDir ($Name + ''.log'') }', 'if ($Journal -eq '''') { $Journal = Join-Path $runnerDir ($Name + ''.supervisor.log'') }', '', 'function Write-Journal {', ' param([string]$Event, [string]$Detail)', ' $stamp = (Get-Date).ToUniversalTime().ToString(''yyyy-MM-ddTHH:mm:ss.fffZ'')', ' $line = ''{0} {1} {2} {3}'' -f $stamp, $Name, $Event, $Detail', ' # Best effort, and it must never be the reason a node stops. A supervisor that dies because a', ' # log volume filled is a supervisor that took the node with it.', ' try { Add-Content -LiteralPath $Journal -Value $line -Encoding utf8 } catch { }', ' Write-Host $line', '}', '', 'Write-Journal ''supervisor-start'' ("runner=$Runner log=$LogFile restartSec=$RestartSeconds burst=$MaxRestarts/$($WindowSeconds)s")', '', '# The rolling window of start times, so the limiter forgets old failures the way systemd does.', '$starts = New-Object System.Collections.Generic.List[datetime]', '', 'while ($true) {', ' $now = Get-Date', ' $cutoff = $now.AddSeconds(-1 * $WindowSeconds)', ' $recent = @($starts | Where-Object { $_ -gt $cutoff })', ' $starts.Clear()', ' foreach ($t in $recent) { [void]$starts.Add($t) }', '', ' if ($starts.Count -ge $MaxRestarts) {', ' Write-Journal ''start-limit-hit'' ("$($starts.Count) starts inside $($WindowSeconds)s; giving up. This is systemd''s StartLimitBurst: the node is left STOPPED so the reason above is readable and so a monitor sees a failed task rather than a log flood.")', ' exit 1', ' }', '', ' [void]$starts.Add($now)', ' Write-Journal ''node-start'' "attempt $($starts.Count) of $MaxRestarts in this window"', '', ' # cmd.exe, so the node''s two streams are APPENDED to one file rather than truncated. Start-Process', ' # -RedirectStandardOutput truncates on every start, which would erase the reason for the previous', ' # exit at the exact moment somebody needed it.', ' $command = ''/s /c '' + ''"'' + ''"'' + $Runner + ''"'' + '' >> '' + ''"'' + $LogFile + ''"'' + '' 2>&1'' + ''"''', ' #', ' # ProcessStartInfo and not Start-Process -PassThru. MEASURED 2026-09-17: with -PassThru the', ' # journal recorded "node-exit code=" on every one of five restarts - the ExitCode property on', ' # the object PowerShell hands back is null, because that object is not the one holding the', ' # process handle. The exit code is the single most useful thing a supervisor can record: 2 is', ' # strblk saying the arguments are wrong and no restart will help, and an empty field there', ' # turns a diagnosable failure into "it keeps stopping".', ' $exitCode = ''unknown''', ' try {', ' $psi = New-Object System.Diagnostics.ProcessStartInfo', ' $psi.FileName = $env:ComSpec', ' $psi.Arguments = $command', ' $psi.UseShellExecute = $false', ' $psi.CreateNoWindow = $true', ' $proc = [System.Diagnostics.Process]::Start($psi)', ' $proc.WaitForExit()', ' $exitCode = $proc.ExitCode', ' } catch {', ' Write-Journal ''node-spawn-failed'' $_.Exception.Message', ' }', '', ' Write-Journal ''node-exit'' "code=$exitCode"', ' if ($exitCode -eq 2) {', ' # strblk''s own exit codes: 2 is "you typed something wrong", which means the command never ran.', ' # Restarting it will produce the identical refusal for ever, so it is named here rather than', ' # being one more indistinguishable line.', ' Write-Journal ''note'' ''exit 2 from strblk means a usage refusal: the arguments in the runner are wrong and no restart can fix them.''', ' }', ' Write-Journal ''restart-wait'' "$RestartSeconds seconds"', ' Start-Sleep -Seconds $RestartSeconds', '}' ) Set-Content -Path $Supervisor -Value $superviseLines -Encoding utf8 Ok "wrote $Supervisor" $serviceLines = @( '# Brokkr 0.2.0 - the SourceLess node service for Windows, one per STARW class.', '#', '# GENERATED by scripts/brokkr.mjs, written and checked by scripts/pharos.mjs. Do not edit this', '# file; edit the generator.', '#', '# strblk-service.ps1 install -Class pulsar -Runner C:\...\strblk-node-dev.cmd', '# strblk-service.ps1 start -Class pulsar', '# strblk-service.ps1 status -Class pulsar', '# strblk-service.ps1 stop -Class pulsar', '# strblk-service.ps1 remove -Class pulsar', '# strblk-service.ps1 status (every class at once)', '#', '# THE WINDOWS EQUIVALENT OF A SYSTEMD UNIT, AND WHERE IT IS NOT EQUIVALENT.', '#', '# strblk is not a Windows service binary: a real service implements the service control protocol,', '# which a Node program does not and should not. So this registers a Scheduled Task whose action is', '# the supervisor, and the supervisor is what gives it Restart=always and a burst limiter. The task', '# alone would not: RestartCount restarts a task whose action FAILED, and a node that exits 0 has', '# not failed by that definition - which is the exact gap that let a detached block generator die', '# silently and stop block production.', '#', '# Run this elevated and the task triggers at STARTUP as SYSTEM, which is the systemd guarantee.', '# Run it unelevated and it triggers at LOGON as you, which is not: nothing runs before somebody', '# logs in. It tells you which one you got.', '', '[CmdletBinding()]', 'param(', ' [Parameter(Position = 0)][ValidateSet(''install'',''start'',''stop'',''status'',''remove'',''help'')][string]$Verb = ''help'',', ' [ValidateSet(''pulsar'',''quasar'',''supernova'')][string]$Class = '''',', ' [string]$Runner = '''',', ' [string]$Supervisor = '''',', ' [string]$LogFile = '''',', ' [int]$RestartSeconds = 5,', ' [int]$MaxRestarts = 5,', ' [int]$WindowSeconds = 600,', ' [switch]$Help', ')', '', '$ErrorActionPreference = ''Stop''', '', 'function Show-Usage {', ' Write-Host ''usage: strblk-service.ps1 -Class ''', ' Write-Host ''''', ' Write-Host '' install Register the task. -Runner is REQUIRED: the .cmd brokkr wrote.''', ' Write-Host '' start Start it now.''', ' Write-Host '' stop Stop it. The supervisor and the node both go; the task stays registered.''', ' Write-Host '' status What is registered, what is running, and the last result.''', ' Write-Host '' remove Unregister it. Stops it first.''', ' Write-Host ''''', ' Write-Host '' -Class C pulsar | quasar | supernova. Required for everything but status.''', ' Write-Host '' -Runner PATH The node runner .cmd. Required for install.''', ' Write-Host '' -Supervisor PATH strblk-supervise.ps1. Default: beside this script.''', ' Write-Host '' -LogFile PATH Node stdout and stderr. Default: beside the runner.''', ' Write-Host '' -RestartSeconds N systemd RestartSec. Default 5.''', ' Write-Host '' -MaxRestarts N systemd StartLimitBurst. Default 5.''', ' Write-Host '' -WindowSeconds N systemd StartLimitIntervalSec. Default 600.''', ' Write-Host ''''', ' Write-Host '' Elevated: the task triggers at STARTUP as SYSTEM - the systemd guarantee.''', ' Write-Host '' Unelevated: it triggers at LOGON as you, and nothing runs before you log in.''', '}', '', 'if ($Help -or $Verb -eq ''help'') { Show-Usage; exit 0 }', '', '$Classes = @(''pulsar'',''quasar'',''supernova'')', 'function Get-TaskName { param([string]$c) return "SourceLess strblk node ($c)" }', '', 'function Test-Elevated {', ' $id = [Security.Principal.WindowsIdentity]::GetCurrent()', ' return (New-Object Security.Principal.WindowsPrincipal($id)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)', '}', '', 'function Get-Task { param([string]$c) return (Get-ScheduledTask -TaskName (Get-TaskName $c) -ErrorAction SilentlyContinue) }', '', 'function Show-Status {', ' param([string]$c)', ' $task = Get-Task $c', ' if ($null -eq $task) { Write-Host (" {0,-10} not registered" -f $c); return }', ' $info = Get-ScheduledTaskInfo -TaskName (Get-TaskName $c) -ErrorAction SilentlyContinue', ' $trigger = ($task.Triggers | ForEach-Object { $_.CimClass.CimClassName }) -join '',''', ' $user = $task.Principal.UserId', ' $last = if ($null -ne $info) { $info.LastTaskResult } else { ''unknown'' }', ' $when = if ($null -ne $info) { $info.LastRunTime } else { ''never'' }', ' Write-Host (" {0,-10} {1,-10} as {2} trigger {3} lastResult {4} lastRun {5}" -f $c, $task.State, $user, $trigger, $last, $when)', ' if ($last -eq 1) {', ' Write-Host '' lastResult 1 is the supervisor giving up after its burst limit.''', ' Write-Host '' Read the .supervisor.log beside the runner: the reason is in it.''', ' }', '}', '', 'switch ($Verb) {', ' ''status'' {', ' Write-Host ''SourceLess node services (Scheduled Tasks running the supervisor)''', ' if ($Class -ne '''') { Show-Status $Class } else { foreach ($c in $Classes) { Show-Status $c } }', ' exit 0', ' }', ' ''install'' {', ' if ($Class -eq '''') { Write-Host ''strblk-service: install needs -Class''; exit 2 }', ' if ($Runner -eq '''') { Write-Host ''strblk-service: install needs -Runner, the node runner .cmd brokkr wrote''; exit 2 }', ' if (-not (Test-Path -LiteralPath $Runner)) { Write-Host "strblk-service: no runner at $Runner"; exit 2 }', ' if ($Supervisor -eq '''') { $Supervisor = Join-Path $PSScriptRoot ''strblk-supervise.ps1'' }', ' if (-not (Test-Path -LiteralPath $Supervisor)) { Write-Host "strblk-service: no supervisor at $Supervisor"; exit 2 }', ' $Runner = (Resolve-Path -LiteralPath $Runner).Path', ' $Supervisor = (Resolve-Path -LiteralPath $Supervisor).Path', ' if ($LogFile -eq '''') { $LogFile = Join-Path (Split-Path -Parent $Runner) (''strblk-'' + $Class + ''.log'') }', '', ' $psArgs = @(', ' ''-NoProfile'', ''-ExecutionPolicy'', ''Bypass'', ''-NonInteractive'', ''-File'', (''"'' + $Supervisor + ''"''),', ' ''-Runner'', (''"'' + $Runner + ''"''),', ' ''-LogFile'', (''"'' + $LogFile + ''"''),', ' ''-Name'', (''strblk-'' + $Class),', ' ''-RestartSeconds'', "$RestartSeconds",', ' ''-MaxRestarts'', "$MaxRestarts",', ' ''-WindowSeconds'', "$WindowSeconds"', ' ) -join '' ''', '', ' $action = New-ScheduledTaskAction -Execute ''powershell.exe'' -Argument $psArgs', ' $elevated = Test-Elevated', ' if ($elevated) {', ' $trigger = New-ScheduledTaskTrigger -AtStartup', ' $principal = New-ScheduledTaskPrincipal -UserId ''SYSTEM'' -LogonType ServiceAccount -RunLevel Highest', ' } else {', ' $trigger = New-ScheduledTaskTrigger -AtLogOn', ' $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive', ' }', ' # ExecutionTimeLimit zero: a node runs for ever and a time limit would stop it. MultipleInstances', ' # IgnoreNew: two supervisors on one data directory is refused by Cerberus anyway, and a refusal', ' # loop is a worse way to find that out. The battery directives matter on the small machine a', ' # mini node is meant for - a laptop on battery must still keep its pulsar running.', ' $settings = New-ScheduledTaskSettingsSet -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -StartWhenAvailable -DontStopOnIdleEnd -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries', ' try {', ' Register-ScheduledTask -TaskName (Get-TaskName $Class) -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null', ' } catch {', ' Write-Host "strblk-service: the task was NOT registered: $($_.Exception.Message)"', ' Write-Host '' MEASURED on 2026-09-08 on Windows 11: Register-ScheduledTask returns "Access is''', ' Write-Host '' denied" (0x80070005) from an unelevated prompt where policy restricts task''', ' Write-Host '' creation. Re-run from an elevated PowerShell, which is also the run that gets''', ' Write-Host '' you a boot service rather than a logon one.''', ' exit 1', ' }', ' Write-Host ("registered ''{0}''" -f (Get-TaskName $Class))', ' if ($elevated) {', ' Write-Host '' trigger AT STARTUP, as SYSTEM. This is the systemd guarantee: the node comes''', ' Write-Host '' back after a reboot with nobody logged in.''', ' } else {', ' Write-Host '' trigger AT LOGON, as you, because this prompt is not elevated. NOT the systemd''', ' Write-Host '' guarantee: nothing runs before somebody logs in. Re-run elevated for''', ' Write-Host '' a boot service.''', ' }', ' Write-Host ('' action '' + $Supervisor)', ' Write-Host ('' restart every exit, code 0 included; '' + $RestartSeconds + ''s apart; '' + $MaxRestarts + '' inside '' + $WindowSeconds + ''s then it stops'')', ' Write-Host ('' node log '' + $LogFile)', ' Write-Host ('' journal '' + (Join-Path (Split-Path -Parent $Runner) (''strblk-'' + $Class + ''.supervisor.log'')))', ' Write-Host ('' start it strblk-service.ps1 start -Class '' + $Class)', ' exit 0', ' }', ' ''start'' {', ' if ($Class -eq '''') { Write-Host ''strblk-service: start needs -Class''; exit 2 }', ' if ($null -eq (Get-Task $Class)) { Write-Host "strblk-service: ''$(Get-TaskName $Class)'' is not registered"; exit 1 }', ' Start-ScheduledTask -TaskName (Get-TaskName $Class)', ' Write-Host ("started ''{0}''" -f (Get-TaskName $Class))', ' Show-Status $Class', ' exit 0', ' }', ' ''stop'' {', ' if ($Class -eq '''') { Write-Host ''strblk-service: stop needs -Class''; exit 2 }', ' if ($null -eq (Get-Task $Class)) { Write-Host "strblk-service: ''$(Get-TaskName $Class)'' is not registered"; exit 1 }', ' Stop-ScheduledTask -TaskName (Get-TaskName $Class) -ErrorAction SilentlyContinue', ' # Stop-ScheduledTask ends the ACTION - the supervisor - and Task Scheduler does not always', ' # reach a grandchild. The node is a child of cmd.exe which is a child of powershell.exe, so', ' # the tree is walked explicitly. taskkill /T is what scripts/live-world.mjs uses for the same', ' # reason: a node left alive holds its Cerberus lease and REFUSES the next start.', ' $stamp = ''strblk-supervise.ps1''', ' $procs = Get-CimInstance Win32_Process -Filter "Name=''powershell.exe''" | Where-Object { $_.CommandLine -like "*$stamp*" -and $_.CommandLine -like "*strblk-$Class*" }', ' foreach ($p in $procs) {', ' Write-Host (" taskkill /PID {0} /T /F" -f $p.ProcessId)', ' & taskkill /PID $p.ProcessId /T /F | Out-Null', ' }', ' Write-Host ("stopped ''{0}''" -f (Get-TaskName $Class))', ' exit 0', ' }', ' ''remove'' {', ' if ($Class -eq '''') { Write-Host ''strblk-service: remove needs -Class''; exit 2 }', ' if ($null -eq (Get-Task $Class)) { Write-Host "strblk-service: ''$(Get-TaskName $Class)'' is not registered"; exit 0 }', ' Stop-ScheduledTask -TaskName (Get-TaskName $Class) -ErrorAction SilentlyContinue', ' Unregister-ScheduledTask -TaskName (Get-TaskName $Class) -Confirm:$false', ' Write-Host ("removed ''{0}''. The data directory and the keys were NOT touched." -f (Get-TaskName $Class))', ' exit 0', ' }', '}' ) Set-Content -Path $ServiceTool -Value $serviceLines -Encoding utf8 Ok "wrote $ServiceTool" # A failure here does NOT fail the install. The node is installed, configured and startable; # what is missing is the thing that starts it again, and discarding a working install over # that would be the wrong trade. So this warns, says exactly what to do, and leaves the rest. $serviceClass = if ($Class -ne '') { $Class } else { 'quasar' } if ($Class -eq '') { Warn 'no -Class was given, so the service is registered under the quasar name - which is' Note ' the class the node itself defaults to (planNode). Pass -Class to be' Note ' explicit; one class is one service and one data directory.' } try { $svcArgs = @('install', '-Class', $serviceClass, '-Runner', $Runner, '-Supervisor', $Supervisor, '-LogFile', $NodeLog) & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $ServiceTool @svcArgs if ($LASTEXITCODE -ne 0) { throw "strblk-service.ps1 exited $LASTEXITCODE" } Ok "registered the service '$TaskName'" Note ' strblk-service.ps1 status what is registered, and its last result' Note ' strblk-service.ps1 stop -Class stops the supervisor and the node' Note " $NodeLog the node's own output" Note (' ' + (Join-Path (Split-Path -Parent $Runner) ('strblk-' + $serviceClass + '.supervisor.log')) + ' every restart, and why') } catch { Warn "the service was NOT registered: $($_.Exception.Message)" Note ' MEASURED on 2026-09-08: Register-ScheduledTask returns "Access is' Note ' denied" (HRESULT 0x80070005) from an unelevated prompt on Windows 11' Note ' where policy restricts task creation. The install itself is complete.' Note ' Re-run from an elevated PowerShell - which is also the run that gets' Note ' you a boot service rather than a logon one - or start the node with:' Note " powershell -File $Supervisor -Runner $Runner" } } 'none' { Note 'no service manager wired. Run it with:' Note " $Runner" Warn 'that is a FOREGROUND process and it is not a service. Nothing restarts it, nothing' Note ' records why it stopped, and nothing outside it knows it is gone. An' Note ' earlier deployment ran a block generator this way, under nohup; it died' Note ' and block production stopped with no signal at all.' Note ' -Service task registers the real thing: a Scheduled Task whose action' Note ' is a supervisor with Restart=always and a burst limiter.' } } # --------------------------------------------------------------------------------------------- # 10. Start # --------------------------------------------------------------------------------------------- Step 'start' $logFile = Join-Path $Prefix "strblk-$Network.log" if ($NoStart) { Note "not starting (-NoStart). $Runner when you are ready." } elseif ($DryRun) { Note 'would start the node and wait for its endpoints to answer' } elseif ($Channel -eq 'docker') { # Asked before it is told. docker writes "No such container" to STDERR when rm is handed a # name that does not exist, and with $ErrorActionPreference = 'Stop' a native command's stderr # becomes a TERMINATING error - MEASURED twice: the first docker-channel run died here on a # container it had never created, and redirecting the stream did not help, because the # redirection turns the line into an ErrorRecord that the preference still catches. ps -aq # with no match prints nothing, writes no stderr and exits 0, so there is nothing to swallow. $existing = (Invoke-Native { docker ps -aq --filter "name=^$Container$" }) -join '' if ($existing -ne '') { Invoke-Native { docker rm -f $Container } | Out-Null } # The endpoints bind loopback INSIDE the container and a non-loopback bind is refused without a # TLS statement, so publishing these ports to the host would forward to nothing. Verification # below goes through docker exec for that reason. $dockerArgs = @('run','-d','--name',$Container,'-v',"$($Dir):/data") # Not $dockerEnvFile: PowerShell names are case-insensitive, so that WAS $DockerEnvFile - the # persistent file the launcher reads - reassigned here to a temp path and deleted by that name. $startEnvFile = $null $dockerEnvLines = @() if ($Seal -ne 'none') { $dockerEnvLines += ($KeyEnv + '=' + $Passphrase) } # The console secret goes in whether or not the keystore is sealed: an unsealed keystore is a # key theft and an open console is a live operator session, and neither implies the other. if (-not [string]::IsNullOrEmpty($DashSecret)) { $dockerEnvLines += ($DashSecretEnv + '=' + $DashSecret) } if ($dockerEnvLines.Count -gt 0) { # --env-file, NOT -e. The passphrase used to be an argument to docker run, which put it in # this host's process list for the life of the call and in the PowerShell history of whoever # ran it. The file is written with no BOM - docker's env-file parser is byte-oriented and a # UTF-8 BOM ends up as part of the first variable NAME - and then narrowed to this account. $startEnvFile = Join-Path ([System.IO.Path]::GetTempPath()) ("brokkr-docker-env-" + [guid]::NewGuid().ToString('N')) # ACL'd to this account and checked BEFORE the secrets are written: see New-PrivateFile. It was # written first and narrowed after, with the ACE named by account name. New-PrivateFile $startEnvFile # Joined with [char]10 rather than with an escaped newline: this file is generated from a # JavaScript template literal and a backtick in it would end the literal. [System.IO.File]::WriteAllText($startEnvFile, (($dockerEnvLines -join [string][char]10) + [char]10), (New-Object System.Text.UTF8Encoding($false))) $dockerArgs += @('--env-file', $startEnvFile) Warn 'MEASURED, 2026-09-19, docker 27.5.1: --env-file keeps these secrets off this host''s' Note ' process list and out of your shell history. It does NOT keep them out of' Note ' "docker inspect". A container''s environment is part of its config' Note ' whichever flag put it there, and' Note ' docker inspect --format "{{json .Config.Env}}" printed the value back' Note ' verbatim in the test that produced this sentence. It will keep doing so' Note ' for as long as the container exists. So this run closes the process-list' Note ' and history exposure and nothing else. Closing the inspect exposure needs' Note ' a node that reads its passphrase from a mounted file rather than from its' Note ' environment, or a secrets store; neither is this installer''s to choose.' } $dockerArgs += @($Image, 'node', '--dir', '/data') + (Get-NetworkFlags) + @('--block-interval', "$BlockInterval") try { Invoke-Argv 'docker' $dockerArgs -Capture | Out-Null } finally { # finally, so a docker run that throws still takes the passphrase off the disk with it. if ($startEnvFile -and (Test-Path -LiteralPath $startEnvFile)) { Remove-Item -LiteralPath $startEnvFile -Force } } Ok "container $Container started" } else { $env:BROKKR_LOG = $logFile Start-Process -FilePath $Runner -WindowStyle Hidden -RedirectStandardOutput $logFile -RedirectStandardError "$logFile.err" Ok "started, log $logFile" } if (-not $NoStart -and -not $DryRun) { $probePort = if ($Channel -eq 'docker') { $OpsPortDefault } else { $OpsPort } $waited = 0 while ($waited -lt 90) { if ((Get-HttpStatus "http://$($Loopback):$probePort/health") -eq 200) { break } Start-Sleep -Seconds 1 $waited++ } Note "waited $waited seconds for the operator endpoint" } # --------------------------------------------------------------------------------------------- # 11. Verify # --------------------------------------------------------------------------------------------- if ($DryRun) { Step 'verify' Note 'would run the six checks: identity pin, astrolabe /health, iris /health, the chain the' Note ' running node serves, gungnir, and peers' Say '' Say 'Dry run complete. Nothing was changed.' exit 0 } if ($NoStart) { Say '' Say 'Installed, not started. Verify after you start it:' Say " brokkr.ps1 -Network $Network -Prefix $Prefix -Verify" exit 0 } $verified = Invoke-Verification Step 'summary' Note "network $Network (chain id $RealmChainId, $RealmMode)" Note "data $Dir" Note "ops http://$($Loopback):$OpsPort/" Note "rpc http://$($Loopback):$RpcPort/rpc" Note "dashboard http://$($Loopback):$DashboardPort/" Note "re-verify brokkr.ps1 -Network $Network -Prefix $Prefix -Verify" Say '' if (-not $verified) { Say "VERIFICATION FAILED: $script:Failures failure(s), $script:Warnings warning(s). The node may" Say 'be running; it is not the node you asked for. Read the FAIL lines above.' exit 1 } Say "Installed and verified: $script:Failures failure(s), $script:Warnings warning(s)." exit 0