diff --git a/AGENTS.md b/AGENTS.md index b4c4599..4abdc35 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,7 +54,7 @@ This repo builds the Grill CLI and project setup tooling. The generated map-proj ## Test Commands -Use `HotReloadTests` for Grill's hot-run and reload transaction. For automated Warcraft III engine tests, use the `wc3-e2e-harness` sibling and follow its `docs/AgentQuickstart.md` for launch, loading-screen input and cleanup. +Use `HotReloadTests` for Grill's hot-run and reload transaction. Run the full WurstSetup suite before publishing: diff --git a/src/main/kotlin/file/BattleNetSignIn.kt b/src/main/kotlin/file/BattleNetSignIn.kt index 4e21ca8..a8b143a 100644 --- a/src/main/kotlin/file/BattleNetSignIn.kt +++ b/src/main/kotlin/file/BattleNetSignIn.kt @@ -1,5 +1,6 @@ package file +import global.Log import java.io.IOException import java.net.BindException import java.net.InetAddress @@ -11,8 +12,11 @@ import java.nio.file.Path import java.nio.file.Paths import java.security.MessageDigest import java.util.Locale +import java.util.UUID import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException /** * Renews the sign-in that Warcraft III 3.x uses for `-editor` launches, from the Battle.net desktop app. @@ -23,11 +27,20 @@ import java.util.concurrent.TimeUnit * not reach it: a client the app starts with `-loadfile` shows the login panel too. * * Just before the app starts the game it writes a one-time `WEB_TOKEN` (`...\Battle.net\Launch Options\W3`). Stored - * as `EDITOR_TOKEN`, that token signs the next `-editor` client in. [renew] asks the app to start the game, closes - * that client before it spends the token, and stores the token; the map is then launched as before. + * as `EDITOR_TOKEN`, that token signs the next `-editor` client in. [renew] runs [TOKEN_SCRIPT], which asks the app + * to start the game, closes that client before it spends the token, and stores the token; the map is then launched as + * before. * - * WurstScript's Run Map (`BattleNetSignIn`) and the wc3-e2e-harness (`docs/BattleNetSignIn.md`) do the same, and all - * hold the same localhost port as a lock from the renewal until the launched client has signed in. + * The app, the script and the map's client hand the sign-in to each other through `HKCU`, so all three must see the + * same registry. A process started from a packaged (MSIX) app, such as the Claude desktop app or an editor started from + * inside one, reads and writes `HKCU` through the package's private copy, and so does everything it starts. The script + * and the client therefore start through WMI, in the user's own registry view ([OutsideStart]), whatever view grill + * has. A Battle.net that was itself started from inside such an app writes its token where nothing else reads it; the + * script then sees the app start the game but no new token, and the user is told to start Battle.net from the Start + * menu. + * + * WurstScript's Run Map (`BattleNetSignIn`) does the same, and every tool that renews this sign-in holds the same + * localhost port as a lock from the renewal until the launched client has signed in. */ /** What [Wc3MapRunner] needs from the Battle.net app; replaced in tests. */ internal interface BattleNetApp { @@ -48,9 +61,10 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri /** The lock, held until the launched client has signed in; see [awaitSignIn]. */ class Renewal internal constructor( private val gate: ServerSocket, - private val token: String, - private val currentToken: () -> String? = { readBinary(GAME_KEY, "EDITOR_TOKEN") }, - private val pollMillis: Long = 500, + /** Whether the launched client has replaced the renewed `EDITOR_TOKEN` yet; throws when that cannot be told. */ + private val signedIn: () -> Boolean, + private val pollMillis: Long = 250, + private val onClose: () -> Unit = {}, ) : AutoCloseable { /** * Blocks until the launched client replaces `EDITOR_TOKEN`, which it does as it signs in (about ten seconds after @@ -61,7 +75,7 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SIGN_IN_TIMEOUT_SECONDS) try { while (System.nanoTime() < deadline) { - if (currentToken() != token) return true + if (signedIn()) return true Thread.sleep(pollMillis) } return false @@ -75,9 +89,69 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri gate.close() } catch (_: IOException) { } + onClose() + } + } + + /** + * [SIGNIN_SCRIPT] running in the user's own registry view, where the client replaces `EDITOR_TOKEN` as it signs in. + * Read from grill's own view, the token may never change: a packaged app's private copy keeps the old one. + */ + internal class SignInWatcher(private val process: ProcessHandle?, private val output: Path) { + /** True once the client has signed in; throws once the watcher has ended without seeing it. */ + fun signedIn(): Boolean { + val alive = process?.isAlive == true + // Read after the check, so a watcher that saw the sign-in and ended in between is not missed. + val lines = parseTokenScriptOutput(completeLines(readOutput(output))).lines + if ("signed-in" in lines) return true + if ("timeout" in lines || !alive) throw IOException("the sign-in watcher ended (${lines.lastOrNull() ?: "no output"})") + return false + } + + fun ready(): Boolean = "ready" in parseTokenScriptOutput(completeLines(readOutput(output))).lines + + fun stop() { + process?.destroyForcibly() + try { + process?.onExit()?.get(OUTPUT_RELEASE_SECONDS, TimeUnit.SECONDS) + } catch (_: Exception) { + } + try { + Files.deleteIfExists(output) + } catch (_: IOException) { + output.toFile().deleteOnExit() + } } } + /** + * How [Renewal] tells that the launched client has signed in: from [SignInWatcher] started outside grill's registry + * view, or, if that cannot start, by reading `EDITOR_TOKEN` from here. Called after the renewal and before the + * launch, so the token seen as the starting point is the renewed one. + */ + private fun signInCheck(gate: ServerSocket): Renewal { + try { + val output = tempDir().resolve("grill-battlenet-signin-${UUID.randomUUID()}.log") + val command = listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", + "& ${powerShellQuote(scriptCopy(SIGNIN_SCRIPT, tempDir()).toString())}" + + " -TimeoutSeconds ${SIGN_IN_TIMEOUT_SECONDS + 10} *> ${powerShellQuote(output.toString())}") + val pid = OutsideStart.startOrHere(command, null, OutsideStart.Show.HIDDEN) + val watcher = SignInWatcher(ProcessHandle.of(pid).orElse(null), output) + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SIGNIN_READY_SECONDS) + while (!watcher.ready() && System.nanoTime() < deadline) Thread.sleep(50) + if (watcher.ready()) return Renewal(gate, watcher::signedIn, onClose = watcher::stop) + watcher.stop() + } catch (e: IOException) { + Log.println("Watching the Warcraft III sign-in from grill instead: ${e.message}") + } + val token = try { + readBinary(GAME_KEY, "EDITOR_TOKEN") + } catch (_: IOException) { + null + } + return Renewal(gate, { readBinary(GAME_KEY, "EDITOR_TOKEN") != token }) + } + override fun isRunning(): Boolean = ProcessHandle.allProcesses().anyMatch { named(command(it), LAUNCHER) } override fun renew(onWait: () -> Unit): Renewal = renew(GATE_WAIT_SECONDS, onWait) @@ -89,72 +163,63 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri fun renew(gateWaitSeconds: Long, onWait: () -> Unit = {}): Renewal { val gate = acquireGate(gateWaitSeconds, onWait) try { - return Renewal(gate, renewLocked()) + renewLocked() + return signInCheck(gate) } catch (e: Throwable) { gate.close() throw e } } - private fun renewLocked(): String { + private fun renewLocked() { if (!isRunning()) throw IOException("Battle.net is not running.") - val seen = HashSet() - for (game in games()) { - if (startedByLauncher(game)) { - throw IOException("Close the Warcraft III client started from Battle.net, then run the map again.") - } - seen.add(game.pid()) - } - val before = readBinary(LAUNCH_KEY, "WEB_TOKEN") + if (games().any { startedByLauncher(it) }) throw IOException(APP_GAME_RUNNING) + val script = scriptCopy(TOKEN_SCRIPT, tempDir()) // Asked to start the game, the app shows its window in front; the watcher minimizes it as soon as it appears // and brings the map's client forward once that has a window. watchLauncherWindow() - val start = System.nanoTime() - var askedAt = Long.MIN_VALUE - var token: String? = null - var tokenAt = 0L - var closed = 0 - while (System.nanoTime() - start < TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS)) { - if (token == null && (askedAt == Long.MIN_VALUE - || System.nanoTime() - askedAt >= TimeUnit.SECONDS.toNanos(ASK_AGAIN_SECONDS))) { - askedAt = System.nanoTime() - // An app that is still starting ignores the command, so it is repeated while waiting. - ProcessBuilder(launcher.toString(), "--exec=launch W3") - .redirectOutput(ProcessBuilder.Redirect.DISCARD) - .redirectError(ProcessBuilder.Redirect.DISCARD) - .start() - } - for (game in games()) { - if (!seen.add(game.pid()) || !startedByLauncher(game)) continue - game.destroyForcibly() - closed++ + val result = runTokenScript(script) + problem(result)?.let { throw IOException(it) } + } + + /** + * Runs [TOKEN_SCRIPT] hidden in the user's own registry view, where the app writes `WEB_TOKEN` and the client reads + * `EDITOR_TOKEN`, whatever view grill has. Only if WMI cannot start it does it run from here. + */ + private fun runTokenScript(script: Path): TokenScriptResult { + val output = tempDir().resolve("grill-battlenet-renewal-${UUID.randomUUID()}.log") + try { + val pid = OutsideStart.startOrHere(tokenScriptCommand(script, launcher, TIMEOUT_SECONDS, output), null, + OutsideStart.Show.HIDDEN) + val handle = ProcessHandle.of(pid).orElse(null) + val result = awaitTokenScript(handle, output, TIMEOUT_SECONDS + SCRIPT_EXIT_GRACE_SECONDS) + // The script ends right after its result line; let it close the output file before that is removed. + try { + handle?.onExit()?.get(OUTPUT_RELEASE_SECONDS, TimeUnit.SECONDS) + } catch (_: ExecutionException) { + } catch (_: TimeoutException) { + // still running: the delete below falls back to deleteOnExit } - if (token == null) { - val now = readBinary(LAUNCH_KEY, "WEB_TOKEN") - if (now != null && now != before) { - token = now - tokenAt = System.nanoTime() - } + return result + } finally { + try { + Files.deleteIfExists(output) + } catch (_: IOException) { + output.toFile().deleteOnExit() } - // The app writes the token, then starts the game: wait briefly for that game so it is closed. - if (token != null && (closed > 0 - || System.nanoTime() - tokenAt >= TimeUnit.SECONDS.toNanos(GAME_AFTER_TOKEN_SECONDS))) break - Thread.sleep(50) - } - if (token == null) { - throw IOException("Battle.net did not start Warcraft III. Check that it is signed in and the game is ready to play.") } - writeBinary(GAME_KEY, "EDITOR_TOKEN", token) - return token } + /** What [TOKEN_SCRIPT] printed: its outcome, null until its `result` line, and every line. */ + data class TokenScriptResult(val outcome: String?, val lines: List) + private fun acquireGate(waitSeconds: Long, onWait: () -> Unit): ServerSocket { val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(waitSeconds) var waiting = false while (true) { val socket = ServerSocket() try { - // 127.0.0.1 exactly, as the harness binds it; the loopback name could resolve to ::1. + // 127.0.0.1 exactly, as every holder binds it; the loopback name could resolve to ::1. socket.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), gatePort(config))) return socket } catch (e: BindException) { @@ -175,14 +240,16 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri } companion object { - const val LAUNCH_KEY = "HKCU\\Software\\Blizzard Entertainment\\Battle.net\\Launch Options\\W3" const val GAME_KEY = "HKCU\\Software\\Blizzard Entertainment\\Warcraft III" private const val LAUNCHER = "Battle.net.exe" private const val GAME = "Warcraft III.exe" private const val TIMEOUT_SECONDS = 90L - private const val ASK_AGAIN_SECONDS = 25L - private const val GAME_AFTER_TOKEN_SECONDS = 10L + /** How long past its own timeout the renewal script may take to start and to write its result. */ + private const val SCRIPT_EXIT_GRACE_SECONDS = 30L + /** How long the renewal script may take to exit, and close its output file, after writing its result. */ + private const val OUTPUT_RELEASE_SECONDS = 5L const val SIGN_IN_TIMEOUT_SECONDS = 120L + const val APP_GAME_RUNNING = "Close the Warcraft III client started from Battle.net, then run the map again." /** Another holder renews (up to [TIMEOUT_SECONDS]) and waits for its client's sign-in; outwait both. */ const val GATE_WAIT_SECONDS = TIMEOUT_SECONDS + SIGN_IN_TIMEOUT_SECONDS + 30 @@ -190,28 +257,116 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri internal fun forTest(config: Path): BattleNetSignIn = BattleNetSignIn(config, Paths.get(LAUNCHER)) private val REG_BINARY = Regex("""^\s*(\S+)\s+REG_BINARY\s+([0-9A-Fa-f]*)\s*$""", RegexOption.MULTILINE) - /** A copy of the wc3-e2e-harness `node/src/runner/battlenet-window.ps1`; keep the two equal. */ + /** The renewal script, run in the user's own registry view. */ + const val TOKEN_SCRIPT = "battlenet-token.ps1" + /** The sign-in watcher, run in the user's own registry view ([SignInWatcher]). */ + const val SIGNIN_SCRIPT = "battlenet-signin.ps1" + /** How long the sign-in watcher may take to start and read the renewed token before the game is launched. */ + private const val SIGNIN_READY_SECONDS = 15L + /** The watcher that keeps the app's window out of sight during the renewal. */ const val WINDOW_SCRIPT = "battlenet-window.ps1" /** The watcher's limit without a client: every request the renewal may send, then a launch and a slow sign-in. */ const val WINDOW_WATCH_SECONDS = TIMEOUT_SECONDS + 150 private const val WINDOW_READY_SECONDS = 3L + private val RESULT = Regex("""result (\S+)""") - /** The PowerShell command that runs [WINDOW_SCRIPT] with [arguments]; null if the script is missing. */ - fun windowWatcherCommand(arguments: List, dir: Path = Paths.get(System.getProperty("java.io.tmpdir"))): List? { - val script = BattleNetSignIn::class.java.classLoader.getResourceAsStream(WINDOW_SCRIPT)?.use { it.readBytes() } - ?: return null - // A file, not -EncodedCommand: encoded, the script is close to Windows' 32,767-character command line limit. - // Named by content, so a grill of another version never runs this one's copy. - val hash = MessageDigest.getInstance("SHA-256").digest(script).take(6).joinToString("") { "%02x".format(it) } - val file = dir.resolve("grill-battlenet-window-$hash.ps1") - try { - if (!Files.isRegularFile(file) || !Files.readAllBytes(file).contentEquals(script)) Files.write(file, script) + private fun tempDir(): Path = Paths.get(System.getProperty("java.io.tmpdir")) + + /** + * A copy of the resource [script] in [dir], named by its content, so a grill of another version never runs this + * one's copy. A file, not -EncodedCommand: encoded, the window watcher is close to Windows' 32,767-character + * command line limit. + */ + fun scriptCopy(script: String, dir: Path): Path { + val content = BattleNetSignIn::class.java.classLoader.getResourceAsStream(script)?.use { it.readBytes() } + ?: throw IOException("$script is missing from grill") + val hash = MessageDigest.getInstance("SHA-256").digest(content).take(6).joinToString("") { "%02x".format(it) } + val file = dir.resolve("grill-${script.removeSuffix(".ps1")}-$hash.ps1") + if (!Files.isRegularFile(file) || !Files.readAllBytes(file).contentEquals(content)) Files.write(file, content) + return file + } + + /** The PowerShell command that runs [WINDOW_SCRIPT] with [arguments]; null if the script cannot be provided. */ + fun windowWatcherCommand(arguments: List, dir: Path = tempDir()): List? { + val file = try { + scriptCopy(WINDOW_SCRIPT, dir) } catch (_: IOException) { return null } return listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file.toString()) + arguments } + /** A PowerShell single-quoted string literal. PowerShell also reads the typographic single quotes as quotes. */ + fun powerShellQuote(text: String): String = "'" + text.replace(Regex("['‘’‚‛]")) { it.value + it.value } + "'" + + /** + * The command that runs [script] and redirects everything it prints to [output]. Started outside, the script's + * output cannot come back through a pipe, so it goes to a file. + */ + fun tokenScriptCommand(script: Path, launcher: Path, timeoutSeconds: Long, output: Path): List = + listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", + "& ${powerShellQuote(script.toString())} -BattleNetExe ${powerShellQuote(launcher.toString())}" + + " -TimeoutSeconds $timeoutSeconds *> ${powerShellQuote(output.toString())}") + + fun parseTokenScriptOutput(output: String): TokenScriptResult { + val lines = output.lines().map { it.trim() }.filter { it.isNotEmpty() } + return TokenScriptResult(lines.firstNotNullOfOrNull { RESULT.matchEntire(it)?.groupValues?.get(1) }, lines) + } + + /** + * The complete lines of a script's redirected output: Windows PowerShell writes UTF-16 with a byte order mark, + * and a line still being written could read as a different result. + */ + fun completeLines(output: ByteArray): String { + val utf16 = output.size >= 2 && output[0] == 0xFF.toByte() && output[1] == 0xFE.toByte() + val text = if (utf16) String(output, 2, output.size - 2, Charsets.UTF_16LE) else String(output, Charsets.UTF_8) + return text.substring(0, text.lastIndexOf('\n') + 1) + } + + /** The message for the user when the renewal did not succeed; null when it did. */ + fun problem(result: TokenScriptResult): String? = when (result.outcome) { + "refreshed" -> null + "no-token" -> "Battle.net did not start Warcraft III. Check that it is signed in and the game is ready to play." + "app-game-running" -> APP_GAME_RUNNING + "token-not-visible" -> "Battle.net started Warcraft III, but wrote its sign-in where other programs cannot" + + " read it, probably because Battle.net was started from a packaged app (such as the Claude desktop app)." + + " Quit Battle.net from its tray icon and start it from the Start menu." + else -> "The Battle.net sign-in renewal failed: " + + (if (result.lines.isEmpty()) "it printed nothing" else result.lines.takeLast(3).joinToString(" | ")) + "." + } + + /** + * Waits for the script's result line, or for the script to end, and ends the script if it outlives + * [timeoutSeconds] or this thread is interrupted. + * + * @param script null when it has ended already + */ + fun awaitTokenScript(script: ProcessHandle?, output: Path, timeoutSeconds: Long, pollMillis: Long = 250): TokenScriptResult { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds) + var done = false + try { + while (true) { + // Read after the check, so a script that wrote its result and ended in between is not missed. + val running = script != null && script.isAlive + val result = parseTokenScriptOutput(completeLines(readOutput(output))) + if (result.outcome != null || !running) { + done = true + return result + } + if (System.nanoTime() >= deadline) return TokenScriptResult(null, result.lines + "the renewal script did not finish") + Thread.sleep(pollMillis) + } + } finally { + if (!done) script?.destroyForcibly() + } + } + + private fun readOutput(output: Path): ByteArray = try { + Files.readAllBytes(output) + } catch (_: IOException) { + ByteArray(0) // not created yet + } + /** * Starts the window watcher and waits until it has noted the windows already open (at most * [WINDOW_READY_SECONDS]). It then runs on its own: the app shows its window again as the map's client signs in, @@ -278,7 +433,7 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri .firstOrNull { it.groupValues[1].equals(value, ignoreCase = true) } ?.groupValues?.get(2)?.uppercase(Locale.ROOT) - /** The lock port the wc3-e2e-harness and WurstScript use for the same Battle.net profile. */ + /** The lock port every tool that renews this sign-in, WurstScript's Run Map among them, uses for a Battle.net profile. */ fun gatePort(config: Path): Int { val key = config.toAbsolutePath().normalize().toString().lowercase(Locale.ROOT) val hash = MessageDigest.getInstance("SHA-256").digest(key.toByteArray(Charsets.UTF_8)) @@ -300,15 +455,6 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri private fun readBinary(key: String, value: String): String? = parseBinary(readCommand("reg.exe", "query", key, "/v", value), value) - private fun writeBinary(key: String, value: String, hex: String) { - val process = ProcessBuilder("reg.exe", "add", key, "/v", value, "/t", "REG_BINARY", "/d", hex, "/f") - .redirectOutput(ProcessBuilder.Redirect.DISCARD).redirectError(ProcessBuilder.Redirect.DISCARD).start() - if (!process.waitFor(8, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly() - throw IOException("Could not store the Warcraft III sign-in.") - } - } - private fun readCommand(vararg command: String): List { val process = ProcessBuilder(*command).redirectError(ProcessBuilder.Redirect.DISCARD).start() if (!process.waitFor(8, TimeUnit.SECONDS)) { diff --git a/src/main/kotlin/file/OutsideStart.kt b/src/main/kotlin/file/OutsideStart.kt new file mode 100644 index 0000000..73f459a --- /dev/null +++ b/src/main/kotlin/file/OutsideStart.kt @@ -0,0 +1,112 @@ +package file + +import global.Log +import java.io.IOException +import java.nio.file.Path +import java.util.concurrent.CompletableFuture +import java.util.concurrent.TimeUnit + +/** + * Starts processes on Windows in the user's own registry view. + * + * A child process sees the registry its parent sees. Under a packaged (MSIX) app, such as the Claude desktop app or a + * VS Code started from a terminal inside it, that is the package's private copy of `HKCU`: what such a process writes + * there no other process reads, and once it has written a value it no longer reads the user's. Battle.net, the sign-in + * renewal and the game pass the sign-in between them through `HKCU` ([BattleNetSignIn]), so each of them started from + * inside such an app would keep it where the rest of the machine never sees it. A process created through WMI + * (`Win32_Process.Create`) starts in the user's own context instead, in the same session and on the same desktop. + */ +internal object OutsideStart { + /** The `SW_` value WMI passes to the new process's first window. */ + enum class Show(val value: Int) { HIDDEN(0), NORMAL(1), MINIMIZED(7) } + + private const val WMI_TIMEOUT_SECONDS = 30L + private val CREATED = Regex("""^created (\d+) (\d+)\s*$""", RegexOption.MULTILINE) + + // The command line, window and directory travel in the environment, so nothing in them needs PowerShell quoting. + private val CREATE_SCRIPT = listOf( + "\$ErrorActionPreference = 'Stop'", + "\$ProgressPreference = 'SilentlyContinue'", + "[Console]::OutputEncoding = [Text.Encoding]::UTF8", + "\$startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]\$env:GRILL_OUTSIDE_SHOW }", + "\$arguments = @{ CommandLine = \$env:GRILL_OUTSIDE_COMMAND; ProcessStartupInformation = \$startup }", + "if (\$env:GRILL_OUTSIDE_CWD) { \$arguments.CurrentDirectory = \$env:GRILL_OUTSIDE_CWD }", + "\$created = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments \$arguments", + "'created {0} {1}' -f \$created.ReturnValue, \$created.ProcessId", + ).joinToString("; ") + + /** One argument quoted for a Windows command line, as CommandLineToArgvW and the C runtime split it. */ + fun quoteWindowsArg(arg: String): String { + if (arg.isNotEmpty() && arg.none { it == '"' || it.isWhitespace() }) return arg + val quoted = StringBuilder("\"") + var backslashes = 0 + for (c in arg) { + if (c == '\\') { + backslashes++ + continue + } + quoted.append("\\".repeat(if (c == '"') backslashes * 2 + 1 else backslashes)).append(c) + backslashes = 0 + } + return quoted.append("\\".repeat(backslashes * 2)).append('"').toString() + } + + fun commandLine(command: List): String = command.joinToString(" ") { quoteWindowsArg(it) } + + /** + * Starts [command] through WMI, in the user's own registry view, and returns its pid. Throws when WMI cannot + * create it. + * + * @param directory the new process's working directory; null for WMI's default + */ + fun start(command: List, directory: Path?, show: Show): Long { + val builder = ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive", "-Command", CREATE_SCRIPT) + .redirectErrorStream(true) + builder.environment()["GRILL_OUTSIDE_COMMAND"] = commandLine(command) + builder.environment()["GRILL_OUTSIDE_SHOW"] = show.value.toString() + builder.environment()["GRILL_OUTSIDE_CWD"] = directory?.toString() ?: "" + val process = builder.start() + val output = try { + process.outputStream.close() + // Read while it runs: an error record could fill the pipe and stall PowerShell until the timeout. + val read = CompletableFuture.supplyAsync { + try { + process.inputStream.use { String(it.readAllBytes(), Charsets.UTF_8) } + } catch (_: IOException) { + "" + } + } + if (!process.waitFor(WMI_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw IOException("WMI did not answer within $WMI_TIMEOUT_SECONDS s") + } + read.get(5, TimeUnit.SECONDS) + } finally { + process.destroyForcibly() + } + val name = Path.of(command[0]).fileName.toString() + val created = CREATED.find(output) + ?: throw IOException("WMI could not start $name: ${output.trim().lineSequence().firstOrNull() ?: "no answer"}") + if (created.groupValues[1] != "0") { + throw IOException("WMI could not start $name (Win32_Process.Create returned ${created.groupValues[1]})") + } + return created.groupValues[2].toLong() + } + + /** + * [start] if WMI can, else a direct start from this process (whose registry view the process then shares). + * Returns the pid. + */ + fun startOrHere(command: List, directory: Path?, show: Show): Long { + return try { + start(command, directory, show) + } catch (e: Exception) { + if (e is InterruptedException) throw e + Log.println("Starting ${Path.of(command[0]).fileName} from grill instead: ${e.message}") + val builder = ProcessBuilder(command) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + if (directory != null) builder.directory(directory.toFile()) + builder.start().pid() + } + } +} diff --git a/src/main/kotlin/file/SetupApp.kt b/src/main/kotlin/file/SetupApp.kt index d2e520d..5376d0b 100644 --- a/src/main/kotlin/file/SetupApp.kt +++ b/src/main/kotlin/file/SetupApp.kt @@ -41,7 +41,7 @@ object SetupApp { get() = "Tests: $passed/$total passed" } - internal const val AGENTS_TEMPLATE_VERSION = "2026-11-06" + internal const val AGENTS_TEMPLATE_VERSION = "2026-11-17" private const val AGENTS_TEMPLATE_MARKER_PREFIX = "" private const val AGENTS_TEMPLATE_SOURCE_HINT = "WurstScript Warcraft III map project notes" diff --git a/src/main/kotlin/file/Wc3MapRunner.kt b/src/main/kotlin/file/Wc3MapRunner.kt index 5774e42..db5b221 100644 --- a/src/main/kotlin/file/Wc3MapRunner.kt +++ b/src/main/kotlin/file/Wc3MapRunner.kt @@ -99,11 +99,16 @@ internal object Wc3MapRunner { val command = launchCommand(client, launchMap) val renewal = renewSignIn(client, command, launchMode, report) try { - ProcessBuilder(command) - .directory(client.root.toFile()) - .redirectOutput(ProcessBuilder.Redirect.DISCARD) - .redirectError(ProcessBuilder.Redirect.DISCARD) - .start() + if (System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) { + // In the user's own registry view, where the sign-in is renewed, whatever view grill has. + OutsideStart.startOrHere(command, client.root, OutsideStart.Show.NORMAL) + } else { + ProcessBuilder(command) + .directory(client.root.toFile()) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start() + } } catch (e: Exception) { renewal?.close() throw e diff --git a/src/main/resources/battlenet-signin.ps1 b/src/main/resources/battlenet-signin.ps1 new file mode 100644 index 0000000..1170aa1 --- /dev/null +++ b/src/main/resources/battlenet-signin.ps1 @@ -0,0 +1,28 @@ +# Waits, in the registry view it runs in, until the launched client replaces EDITOR_TOKEN, which it does as it signs in. +# +# Prints "ready" once it has read the token the renewal stored, then "signed-in" when that token changes, or "timeout". +# Never prints a token. +param( + [int]$TimeoutSeconds = 120, + [string]$Key = "HKCU:\Software\Blizzard Entertainment\Warcraft III" +) +$ErrorActionPreference = "Stop" + +function Read-EditorToken { + $value = (Get-ItemProperty -Path $Key -Name EDITOR_TOKEN -ErrorAction SilentlyContinue).EDITOR_TOKEN + if ($value -is [byte[]]) { return [BitConverter]::ToString($value) } + return "" +} + +$before = Read-EditorToken +"ready" +$watch = [Diagnostics.Stopwatch]::StartNew() +while ($watch.Elapsed.TotalSeconds -lt $TimeoutSeconds) { + if ((Read-EditorToken) -ne $before) { + "signed-in" + exit 0 + } + Start-Sleep -Milliseconds 250 +} +"timeout" +exit 1 diff --git a/src/main/resources/battlenet-token.ps1 b/src/main/resources/battlenet-token.ps1 new file mode 100644 index 0000000..cb94093 --- /dev/null +++ b/src/main/resources/battlenet-token.ps1 @@ -0,0 +1,90 @@ +# Renews the session that -editor launches sign in with, from the Battle.net desktop app. +# +# The app signs Warcraft III in with a one-time WEB_TOKEN it writes just before it starts the game. A client given +# -editor signs in with EDITOR_TOKEN instead, which only the client itself renews (on each sign-in), so once it has +# lapsed every -editor launch stops at the login panel. This asks the app to start the game, closes that game the +# moment it appears - before it can spend the token - and stores the token as EDITOR_TOKEN. +# +# Prints one line per step and ends with "result "; never prints a token. +param( + [Parameter(Mandatory = $true)][string]$BattleNetExe, + [int]$TimeoutSeconds = 90, + [int]$AskAgainSeconds = 25 +) +$ErrorActionPreference = "Stop" +$launchKey = "HKCU:\Software\Blizzard Entertainment\Battle.net\Launch Options\W3" +$gameKey = "HKCU:\Software\Blizzard Entertainment\Warcraft III" + +function Read-WebToken { + $value = (Get-ItemProperty -Path $launchKey -Name WEB_TOKEN -ErrorAction SilentlyContinue).WEB_TOKEN + if ($value -is [byte[]]) { return $value } + return $null +} + +function Test-AppGame([int]$id) { + # A client the app started: its parent is a Battle.net.exe process. Anything else is someone else's client. + $process = Get-CimInstance Win32_Process -Filter "ProcessId=$id" -ErrorAction SilentlyContinue + if (-not $process) { return $false } + $parent = Get-Process -Id $process.ParentProcessId -ErrorAction SilentlyContinue + return [bool]($parent -and $parent.ProcessName -eq "Battle.net") +} + +function Get-GamePids { + @(Get-Process -Name "Warcraft III" -ErrorAction SilentlyContinue | ForEach-Object { $_.Id }) +} + +$before = Read-WebToken +$beforeHex = if ($before) { [BitConverter]::ToString($before) } else { "" } +$existing = Get-GamePids +# The app does not start a second client while its own is running, so it would never write a token. +if (@($existing | Where-Object { Test-AppGame $_ }).Count -gt 0) { + "result app-game-running" + exit 3 +} + +$watch = [Diagnostics.Stopwatch]::StartNew() +$askedAt = -1e9 +$token = $null +$tokenAt = 0 +$closed = 0 +while ($watch.Elapsed.TotalSeconds -lt $TimeoutSeconds) { + if (-not $token -and $watch.Elapsed.TotalSeconds - $askedAt -ge $AskAgainSeconds) { + $askedAt = $watch.Elapsed.TotalSeconds + Start-Process -FilePath $BattleNetExe -ArgumentList '--exec="launch W3"' + "asked {0:N1}" -f $askedAt + } + foreach ($id in Get-GamePids) { + if ($existing -contains $id) { continue } + $existing += $id + if (Test-AppGame $id) { + Stop-Process -Id $id -Force -ErrorAction SilentlyContinue + $closed++ + "closed {0} {1:N1}" -f $id, $watch.Elapsed.TotalSeconds + } + } + if (-not $token) { + $now = Read-WebToken + if ($now -and [BitConverter]::ToString($now) -ne $beforeHex) { + $token = $now + $tokenAt = $watch.Elapsed.TotalSeconds + "token {0:N1}" -f $tokenAt + } + } + # The app writes the token, then starts the game: wait briefly for that game so it is closed, not left running. + if ($token -and ($closed -gt 0 -or $watch.Elapsed.TotalSeconds - $tokenAt -ge 10)) { break } + Start-Sleep -Milliseconds 50 +} +if (-not $token -and $closed -gt 0) { + # The app started the game, so it wrote a token, but not where this script reads: the app keeps a private copy of + # the registry, as one started from a packaged (MSIX) app does. + "result token-not-visible" + exit 4 +} +if (-not $token) { + "result no-token" + exit 2 +} +if (-not (Test-Path $gameKey)) { New-Item -Path $gameKey -Force | Out-Null } +Set-ItemProperty -Path $gameKey -Name EDITOR_TOKEN -Value ([byte[]]$token) -Type Binary +"result refreshed" +exit 0 diff --git a/src/test/kotlin/BattleNetSignInTests.kt b/src/test/kotlin/BattleNetSignInTests.kt index 151dab5..7ab2aa0 100644 --- a/src/test/kotlin/BattleNetSignInTests.kt +++ b/src/test/kotlin/BattleNetSignInTests.kt @@ -1,6 +1,7 @@ import config.WurstProjectConfig import file.BattleNetApp import file.BattleNetSignIn +import file.OutsideStart import java.net.InetAddress import java.net.InetSocketAddress import java.net.ServerSocket @@ -37,12 +38,108 @@ class BattleNetSignInTests { } @Test - fun takesTheSameLockAsTheE2eHarnessAndWurstScript() { + fun takesTheSameLockAsWurstScript() { if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows paths") - // wc3-e2e-harness node/src/runner/battlenet.cjs: 33000 + sha256(lower-cased path) as uint32 BE % 10000 + // 33000 + sha256(lower-cased path) as uint32 BE % 10000, the port every tool that renews this sign-in binds Assert.assertEquals(BattleNetSignIn.gatePort(Paths.get("C:\\Users\\tester\\AppData\\Roaming\\Battle.net\\Battle.net.config")), 36941) } + @Test + fun theRenewalScriptShipsAndRunsWithItsOutputRedirectedToAFile() { + val dir = Files.createTempDirectory("grill renewal script") + val script = BattleNetSignIn.scriptCopy(BattleNetSignIn.TOKEN_SCRIPT, dir) + Assert.assertEquals(script.parent, dir) + val content = Files.readString(script) + Assert.assertTrue(content.contains("\"result token-not-visible\"")) + Assert.assertTrue(content.all { it.code < 128 }, "Windows PowerShell reads a .ps1 without BOM as ANSI") + Assert.assertEquals(BattleNetSignIn.scriptCopy(BattleNetSignIn.TOKEN_SCRIPT, dir), script, "a second call reuses the file") + + val command = BattleNetSignIn.tokenScriptCommand(Paths.get("C:\\it's here\\s.ps1"), + Paths.get("C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"), 90, Paths.get("C:\\tmp\\out.log")) + Assert.assertEquals(command.subList(0, 6), + listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command")) + Assert.assertEquals(command[6], "& 'C:\\it''s here\\s.ps1' -BattleNetExe 'C:\\Program Files (x86)\\Battle.net\\Battle.net.exe'" + + " -TimeoutSeconds 90 *> 'C:\\tmp\\out.log'") + Assert.assertEquals(BattleNetSignIn.powerShellQuote("O\u2019Neil"), "'O\u2019\u2019Neil'") + } + + private fun utf16(text: String) = byteArrayOf(0xFF.toByte(), 0xFE.toByte()) + text.toByteArray(Charsets.UTF_16LE) + + @Test + fun onlyCompleteLinesOfTheScriptsOutputCount() { + Assert.assertEquals(BattleNetSignIn.completeLines(utf16("asked 0.0\r\nresult refreshed\r\n")), "asked 0.0\r\nresult refreshed\r\n") + Assert.assertEquals(BattleNetSignIn.completeLines(utf16("asked 0.0\r\nresult refre")), "asked 0.0\r\n") + Assert.assertEquals(BattleNetSignIn.completeLines("asked 0.0\nresult no-token\n".toByteArray()), "asked 0.0\nresult no-token\n") + val parsed = BattleNetSignIn.parseTokenScriptOutput("asked 0.0\r\ntoken 0.5\r\nresult refreshed\r\n") + Assert.assertEquals(parsed.outcome, "refreshed") + Assert.assertEquals(parsed.lines, listOf("asked 0.0", "token 0.5", "result refreshed")) + Assert.assertNull(BattleNetSignIn.parseTokenScriptOutput("asked 0.0\r\n").outcome) + } + + @Test + fun aScriptThatHasEndedIsReadOnceMoreAndOneStillRunningIsWaitedFor() { + val output = Files.createTempFile("grill-renewal", ".log") + Files.write(output, utf16("asked 0.0\r\nresult app-game-running\r\n")) + Assert.assertEquals(BattleNetSignIn.awaitTokenScript(null, output, 5).outcome, "app-game-running") + Files.write(output, utf16("asked 0.0\r\n")) + val ended = BattleNetSignIn.awaitTokenScript(null, output, 5) + Assert.assertNull(ended.outcome) + Assert.assertEquals(ended.lines, listOf("asked 0.0")) + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) return + // A script still running without a result is ended at the timeout. + val script = ProcessBuilder("ping", "-n", "60", "127.0.0.1").redirectOutput(ProcessBuilder.Redirect.DISCARD).start() + val timedOut = BattleNetSignIn.awaitTokenScript(script.toHandle(), output, 0, pollMillis = 10) + Assert.assertNull(timedOut.outcome) + Assert.assertEquals(timedOut.lines.last(), "the renewal script did not finish") + Assert.assertTrue(script.waitFor(10, java.util.concurrent.TimeUnit.SECONDS), "the script was ended") + } + + @Test + fun everyRenewalOutcomeHasItsMessage() { + fun problem(outcome: String?, vararg lines: String) = + BattleNetSignIn.problem(BattleNetSignIn.TokenScriptResult(outcome, lines.toList())) + Assert.assertNull(problem("refreshed")) + Assert.assertTrue(problem("no-token")!!.startsWith("Battle.net did not start Warcraft III.")) + Assert.assertEquals(problem("app-game-running"), BattleNetSignIn.APP_GAME_RUNNING) + Assert.assertTrue(problem("token-not-visible")!!.contains("start it from the Start menu")) + Assert.assertEquals(problem(null), "The Battle.net sign-in renewal failed: it printed nothing.") + Assert.assertEquals(problem(null, "a", "b", "c", "d"), "The Battle.net sign-in renewal failed: b | c | d.") + } + + @Test + fun commandLineQuotingKeepsArgumentsWhole() { + Assert.assertEquals(OutsideStart.quoteWindowsArg("-editor"), "-editor") + Assert.assertEquals(OutsideStart.quoteWindowsArg(""), "\"\"") + Assert.assertEquals(OutsideStart.quoteWindowsArg("C:\\Program Files\\x.exe"), "\"C:\\Program Files\\x.exe\"") + Assert.assertEquals(OutsideStart.quoteWindowsArg("say \"hi\""), "\"say \\\"hi\\\"\"") + Assert.assertEquals(OutsideStart.quoteWindowsArg("C:\\dir with space\\"), "\"C:\\dir with space\\\\\"") + } + + @Test + fun aProcessStartedThroughWmiGetsItsArgumentsAndWorkingDirectory() { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("WMI is Windows only") + val dir = Files.createTempDirectory("grill outside start") + val out = dir.resolve("args.txt") + val program = dir.resolve("Args.java") + Files.writeString(program, """ + public class Args { + public static void main(String[] a) throws Exception { + StringBuilder s = new StringBuilder(System.getProperty("user.dir")); + for (int i = 1; i < a.length; i++) s.append('\n').append('[').append(a[i]).append(']'); + java.nio.file.Files.writeString(java.nio.file.Path.of(a[0]), s.toString()); + } + } + """.trimIndent()) + val args = listOf("plain", "with space", "quote\"inside", "trailing\\", "") + val java = ProcessHandle.current().info().command().orElseThrow() + val pid = OutsideStart.start(listOf(java, program.toString(), out.toString()) + args, dir, OutsideStart.Show.HIDDEN) + Assert.assertTrue(pid > 0) + val deadline = System.nanoTime() + 60_000_000_000L + while (!Files.exists(out) && System.nanoTime() < deadline) Thread.sleep(100) + Thread.sleep(200) + Assert.assertEquals(Files.readString(out).lines(), listOf(dir.toString()) + args.map { "[$it]" }) + } + @Test fun theWindowWatcherShipsAndRunsFromAFileNamedByItsContent() { val dir = Files.createTempDirectory("grill-window-watcher") @@ -112,7 +209,7 @@ class BattleNetSignInTests { fun aSignInThatCannotBeWatchedNeitherFailsTheLaunchNorKeepsTheLock() { // The map runs by now: an exception would make `grill run --hot` roll back a session the new map uses. val gate = ServerSocket().apply { bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 0)) } - val renewal = BattleNetSignIn.Renewal(gate, "TOKEN", { throw java.io.IOException("registry query timed out") }, 1) + val renewal = BattleNetSignIn.Renewal(gate, { throw java.io.IOException("registry query timed out") }, 1) val reports = mutableListOf() Wc3MapRunner.awaitSignIn(renewal, reports::add) @@ -132,17 +229,61 @@ class BattleNetSignInTests { @Test fun aSignInIsAwaitedUntilTheClientReplacesTheToken() { val gate = ServerSocket().apply { bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 0)) } - val reads = mutableListOf("TOKEN", "TOKEN", "NEW") - val renewal = BattleNetSignIn.Renewal(gate, "TOKEN", { reads.removeAt(0) }, 1) + val reads = mutableListOf(false, false, true) + var stopped = false + val renewal = BattleNetSignIn.Renewal(gate, { reads.removeAt(0) }, 1, onClose = { stopped = true }) val reports = mutableListOf() Wc3MapRunner.awaitSignIn(renewal, reports::add) Assert.assertTrue(reads.isEmpty(), "polled until the token changed") Assert.assertTrue(gate.isClosed) + Assert.assertTrue(stopped, "the sign-in watcher is stopped with the lock") Assert.assertEquals(reports, listOf("Waiting for Warcraft III to sign in...")) } + @Test + fun theSignInWatcherReportsWhenTheTokenItStartedWithIsReplaced() { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows registry") + val key = "HKCU\\Software\\WurstSetupTests\\SignIn-${java.util.UUID.randomUUID()}" + fun reg(vararg args: String) = Assert.assertEquals(ProcessBuilder("reg.exe", *args).redirectErrorStream(true) + .redirectOutput(ProcessBuilder.Redirect.DISCARD).start().waitFor(), 0) + reg("add", key, "/v", "EDITOR_TOKEN", "/t", "REG_BINARY", "/d", "0102", "/f") + val dir = Files.createTempDirectory("grill signin watcher") + val output = dir.resolve("out.log") + val script = BattleNetSignIn.scriptCopy(BattleNetSignIn.SIGNIN_SCRIPT, dir) + val process = ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", + "& ${BattleNetSignIn.powerShellQuote(script.toString())} -TimeoutSeconds 30" + + " -Key ${BattleNetSignIn.powerShellQuote(key.replaceFirst("HKCU\\", "HKCU:\\"))}" + + " *> ${BattleNetSignIn.powerShellQuote(output.toString())}").start() + val watcher = BattleNetSignIn.SignInWatcher(process.toHandle(), output) + try { + val deadline = System.nanoTime() + 30_000_000_000L + while (!watcher.ready() && System.nanoTime() < deadline) Thread.sleep(50) + Assert.assertTrue(watcher.ready()) + Assert.assertFalse(watcher.signedIn(), "the token it started with is still there") + reg("add", key, "/v", "EDITOR_TOKEN", "/t", "REG_BINARY", "/d", "0304", "/f") + while (!watcher.signedIn() && System.nanoTime() < deadline) Thread.sleep(50) + Assert.assertTrue(watcher.signedIn()) + } finally { + watcher.stop() + reg("delete", key, "/f") + } + Assert.assertFalse(Files.exists(output), "stop removes its output") + Assert.assertTrue(Files.readString(script).all { it.code < 128 }, "Windows PowerShell reads a .ps1 without BOM as ANSI") + } + + @Test + fun aSignInWatcherThatEndedWithoutTheSignInIsNotTakenForOne() { + val output = Files.createTempFile("grill-signin", ".log") + Files.write(output, utf16("ready\r\ntimeout\r\n")) + val watcher = BattleNetSignIn.SignInWatcher(null, output) + Assert.assertTrue(watcher.ready()) + Assert.assertThrows(java.io.IOException::class.java) { watcher.signedIn() } + Files.write(output, utf16("ready\r\nsigned-in\r\n")) + Assert.assertTrue(watcher.signedIn(), "a watcher that saw the sign-in and ended still reports it") + } + @Test fun anInvalidConfiguredPathFallsBackToDetection() { if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows path rules") diff --git a/templates/AGENTS.md b/templates/AGENTS.md index 0022013..15d3ff1 100644 --- a/templates/AGENTS.md +++ b/templates/AGENTS.md @@ -1,4 +1,4 @@ - + # AGENTS.md - WurstScript Map Project Notes WurstScript Warcraft III map project notes for editing `.wurst` code, dependencies, generated objects, tests, or map build logic. @@ -51,7 +51,6 @@ Read `scriptMode` before adding `execute()` or timer chunking. Lua has no practi - For single-player Lua iteration, check that `grill help` lists `run --hot` and `reload`. Start with `grill run --hot ExampleMap.w3x`, then save edits and run `grill reload`. In VS Code, use **Hot run wurstscript map** and save, or invoke **Hot reload code**. - Fix compile errors and retry. If the reload refuses an incompatible change, read the reason. Undo the incompatible part and retry in the same game, or keep it and hot-run again for a fresh baseline. - Verify the behavior in game. If a payload was written but nothing changed, check the in-game status, active session and Warcraft III's `CustomMapData/Wurst` directory. See [Lua hot reload recovery](https://github.com/wurstscript/WurstScript/blob/master/docs/LUA_HOT_RELOAD.md). -- Use `wc3-e2e-harness` for automated Warcraft III engine tests, including launch and loading-screen input. ## Validate