import test from 'node:test'; import assert from 'node:assert/strict'; import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm } from 'node:fs/promises'; import { existsSync, readFileSync, realpathSync } from 'node:fs'; import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; import { releaseVersion, nextHotfix, compareReleases } from '../../../scripts/releaseVersion.mjs'; const ordering = ['0.1.22z', '0.1.23', '0.1.23a', '0.1.23b', '0.1.23c', '0.1.23z', '0.1.23aa', '0.1.23ab', '0.1.23zz', '0.1.23aaa', '0.1.24']; const hooks = path.resolve('src-tauri/windows/hooks.nsh'); test('hotfix versions retain their release identity and advance in letter order', () => { assert.deepEqual(releaseVersion('0.1.23a'), { version: '0.1.23a', base: '0.1.23', suffix: 'a', revision: 1, toolchain: '0.1.23+1', windows: '0.1.23.1' }); for (const [before, after] of [['0.1.23', '0.1.23a'], ['0.1.23a', '0.1.23b'], ['0.1.23b', '0.1.23c'], ['0.1.23z', '0.1.23aa'], ['0.1.23aa', '0.1.23ab'], ['0.1.23zz', '0.1.23aaa']]) assert.equal(nextHotfix(before), after); for (const version of ['0.1.23A', '0.1.23a1', '0.1.23-a', '0.1.23+1', '0.1', '0.1.23aaaaa', '0.1.65536']) assert.throws(() => releaseVersion(version)); for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) assert.equal(compareReleases(ordering[i], ordering[j]), Math.sign(i - j)); }); test('the Windows configuration uses the RuneStone hooks with the stock template', async () => { const config = JSON.parse(await readFile('src-tauri/tauri.conf.json', 'utf8')); const windows = JSON.parse(await readFile('src-tauri/tauri.windows.conf.json', 'utf8')).bundle.windows; assert.equal(windows.allowDowngrades, false); assert.equal(windows.nsis.template, undefined, 'Use the stock Tauri template. Put RuneStone behavior in the hooks.'); assert.equal(path.resolve('src-tauri', windows.nsis.installerHooks), hooks); // The hooks read SHCTX as HKCU and use the uninstall key of the product name. assert.equal(windows.nsis.installMode, 'currentUser'); const source = await readFile(hooks, 'utf8'); assert.ok(source.includes(`!define /ifndef RUNESTONE_UNINSTKEY "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${config.productName}"`)); }); // The Tauri CLI embeds its NSIS template. These checks fail when a Tauri update changes what the hooks rely on. function stockTemplate() { const cli = createRequire(realpathSync('node_modules/@tauri-apps/cli/package.json')); let binary: string; try { binary = cli.resolve('@tauri-apps/cli-win32-x64-msvc'); } catch { return null; } const bytes = readFileSync(binary); const start = bytes.indexOf('Unicode true\r\nManifestDPIAware true'); assert.ok(start >= 0, 'The Tauri CLI no longer contains the expected NSIS template.'); let end = start; while (end < bytes.length && (bytes[end] === 9 || bytes[end] === 10 || bytes[end] === 13 || (bytes[end] >= 32 && bytes[end] < 127))) end++; return bytes.subarray(start, end).toString('latin1').replaceAll('\r\n', '\n'); } const template = process.platform === 'win32' ? stockTemplate() : null; test('the stock Tauri template still provides what the hooks rely on', { skip: template ? false : 'needs the Windows Tauri CLI' }, () => { const text = template!; const at = (fragment: string) => { const index = text.indexOf(fragment); assert.ok(index >= 0, 'The stock template no longer contains: ' + fragment); return index; }; // NSIS_HOOK_POSTUNINSTALL removes the downloaded engine. It needs ${BUNDLEID}, $UpdateMode, and its place after the app data step. const removal = at('RmDir /r "$LOCALAPPDATA\\${BUNDLEID}"'); assert.ok(text.indexOf('${AndIf} $UpdateMode <> 1') < removal); assert.ok(removal < at('!insertmacro NSIS_HOOK_POSTUNINSTALL'), 'The uninstall hook must run after the app data step.'); const include = at('!include "{{installer_hooks}}"'); assert.ok(include < at('!insertmacro MUI_PAGE_WELCOME'), 'Tauri must include the hooks before the first page.'); assert.ok(include < at('\nSection EarlyChecks'), 'Tauri must include the hooks before its first section.'); assert.ok(include < at('\nVar '), 'The hooks file cannot use the template variables.'); at('!define UNINSTKEY "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${PRODUCTNAME}"'); // RuneStoneInstallerVersion reads the version resource. at('VIProductVersion "${VERSIONWITHBUILD}"'); assert.ok(!text.includes('VIFileVersion')); assert.ok(!text.includes('MUI_CUSTOMFUNCTION_GUIINIT') && !text.includes('.onGUIInit'), 'The hooks define the GUI initialization function.'); // RuneStoneGuiInit makes the maintenance page skip itself. That page must look for the installation in SHCTX. const page = text.slice(at('Function PageReinstall\n'), at('Function PageReinstallUpdateSelection')); for (const line of ['ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""', 'ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"', '${IfThen} "$R0$R1" == "" ${|} Abort ${|}']) { assert.ok(page.includes(line), 'PageReinstall no longer contains: ' + line); } // No installer code may change the context between RuneStoneGuiInit and the RuneStoneVersionCheck section. const install = text.slice(0, at('Function un.onInit')); assert.ok(!install.includes('SetShellVarContext'), 'The installer part of the template now changes the shell context.'); assert.ok(text.slice(at('Function .onInit'), at('Section EarlyChecks')).includes('!insertmacro SetContext')); const section = text.slice(at('Section Install\n'), at('Function .onInstSuccess')); assert.ok(section.indexOf('"DisplayVersion" "${VERSION}"') >= 0); assert.ok(section.indexOf('"DisplayVersion" "${VERSION}"') < section.indexOf('!insertmacro NSIS_HOOK_POSTINSTALL'), 'The hook must write DisplayVersion after the template.'); }); const makensis = path.join(process.env.LOCALAPPDATA ?? '', 'tauri/NSIS/makensis.exe'); const nsisSkip = process.platform !== 'win32' ? 'Windows only' : existsSync(makensis) ? false : 'the NSIS compiler is missing; Tauri downloads it during the first installer build'; function compile(script: string, source: string) { const built = spawnSync(makensis, ['/V2', script], { input: undefined, encoding: 'utf8', windowsHide: true }); assert.equal(built.status, 0, source + '\n' + built.stdout + built.stderr); } test('the hook functions convert versions in release order', { skip: nsisSkip }, async () => { const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-version-')); try { const results = path.join(root, 'results.txt'); const valid = new Map([['65535.0.0.65535', '65535.0.0.65535'], ['0.1.23', '0.1.23.0']]); for (const version of ordering) { const { toolchain, windows } = releaseVersion(version); valid.set(toolchain, windows); valid.set(windows, windows); } const invalid = ['', '0.1.23a', '0.1.23A', '0.1.23-rc', '0.1', '0.1.', '.1.2', '1..2.3', '0.1.23+', '0.1.23+1.2', '1.2+3', '0.1.23.1.0', '0.1.65536', '0.1.23+65536', '0.1.23.65536', 'garbage', ' 0.1.23', '0.1.23 ', '0x1.2.3']; const lines = ['FileOpen $9 "' + results + '" w']; for (const input of [...valid.keys(), ...invalid]) lines.push(`Push "${input}"`, 'Call RuneStoneNumericVersion', 'Pop $0', `FileWrite $9 "numeric|${input}|$0$\\n"`); for (const version of ordering) lines.push(`Push "${releaseVersion(version).windows}"`, 'Call RuneStoneReleaseName', 'Pop $0', `FileWrite $9 "release|${version}|$0$\\n"`); for (const left of ordering) for (const right of ordering) { lines.push(`\${VersionCompare} "${releaseVersion(left).windows}" "${releaseVersion(right).windows}" $0`, `FileWrite $9 "compare|${left}|${right}|$0$\\n"`); } lines.push('FileClose $9'); const executable = path.join(root, 'functions.exe'); const script = path.join(root, 'functions.nsi'); const source = `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone hook functions"\nOutFile "${executable}"\n` + `!define RUNESTONE_UNINSTKEY "Software\\RuneStoneInstallerTest-${path.basename(root)}"\n!include "${hooks}"\nSection\n${lines.join('\n')}\nSectionEnd\n`; await writeFile(script, source); compile(script, source); const checked = spawnSync(executable, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 }); assert.equal(checked.status, 0); const output = (await readFile(results, 'utf8')).trim().split('\n').map(line => line.split('|')); const numeric = new Map(output.filter(row => row[0] === 'numeric').map(row => [row[1], row[2]])); for (const [input, expected] of valid) assert.equal(numeric.get(input), expected, 'RuneStoneNumericVersion ' + input); for (const input of invalid) assert.equal(numeric.get(input), '', 'RuneStoneNumericVersion must reject ' + JSON.stringify(input)); for (const row of output.filter(row => row[0] === 'release')) assert.equal(row[2], row[1], 'RuneStoneReleaseName ' + row[1]); for (const [, left, right, result] of output.filter(row => row[0] === 'compare')) { // VersionCompare returns 0 for equal versions, 1 when the first is newer, and 2 when the second is newer. assert.equal(result, String([0, 1, 2].at(compareReleases(left, right))), `VersionCompare ${left} ${right}`); } assert.equal(output.filter(row => row[0] === 'compare').length, ordering.length ** 2); // Tauri cannot write a letter suffix into the version strings of the app executable. const patchedExe = path.join(root, 'patched.exe'); await copyFile(executable, patchedExe); const patched = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.resolve('scripts/setWindowsVersion.ps1'), '-Path', patchedExe, '-Version', '0.1.23a', '-NumericVersion', '0.1.23.1'], { encoding: 'utf8', windowsHide: true }); assert.equal(patched.status, 0, patched.stdout + patched.stderr); assert.match(patched.stdout, /0\.1\.23a/); } finally { assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-version-')), true); await rm(root, { recursive: true, force: true }); } }); // Each test installer has the version resource that Tauri writes for its version, and the stock template // layout: Modern UI, then the hooks, then the pages and an Install section that ends with NSIS_HOOK_POSTINSTALL. // The installed version comes from a test-only registry key. Nothing forces an internal variable. test('the hooks block downgrades in every installer mode', { skip: nsisSkip }, async () => { const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-hooks-')); const key = 'Software\\RuneStoneInstallerTest-' + path.basename(root); const reg = (...args: string[]) => spawnSync('reg', args, { encoding: 'utf8', windowsHide: true }); const installed = () => { const result = reg('query', 'HKCU\\' + key); const values: Record = {}; if (result.status === 0) for (const match of result.stdout.matchAll(/^\s+(\S+)\s+REG_SZ\s+(.*?)\s*$/gm)) values[match[1]] = match[2]; return values; }; const setInstalled = (values: Record) => { reg('delete', 'HKCU\\' + key, '/f'); for (const [name, value] of Object.entries(values)) assert.equal(reg('add', 'HKCU\\' + key, '/v', name, '/d', value, '/f').status, 0); }; const installers = new Map(); const installer = async (version: string) => { if (installers.has(version)) return installers.get(version)!; const { toolchain, windows } = releaseVersion(version); const executable = path.join(root, `setup-${version}.exe`); const script = path.join(root, `setup-${version}.nsi`); const source = `Unicode true RequestExecutionLevel user Name "RuneStone hook test" OutFile "${executable}" InstallDir "${path.join(root, 'install')}" AutoCloseWindow true VIProductVersion "${windows}" VIAddVersionKey "ProductName" "RuneStone hook test" VIAddVersionKey "FileDescription" "RuneStone hook test" VIAddVersionKey "LegalCopyright" "Test" VIAddVersionKey "FileVersion" "${toolchain}" VIAddVersionKey "ProductVersion" "${toolchain}" !define RUNESTONE_UNINSTKEY "${key}" ; Record the notice instead of opening a message box. !macro RUNESTONE_DOWNGRADE_NOTICE \${IfNot} \${Silent} WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestNotice" "shown" \${EndIf} !macroend !include MUI2.nsh !include "${hooks}" !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipPage !insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_LANGUAGE "English" ; In the stock template, the maintenance page that can start the uninstaller follows the first page. ; That page skips itself when it cannot find the installation in SHCTX. Function SkipPage WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestFirstPage" "shown" ReadRegStr $0 SHCTX "\${RUNESTONE_UNINSTKEY}" "RuneStoneWindowsVersion" WriteRegStr HKCU "\${RUNESTONE_UNINSTKEY}" "TestPageFound" "[$0]" Abort FunctionEnd Section Install WriteRegStr SHCTX "\${RUNESTONE_UNINSTKEY}" "DisplayVersion" "${toolchain}" WriteRegStr SHCTX "\${RUNESTONE_UNINSTKEY}" "TestLocalAppData" "$LOCALAPPDATA" !insertmacro NSIS_HOOK_POSTINSTALL SectionEnd `; await writeFile(script, source); compile(script, source); installers.set(version, executable); return executable; }; const install = async (version: string, flags: string[]) => spawnSync(await installer(version), flags, { encoding: 'utf8', windowsHide: true, timeout: 60000 }).status; const silent = (flags: readonly string[]) => flags.includes('/S'); try { // Installer 0.1.23a over 0.1.23b. Without /S, the check runs before the first page. for (const flags of [['/S'], ['/S', '/UPDATE'], ['/S', '/P'], ['/P'], ['/P', '/UPDATE'], []]) { setInstalled({ RuneStoneWindowsVersion: '0.1.23.2', DisplayVersion: '0.1.23b' }); assert.equal(await install('0.1.23a', flags), 2, 'A downgrade must stop with exit code 2: ' + (flags.join(' ') || 'interactive')); const values = installed(); assert.equal(values.DisplayVersion, '0.1.23b', 'A blocked setup must not install.'); assert.equal(values.TestNotice, silent(flags) ? undefined : 'shown'); assert.equal(values.TestFirstPage, undefined, 'Setup must stop before the first page.'); } // Earlier installers wrote only the toolchain version to DisplayVersion. for (const [previous, version, code] of [['0.1.24', '0.1.23z', 2], ['0.1.23+1', '0.1.23', 2], ['0.1.23+1', '0.1.23a', 0], ['0.1.23+1', '0.1.23b', 0]] as const) { setInstalled({ DisplayVersion: previous }); assert.equal(await install(version, ['/S']), code, `${version} over ${previous}`); } // An unknown installed version blocks setup. for (const values of [{ RuneStoneWindowsVersion: '0.1.23b' }, { DisplayVersion: '0.1.23b' }, { DisplayVersion: '0.1.23-beta' }, { DisplayVersion: 'garbage' }] as Record[]) { setInstalled(values); assert.equal(await install('0.1.24', ['/S']), 2, 'Unknown installed version ' + JSON.stringify(values)); } // Same version, upgrade, and first installation. Each writes the literal release version. for (const [previous, version, flags] of [['0.1.23.1', '0.1.23a', ['/S']], ['0.1.23.1', '0.1.23a', []], ['0.1.23.26', '0.1.23aa', ['/P', '/UPDATE']], [null, '0.1.24', ['/S']]] as const) { setInstalled(previous ? { RuneStoneWindowsVersion: previous } : {}); assert.equal(await install(version, [...flags]), 0, `${version} over ${previous ?? 'no installation'} with ${flags.join(' ') || 'interactive'}`); const values = installed(); assert.equal(values.DisplayVersion, version, 'Installed apps must show the release version.'); assert.equal(values.RuneStoneReleaseVersion, version); assert.equal(values.RuneStoneWindowsVersion, releaseVersion(version).windows); assert.equal(values.TestNotice, undefined); // Without /S, the pages must not find the installation, so that setup replaces it in place. assert.equal(values.TestPageFound, silent(flags) ? undefined : '[]'); // RuneStoneGuiInit switches to the "all" context. The sections must run in the current-user context again. assert.equal(values.TestLocalAppData?.toLowerCase(), process.env.LOCALAPPDATA!.toLowerCase()); } } finally { reg('delete', 'HKCU\\' + key, '/f'); assert.equal(reg('query', 'HKCU\\' + key).status, 1, 'The test registry key must be removed.'); assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-hooks-')), true); await rm(root, { recursive: true, force: true }); } }); // NSIS_HOOK_POSTINSTALL removes the engine folder that releases up to 0.1.48 put in the installation folder. // NSIS_HOOK_POSTUNINSTALL removes the downloaded engine, keeps the browser profiles, and keeps everything during an update. test('the hooks remove old and downloaded browser engines but keep the profiles', { skip: nsisSkip }, async () => { const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-engine-')); const bundle = 'com.runestone.hook-test-' + path.basename(root); const local = path.join(process.env.LOCALAPPDATA!, bundle); const install = path.join(root, 'install'); const key = 'Software\\RuneStoneInstallerTest-' + path.basename(root); const program = async (name: string, updateMode: number) => { const executable = path.join(root, name + '.exe'), script = path.join(root, name + '.nsi'); const source = `Unicode true SilentInstall silent RequestExecutionLevel user Name "RuneStone engine hook test" OutFile "${executable}" InstallDir "${install}" VIProductVersion "0.1.49.0" VIAddVersionKey "ProductName" "RuneStone engine hook test" VIAddVersionKey "FileVersion" "0.1.49" VIAddVersionKey "ProductVersion" "0.1.49" !define RUNESTONE_UNINSTKEY "${key}" !define BUNDLEID "${bundle}" !include "${hooks}" Var UpdateMode Section Install StrCpy $UpdateMode ${updateMode} !insertmacro NSIS_HOOK_POSTINSTALL !insertmacro NSIS_HOOK_POSTUNINSTALL SectionEnd `; await writeFile(script, source); compile(script, source); return executable; }; const seed = async () => { await mkdir(path.join(install, 'browser-engine', 'locales'), { recursive: true }); await writeFile(path.join(install, 'browser-engine', 'RuneStone-Browser.exe'), 'old engine'); await writeFile(path.join(install, 'runestone.exe'), 'app'); await mkdir(path.join(local, 'browser-engine', '0.1.8'), { recursive: true }); await writeFile(path.join(local, 'browser-engine', '0.1.8', 'RuneStone-Browser.exe'), 'engine'); await mkdir(path.join(local, 'browser'), { recursive: true }); await writeFile(path.join(local, 'browser', 'browser.json'), '{}'); }; try { await seed(); assert.equal(spawnSync(await program('remove', 0), ['/S'], { windowsHide: true, timeout: 30000 }).status, 0); assert.equal(existsSync(path.join(install, 'browser-engine')), false, 'Setup removes the old engine folder.'); assert.equal(existsSync(path.join(install, 'runestone.exe')), true); assert.equal(existsSync(path.join(local, 'browser-engine')), false, 'Uninstall removes the downloaded engine.'); assert.equal(existsSync(path.join(local, 'browser', 'browser.json')), true, 'The profiles stay.'); await seed(); assert.equal(spawnSync(await program('update', 1), ['/S'], { windowsHide: true, timeout: 30000 }).status, 0); assert.equal(existsSync(path.join(local, 'browser-engine', '0.1.8', 'RuneStone-Browser.exe')), true, 'An update keeps the downloaded engine.'); } finally { spawnSync('reg', ['delete', 'HKCU\\' + key, '/f'], { windowsHide: true }); assert.equal(local.startsWith(process.env.LOCALAPPDATA!) && path.basename(local).startsWith('com.runestone.hook-test-'), true); await rm(local, { recursive: true, force: true }); await rm(root, { recursive: true, force: true }); } });