Add PowerShell installer with shared Windows installation safeguards

This commit is contained in:
Dandaedre 2026-11-10 13:42:29 +01:00
parent 8ba96390cc
commit d34fc8afdb
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
7 changed files with 166 additions and 21 deletions

2
Jenkinsfile vendored
View File

@ -83,7 +83,7 @@ pipeline {
stage('Archive artifacts') {
steps {
archiveArtifacts(
artifacts: 'dist/*.zip,dist/publish/cards/*,dist/publish/xml/*.xml,dist/publish/install.sh,dist/publish/manifest.json',
artifacts: 'dist/*.zip,dist/publish/cards/*,dist/publish/xml/*.xml,dist/publish/install.sh,dist/publish/install.ps1,dist/publish/manifest.json',
allowEmptyArchive: false,
fingerprint: true
)

View File

@ -381,8 +381,51 @@ in shells without `pipefail`, download before executing instead:
For local validation without touching a real Cockatrice installation:
`python3 -m unittest discover -s tests -v`. The generated installer lives at
`dist/publish/install.sh` after `python3 scripts/publish.py prepare`; edit
`scripts/install.py`, not the generated shell script. Native Windows installation
is not implemented.
`scripts/install.py`, not the generated shell script. Windows uses the same installer engine through `install.ps1` (see below).
## Windows installation (PowerShell)
Run from an interactive **non-Administrator** PowerShell console, with Cockatrice
closed. Requires Windows PowerShell 5.1+ (or PowerShell 7), Python 3.8+ accessible
as `py.exe`, `python.exe`, or `python3.exe`, and `curl.exe`. The script does not
install these dependencies or Cockatrice. Install and launch Cockatrice once first.
From this checkout:
```powershell
.\install.ps1
.\install.ps1 -DataDir 'C:\path\to\Cockatrice\data'
.\install.ps1 -Force
```
After CI publishes the new launcher, download and run it with this one-liner:
```powershell
$p = Join-Path $env:TEMP ([guid]::NewGuid().ToString() + '.ps1'); try { Invoke-WebRequest -UseBasicParsing 'https://assets.dandaedre.com/mtg/install.ps1' -OutFile $p -ErrorAction Stop; & $p } finally { if (Test-Path -LiteralPath $p) { Remove-Item -LiteralPath $p } }
```
Your PowerShell execution policy must permit running the downloaded script.
The installer does not change or bypass that policy. You may download and inspect
the script before running it instead. Use `-Help` to view launcher options.
Discovery checks `%LOCALAPPDATA%` and `%APPDATA%` for recognized
`Cockatrice\Cockatrice` and `Cockatrice` data folders. Multiple matches prompt for
selection; no match aborts explicitly. For portable installations, pass the actual
data folder with `-DataDir`. Configured `settings/paths.ini` customsets/pics paths
are respected. Missing destination folders require confirmation.
The shared Python engine displays destinations, stages downloads in a temporary
directory, validates sizes/SHA-256/content, and asks before replacing files. It
skips identical files unless `-Force` is used. Replaced files are backed up during
the operation and rolled back on failure; failed rollback preserves recovery
files and reports their location. Symlinks, junctions/reparse points, reserved
Windows filenames, and alternate data stream paths are rejected.
`install.ps1` in the repository loads `scripts/install.py`; publication embeds the
same Python source into `dist/publish/install.ps1` so the published file works
standalone. CI verifies and publishes both launchers with the same manifest.
Windows-specific runtime behavior still needs testing on a Windows machine;
Linux tests cover discovery, filename rejection, shared rollback and packaging.
## Mock deployment
@ -447,7 +490,7 @@ installer, rendering, and publication tests, renders reminder images and generat
XML from TOML, builds ZIPs, prepares
the public payload, and verifies every payload and ZIP
against the sources. It fingerprints and archives `dist/*.zip`,
`dist/publish/cards/*`, `dist/publish/xml/*.xml`, `dist/publish/install.sh`, and
`dist/publish/cards/*`, `dist/publish/xml/*.xml`, `dist/publish/install.sh`, `dist/publish/install.ps1`, and
`dist/publish/manifest.json` on every successful branch. The last two files are
published at `https://assets.dandaedre.com/mtg/install.sh` and
`https://assets.dandaedre.com/mtg/manifest.json`. The manifest is generated from the

44
install.ps1 Normal file
View File

@ -0,0 +1,44 @@
#requires -Version 5.1
<# Windows launcher for the shared, validated Cockatrice custom-set installer. #>
[CmdletBinding()]
param(
[string]$DataDir,
[switch]$Force,
[switch]$Help
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
if ($Help) {
Write-Host 'Usage: .\install.ps1 [-DataDir C:\path\to\Cockatrice\data] [-Force]'
Write-Host 'Requires Windows, Python 3.8+, curl.exe, and an interactive console. Close Cockatrice first.'
return
}
if ($env:OS -ne 'Windows_NT') { throw 'This launcher requires Windows; use install.sh on Linux/macOS.' }
# Publication replaces this marker with the installer, making the download standalone.
$EmbeddedPython = '__COCKATRICE_PYTHON_BASE64__'
$PythonExe = $null
$PythonPrefix = @()
foreach ($candidate in @('py.exe', 'python.exe', 'python3.exe')) {
$command = Get-Command $candidate -CommandType Application -ErrorAction SilentlyContinue
if ($null -eq $command) { continue }
$prefix = @()
if ($candidate -eq 'py.exe') { $prefix = @('-3') }
& $command.Source @prefix -c 'import sys; sys.exit(sys.version_info < (3, 8))' 2>$null
if ($LASTEXITCODE -eq 0) { $PythonExe = $command.Source; $PythonPrefix = $prefix; break }
}
if ($null -eq $PythonExe) { throw 'Python 3.8+ is required. Install Python, reopen PowerShell, and retry.' }
if ($null -eq (Get-Command curl.exe -CommandType Application -ErrorAction SilentlyContinue)) {
throw 'curl.exe is required; install it and retry. Nothing installed.'
}
$InstallerArgs = @()
if ($DataDir) { $InstallerArgs += @('--data-dir', $DataDir) }
if ($Force) { $InstallerArgs += '--force' }
if ($EmbeddedPython.StartsWith('__COCKATRICE_')) {
$SourceFile = Join-Path $PSScriptRoot 'scripts/install.py'
if (-not (Test-Path -LiteralPath $SourceFile -PathType Leaf)) { throw "Installer source missing: $SourceFile" }
& $PythonExe @PythonPrefix $SourceFile @InstallerArgs
} else {
# Use stdin for the embedded payload; prompts read the Windows console separately.
$EmbeddedPython | & $PythonExe @PythonPrefix -c "import base64,sys; exec(compile(base64.b64decode(sys.stdin.read()), 'install.py', 'exec'))" @InstallerArgs
}
if ($LASTEXITCODE -ne 0) { throw "Installer failed (exit $LASTEXITCODE). See the error and any recovery path above." }

View File

@ -1,13 +1,14 @@
#!/usr/bin/env python3
"""Conservative interactive installer, embedded into the published install.sh."""
"""Conservative interactive installer, embedded into the published shell and PowerShell launchers."""
import argparse
import configparser
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
from pathlib import Path, PurePosixPath, PureWindowsPath
import shutil
import signal
import stat
import subprocess
import sys
import tempfile
@ -24,6 +25,14 @@ def say(message):
def prompt(message):
try:
if sys.platform == 'win32':
with open('CONIN$', 'r') as reader, open('CONOUT$', 'w') as writer:
writer.write(message + ' ')
writer.flush()
answer = reader.readline()
if not answer:
raise ValueError('No answer received; installation cancelled.')
return answer.strip()
# Separate streams work on non-seekable terminals, unlike text mode r+.
with open('/dev/tty', 'r') as reader, open('/dev/tty', 'w') as writer:
writer.write(message + ' ')
@ -42,10 +51,10 @@ def confirm(message):
def safe_path(path):
if not path.is_absolute() or path == Path('/') or path.resolve() != path:
if not path.is_absolute() or path == Path(path.anchor) or path.resolve() != path:
raise ValueError(f'Unsafe path (must be absolute without symlinks or ..): {path}')
for part in (path, *path.parents):
if part.is_symlink():
if part.is_symlink() or (part.exists() and getattr(part.lstat(), 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT):
raise ValueError(f'Symlink paths are not supported: {part}')
if part != path and part.exists() and not part.is_dir():
raise ValueError(f'Parent path is not a directory: {part}')
@ -53,6 +62,14 @@ def safe_path(path):
def discover(home, environment):
if sys.platform == 'win32':
candidates = []
for variable in ('LOCALAPPDATA', 'APPDATA'):
if environment.get(variable):
base = Path(environment[variable])
candidates.extend([base / 'Cockatrice/Cockatrice', base / 'Cockatrice'])
return list(dict.fromkeys(path for path in candidates
if (path / 'cards.xml').is_file() or (path / 'settings').is_dir()))
data = Path(environment.get('XDG_DATA_HOME') or home / '.local/share')
candidates = [data / 'Cockatrice/Cockatrice', home / '.local/share/Cockatrice/Cockatrice',
home / '.var/app/io.cockatrice.Cockatrice/data/Cockatrice/Cockatrice',
@ -114,7 +131,7 @@ def select_install(home, environment, explicit=None):
def download(relative, target, limit):
url = BASE_URL + quote(relative, safe='/')
say(f'Downloading {url}\n temporary file: {target}')
command = ['curl', '--fail', '--show-error', '--silent', '--proto', '=https',
command = ['curl.exe' if sys.platform == 'win32' else 'curl', '--fail', '--show-error', '--silent', '--proto', '=https',
'--connect-timeout', '15', '--max-time', '180', '--max-filesize', str(limit),
'--output', str(target), url]
result = subprocess.run(command, check=False)
@ -157,6 +174,11 @@ def validate_manifest(data, destinations):
raise ValueError('Invalid download size')
if not isinstance(digest, str) or len(digest) != 64 or any(c not in '0123456789abcdef' for c in digest):
raise ValueError('Invalid SHA-256 digest')
if sys.platform == 'win32':
for component in dest.parts:
if (PureWindowsPath(component).is_reserved() or component.endswith((' ', '.'))
or any(c in component for c in '<>:"|?*')):
raise ValueError(f'Unsafe Windows filename: {component}')
target = destinations[dest.parts[0]].joinpath(*dest.parts[1:])
safe_path(target)
if target in seen or (target.exists() and not target.is_file()):
@ -197,7 +219,8 @@ def atomic_copy(source, target):
with source.open('rb') as incoming:
shutil.copyfileobj(incoming, stream)
stream.flush()
os.fchmod(stream.fileno(), 0o644)
if hasattr(os, 'fchmod'):
os.fchmod(stream.fileno(), 0o644)
os.fsync(stream.fileno())
if hashlib.sha256(temporary.read_bytes()).digest() != hashlib.sha256(source.read_bytes()).digest():
raise OSError(f'Copy verification failed before moving into place: {target}')
@ -270,11 +293,15 @@ def plan_updates(entries, force=False):
def run(args):
if sys.platform not in ('linux', 'darwin'):
raise ValueError('This installer supports Linux and macOS only.')
if os.geteuid() == 0:
if sys.platform not in ('linux', 'darwin', 'win32'):
raise ValueError('This installer supports Linux, macOS and Windows only.')
if sys.platform == 'win32':
import ctypes
if ctypes.windll.shell32.IsUserAnAdmin():
raise ValueError('Run PowerShell as your normal user, not as Administrator.')
elif os.geteuid() == 0:
raise ValueError('Run as your normal user, without sudo/root, to avoid installing into the wrong home.')
if not shutil.which('curl'):
if not shutil.which('curl.exe' if sys.platform == 'win32' else 'curl'):
raise ValueError('curl is required. Install curl and retry; nothing installed.')
say('Cockatrice custom tokens installer. Close Cockatrice before proceeding.')
root, destinations = select_install(Path.home(), os.environ, args.data_dir)
@ -346,7 +373,7 @@ def main():
def interrupted(number, frame):
raise KeyboardInterrupt(f'Interrupted by signal {number}')
for number in (signal.SIGTERM, signal.SIGHUP):
for number in (signal.SIGTERM, getattr(signal, 'SIGHUP', signal.SIGTERM)):
signal.signal(number, interrupted)
try:
run(args)

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""Prepare and atomically publish static Cockatrice assets on a mounted web root."""
import argparse
import base64
import hashlib
import json
from urllib.parse import unquote, urlsplit
@ -98,7 +99,10 @@ def installer_files(entries):
" python3 -c 'import sys; sys.exit(sys.version_info < (3, 8))' || { echo 'ERROR: Python 3.8+ is required.' >&2; return 1; }\n"
" python3 - \"$@\" <<'COCKATRICE_INSTALLER_PYTHON'\n" + code +
"\nCOCKATRICE_INSTALLER_PYTHON\n}\ninstall_cockatrice_tokens \"$@\"\n")
return {Path('manifest.json'): manifest, Path('install.sh'): wrapper.encode()}
powershell = (ROOT / 'install.ps1').read_text().replace(
'__COCKATRICE_PYTHON_BASE64__', base64.b64encode(code.encode()).decode())
return {Path('manifest.json'): manifest, Path('install.sh'): wrapper.encode(),
Path('install.ps1'): powershell.encode()}
def prepare(sets, output):
@ -162,7 +166,7 @@ def payload_files(payload):
elif path.suffix.lower() not in IMAGE_SUFFIXES:
raise ValueError(f'Unsupported image: {path}')
entries[Path(category) / path.name] = path
for name in ('install.sh', 'manifest.json'):
for name in ('install.sh', 'install.ps1', 'manifest.json'):
path = payload / name
if path.is_symlink() or not path.is_file() or path.stat().st_size == 0:
raise ValueError(f'Missing or unsafe installer output: {path}')

View File

@ -33,6 +33,24 @@ class InstallerTests(unittest.TestCase):
def manifest(self, entry=None):
return json.dumps({'version': 1, 'files': [entry or self.entry]})
def test_windows_discovery_and_explicit_selection(self):
base = self.home / 'Local'
root = base / 'Cockatrice/Cockatrice'
(root / 'settings').mkdir(parents=True)
(root / 'customsets').mkdir()
(root / 'pics').mkdir()
with patch.object(installer.sys, 'platform', 'win32'):
self.assertEqual(installer.discover(self.home, {'LOCALAPPDATA': str(base)}), [root])
selected, destinations = installer.select_install(self.home, {}, root)
self.assertEqual(selected, root)
self.assertEqual(destinations['pics'], root / 'pics')
def test_windows_manifest_rejects_reserved_names_and_streams(self):
with patch.object(installer.sys, 'platform', 'win32'):
for name in ('CON.xml', 'NUL.xml', 'foo:bar.xml', 'foo?.xml', 'file.xml.'):
with self.subTest(name=name), self.assertRaises(ValueError):
installer.validate_manifest(self.manifest(dict(self.entry, destination='customsets/' + name)), self.destinations)
def test_default_install_detected(self):
with patch.object(installer, 'prompt', side_effect=AssertionError('unexpected prompt')):
root, destinations = installer.select_install(self.home, {})
@ -182,12 +200,12 @@ class InstallerTests(unittest.TestCase):
self.assertEqual((workspace / 'backup-0').read_bytes(), b'previous')
def test_unsupported_platform_aborts_before_prompts_or_downloads(self):
for platform in ('freebsd14', 'win32'):
for platform in ('freebsd14', 'unsupported'):
with self.subTest(platform=platform), \
patch.object(installer.sys, 'platform', platform), \
patch.object(installer, 'prompt') as prompt, \
patch.object(installer, 'download') as download:
with self.assertRaisesRegex(ValueError, 'Linux and macOS only'):
with self.assertRaisesRegex(ValueError, 'Linux, macOS and Windows only'):
installer.run(object())
prompt.assert_not_called()
download.assert_not_called()

View File

@ -1,4 +1,5 @@
import importlib.util
import base64
import json
import os
import subprocess
@ -47,7 +48,7 @@ class PublicationTests(unittest.TestCase):
publish.publish(self.payload, self.mount)
(self.payload / 'cards/card.png').write_bytes(b'updated image')
publish.publish(self.payload, self.mount)
self.assertEqual(len(replaced), 8)
self.assertEqual(len(replaced), 10)
self.assertEqual((self.mount / 'mtg/cards/card.png').read_bytes(), b'updated image')
self.assertEqual((self.mount / 'mtg/xml/tokens.xml').read_bytes(), XML)
self.assertEqual((self.mount / 'unrelated.txt').read_text(), 'keep')
@ -108,6 +109,14 @@ class PublicationTests(unittest.TestCase):
self.assertEqual(len({item['destination'] for item in images}), 2)
self.assertEqual(images[0]['destination'], 'pics/TKR/Command Zone_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa.png')
def test_powershell_embeds_shared_installer(self):
self.prepare()
script = (self.payload / 'install.ps1').read_text()
self.assertNotIn('__COCKATRICE_PYTHON_BASE64__', script)
encoded = script.split("$EmbeddedPython = '", 1)[1].split("'", 1)[0]
self.assertEqual(base64.b64decode(encoded).decode(), (publish.ROOT / 'scripts/install.py').read_text())
self.assertIn(Path('install.ps1'), publish.payload_files(self.payload))
def test_piped_installer_aborts_without_terminal_before_downloads(self):
self.prepare()
home = self.root / 'home'
@ -121,7 +130,7 @@ class PublicationTests(unittest.TestCase):
# Platform/root guards can reject before the terminal check on CI workers.
self.assertTrue(any(message in result.stderr for message in (
'terminal required', 'without sudo/root',
'This installer supports Linux and macOS only.')), result.stderr)
'This installer supports Linux, macOS and Windows only.')), result.stderr)
self.assertEqual(list((data / 'customsets').iterdir()), [])
self.assertNotIn('Downloading', result.stdout)