Use the stock Tauri NSIS template with RuneStone installer hooks
Remove the 996-line fork of the Tauri 2.11.4 template and the custom
comparator. src-tauri/windows/hooks.nsh now adds the RuneStone behavior
through bundle.windows.nsis.installerHooks:
- RuneStoneGuiInit (MUI_CUSTOMFUNCTION_GUIINIT) runs before the first
page in interactive and passive setup. It stops a downgrade with exit
code 2. It makes the stock maintenance page skip itself, so that setup
never starts the uninstaller for an upgrade or a reinstall.
- The hidden section RuneStoneVersionCheck runs before the Tauri sections
in all modes. Silent setup shows no pages, so it needs this check.
- NSIS_HOOK_POSTINSTALL writes the release version to DisplayVersion and
RuneStoneReleaseVersion, and the Windows version to
RuneStoneWindowsVersion. Installed apps now show 0.1.23a, not 0.1.23+1.
Setup compares the four-number Windows encoding with ${VersionCompare}.
An unknown installed version stops setup.
buildInstaller.mjs gives the toolchain version to Tauri through a
--config override. It writes tauri.conf.json, Cargo.toml, and Cargo.lock
only after the installer is complete. package.json changes during the
build because the Settings dialog imports its version. A failed build
restores it. Add --dry-run, which prints the plan and changes no file.
The tests compile NSIS programs with the real makensis. They simulate the
installed version in a test-only HKCU key and check /S, /P, /UPDATE, and
interactive setup. A drift check reads the template from the installed
Tauri CLI. The first real installer needs the installer checks in
docs/builds.md.
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, mkdir, readFile, writeFile, copyFile, readdir, rm, access } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { buildCommands, describePlan, parseArguments, planInstallerBuild, runInstallerBuild, versionFiles } from '../../../scripts/buildInstaller.mjs';
|
||||
import { nextHotfix, releaseVersion } from '../../../scripts/releaseVersion.mjs';
|
||||
|
||||
const repository = path.resolve('.');
|
||||
const exists = (file: string) => access(file).then(() => true, () => false);
|
||||
|
||||
// A copy of the files that the installer script reads, with a placeholder Browser runtime.
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-build-'));
|
||||
for (const file of [...versionFiles, 'src-tauri/tauri.windows.conf.json', 'src-tauri/windows/hooks.nsh']) {
|
||||
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
|
||||
await copyFile(path.join(repository, file), path.join(root, file));
|
||||
}
|
||||
await mkdir(path.join(root, 'src-tauri/browser-engine'), { recursive: true });
|
||||
await writeFile(path.join(root, 'src-tauri/browser-engine/RuneStone-Browser.exe'), '');
|
||||
const before = await Promise.all(versionFiles.map(file => readFile(path.join(root, file), 'utf8')));
|
||||
const current = releaseVersion(JSON.parse(before[0]).version);
|
||||
return { root, before, current, next: releaseVersion(nextHotfix(current.version)) };
|
||||
}
|
||||
|
||||
const contents = (root: string) => Promise.all(versionFiles.map(file => readFile(path.join(root, file), 'utf8')));
|
||||
|
||||
async function withFixture(body: (setup: Awaited<ReturnType<typeof fixture>>) => Promise<void>) {
|
||||
const setup = await fixture();
|
||||
try { await body(setup); } finally { await rm(setup.root, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
test('the installer script reads --version and --dry-run', () => {
|
||||
assert.deepEqual(parseArguments([]), { version: undefined, dryRun: false });
|
||||
assert.deepEqual(parseArguments(['--version', '0.1.44a', '--dry-run']), { version: '0.1.44a', dryRun: true });
|
||||
assert.deepEqual(parseArguments(['--dry-run', '--version', '0.1.45']), { version: '0.1.45', dryRun: true });
|
||||
for (const args of [['--version'], ['0.1.45'], ['--version', '0.1.45', '--version', '0.1.46'], ['--force']]) assert.throws(() => parseArguments(args));
|
||||
});
|
||||
|
||||
test('a completed build sets the version fields only after the installer exists', () => withFixture(async ({ root, before, next }) => {
|
||||
const plan = await planInstallerBuild(root, next.version);
|
||||
assert.deepEqual(await contents(root), before, 'Planning must not change a file.');
|
||||
assert.deepEqual(plan.override, { version: next.toolchain });
|
||||
const plain = describePlan(plan);
|
||||
assert.match(plain, new RegExp(`Configuration override: \\{"version":"${next.toolchain.replace('+', '\\+')}"\\}`));
|
||||
assert.match(plain, /compile: .* build --no-bundle --config .* -- --locked/);
|
||||
const staging = path.join(root, 'output/attempt');
|
||||
const overridePath = path.join(staging, 'tauri.version.json');
|
||||
const calls: { command: string, args: string[], files: string[] }[] = [];
|
||||
const installer = await runInstallerBuild(plan, async (command: string, args: string[]) => {
|
||||
calls.push({ command, args, files: await contents(root) });
|
||||
if (args.includes('bundle')) {
|
||||
assert.deepEqual(JSON.parse(await readFile(overridePath, 'utf8')), { version: next.toolchain });
|
||||
await mkdir(path.dirname(plan.artifacts.bundled), { recursive: true });
|
||||
await writeFile(plan.artifacts.bundled, 'setup');
|
||||
}
|
||||
}, staging);
|
||||
assert.deepEqual(calls.map(({ command, args }) => ({ command, args })),
|
||||
buildCommands(plan, overridePath).map(({ command, args }) => ({ command, args })));
|
||||
for (const call of calls) {
|
||||
// The front end reads package.json. Tauri, Cargo, and the bundler get the version from the override.
|
||||
assert.equal(JSON.parse(call.files[0]).version, next.version);
|
||||
assert.deepEqual(call.files.slice(1), before.slice(1), 'Only package.json changes during the build.');
|
||||
}
|
||||
assert.equal(installer, path.join(root, 'releases', next.version, `RuneStone_${next.version}_x64-setup.exe`));
|
||||
assert.equal(await readFile(installer, 'utf8'), 'setup');
|
||||
assert.equal(await exists(plan.artifacts.bundled), false);
|
||||
assert.equal(await exists(plan.artifacts.renamed), false);
|
||||
const metadata = JSON.parse(await readFile(plan.artifacts.metadata, 'utf8'));
|
||||
assert.deepEqual([metadata.version, metadata.toolchainVersion, metadata.windowsVersion, metadata.bytes], [next.version, next.toolchain, next.windows, 5]);
|
||||
const after = await contents(root);
|
||||
assert.deepEqual(after, plan.updated);
|
||||
assert.equal(JSON.parse(after[0]).version, next.version);
|
||||
assert.equal(JSON.parse(after[1]).version, next.toolchain);
|
||||
assert.match(after[2], new RegExp(`^version = "${next.toolchain.replace('+', '\\+')}"`, 'm'));
|
||||
assert.match(after[2], new RegExp(`\\[package\\.metadata\\.runestone\\]\\r?\\nversion = "${next.version}"`));
|
||||
assert.match(after[3], new RegExp(`name = "runestone"\\r?\\nversion = "${next.toolchain.replace('+', '\\+')}"`));
|
||||
}));
|
||||
|
||||
test('a failed build leaves the version fields unchanged', () => withFixture(async ({ root, before, next }) => {
|
||||
for (const failure of ['compile', 'version-resource', 'bundle', 'missing setup file']) {
|
||||
const plan = await planInstallerBuild(root, next.version);
|
||||
const staging = path.join(root, 'output', failure.replaceAll(' ', '-'));
|
||||
const steps = buildCommands(plan, path.join(staging, 'tauri.version.json'));
|
||||
let index = 0;
|
||||
await assert.rejects(runInstallerBuild(plan, async () => {
|
||||
if (steps[index++].step === failure) throw Error('The build command failed with exit code 1');
|
||||
}, staging));
|
||||
assert.deepEqual(await contents(root), before, 'A failure during ' + failure + ' must restore the version fields.');
|
||||
assert.equal(await exists(plan.artifacts.release), false);
|
||||
assert.equal(await exists(plan.artifacts.metadata), false);
|
||||
assert.ok((await readdir(staging)).includes('package.json.before'));
|
||||
}
|
||||
}));
|
||||
|
||||
test('the plan stops before a build that breaks the release rules', () => withFixture(async ({ root, before, current, next }) => {
|
||||
const tauriConfig = path.join(root, 'src-tauri/tauri.conf.json');
|
||||
const windowsConfig = path.join(root, 'src-tauri/tauri.windows.conf.json');
|
||||
const windowsBefore = await readFile(windowsConfig, 'utf8');
|
||||
await assert.rejects(planInstallerBuild(root, '0.1.44-rc1'), /release version such as/);
|
||||
await writeFile(tauriConfig, before[1].replace(`"version": "${current.toolchain}"`, '"version": "9.9.9"'));
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /do not match/);
|
||||
await writeFile(tauriConfig, before[1]);
|
||||
const windows = JSON.parse(windowsBefore);
|
||||
windows.bundle.windows.allowDowngrades = true;
|
||||
await writeFile(windowsConfig, JSON.stringify(windows));
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /Downgrade protection/);
|
||||
windows.bundle.windows.allowDowngrades = false;
|
||||
delete windows.bundle.windows.nsis.installerHooks;
|
||||
await writeFile(windowsConfig, JSON.stringify(windows));
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /installer hooks/);
|
||||
await writeFile(windowsConfig, windowsBefore);
|
||||
const plan = await planInstallerBuild(root, next.version);
|
||||
await mkdir(plan.releaseDir, { recursive: true });
|
||||
await writeFile(plan.artifacts.release, 'existing');
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /already exists/);
|
||||
await rm(plan.releaseDir, { recursive: true });
|
||||
await rm(path.join(root, 'src-tauri/browser-engine'), { recursive: true });
|
||||
await assert.rejects(planInstallerBuild(root, next.version), /browser runtime is not staged/);
|
||||
assert.deepEqual(await contents(root), before);
|
||||
}));
|
||||
@@ -1,13 +1,15 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
|
||||
import { mkdtemp, 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 { existsSync } from 'node:fs';
|
||||
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' });
|
||||
@@ -16,62 +18,227 @@ test('hotfix versions retain their release identity and advance in letter order'
|
||||
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));
|
||||
});
|
||||
|
||||
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; run pnpm build:installer once to download it';
|
||||
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}"`));
|
||||
});
|
||||
|
||||
test('the native NSIS comparator blocks older hotfixes and permits reinstall', { skip: nsisSkip }, async () => {
|
||||
// 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;
|
||||
};
|
||||
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 checks: string[] = [];
|
||||
checks.push('StrCpy $0 "keep0"\nStrCpy $1 "keep1"\nPush "0.1.23a"\nPush "0.1.23"\nCall RuneStoneCompareVersions\nPop $2\nStrCmp $0 "keep0" saved0\nSetErrorLevel 1\nQuit\nsaved0:\nStrCmp $1 "keep1" saved1\nSetErrorLevel 1\nQuit\nsaved1:');
|
||||
let index = 0;
|
||||
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) {
|
||||
checks.push(`Push "${ordering[i]}"\nPush "${ordering[j]}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 ${Math.sign(i - j)} check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
|
||||
const results = path.join(root, 'results.txt');
|
||||
const valid = new Map<string, string>([['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);
|
||||
}
|
||||
for (const version of ['0.1.23A', '0.1.23a1', '0.1.a', '0.1.23-rc', '0.1.23aaaaa', '4294967296.0.0']) {
|
||||
checks.push(`Push "0.1.23a"\nPush "${version}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 -1 check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
|
||||
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"`);
|
||||
}
|
||||
const executable = path.join(root, 'compare.exe');
|
||||
const source = `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone version check"\nOutFile "${executable}"\n!include LogicLib.nsh\n!include WordFunc.nsh\n!include "${path.resolve('src-tauri/windows/versionCompare.nsh')}"\nSection\n${checks.join('\n')}\nSetErrorLevel 0\nSectionEnd\n`;
|
||||
const script = path.join(root, 'compare.nsi');
|
||||
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);
|
||||
const compiler = makensis;
|
||||
const built = spawnSync(compiler, ['/V2', script], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(built.status, 0, built.stdout + built.stderr);
|
||||
compile(script, source);
|
||||
const checked = spawnSync(executable, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
|
||||
assert.equal(checked.status, 0, checked.stdout + checked.stderr);
|
||||
const patched = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.resolve('scripts/setWindowsVersion.ps1'), '-Path', executable, '-Version', '0.1.23a', '-NumericVersion', '0.1.23.1'], { encoding: 'utf8', windowsHide: true });
|
||||
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/);
|
||||
// Git can check the template out with CRLF line endings on Windows.
|
||||
const template = (await readFile('src-tauri/windows/installer.nsi', 'utf8')).replaceAll('\r\n', '\n');
|
||||
assert.ok(template.includes('Call RuneStoneCompareVersions'));
|
||||
assert.ok(!template.includes('nsis_tauri_utils::SemverCompare'));
|
||||
assert.match(template, /SetErrorLevel 2\n\s+Quit/);
|
||||
const guard = / !if "\$\{ALLOWDOWNGRADES\}" == "false"\n \$\{If\} \$R0 = -1[\s\S]+? !endif/.exec(template)?.[0];
|
||||
assert.ok(guard, 'The downgrade guard must precede reinstall and update actions.');
|
||||
const blockExe = path.join(root, 'block.exe');
|
||||
const blockScript = path.join(root, 'block.nsi');
|
||||
await writeFile(blockScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone downgrade check"\nOutFile "${blockExe}"\n!include LogicLib.nsh\n!define ALLOWDOWNGRADES "false"\nLangString dontUninstallDowngrade 1033 "Older versions cannot replace this installation."\nSection\nStrCpy $R0 -1\n${guard}\nSetErrorLevel 1\nSectionEnd\n`);
|
||||
const blockBuilt = spawnSync(compiler, ['/V2', blockScript], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(blockBuilt.status, 0, blockBuilt.stdout + blockBuilt.stderr);
|
||||
for (const flags of [['/S'], ['/S', '/P'], ['/S', '/UPDATE']]) {
|
||||
const blocked = spawnSync(blockExe, flags, { encoding: 'utf8', windowsHide: true, timeout: 30000 });
|
||||
assert.equal(blocked.status, 2, 'The installer must block a downgrade with ' + flags.join(' '));
|
||||
}
|
||||
assert.match(template, /\$\{ElseIf\} \$R0 = 1 ; Upgrading\n\s+\$\{If\} \$R1 = 1\n\s+Goto reinst_done/);
|
||||
assert.ok(template.includes('"RuneStoneReleaseVersion" "${VERSION}"'));
|
||||
assert.ok(template.includes('"DisplayVersion" "${TOOLCHAINVERSION}"'));
|
||||
const legacyExe = path.join(root, 'legacy.exe');
|
||||
const legacyScript = path.join(root, 'legacy.nsi');
|
||||
const pluginPath = path.join(process.env.LOCALAPPDATA!, 'tauri/NSIS/Plugins/x86-unicode/additional');
|
||||
await writeFile(legacyScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone legacy version check"\nOutFile "${legacyExe}"\n!addplugindir "${pluginPath}"\nSection\nnsis_tauri_utils::SemverCompare "0.1.23" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_ok\nSetErrorLevel 1\nQuit\nlegacy_ok:\nnsis_tauri_utils::SemverCompare "0.1.22" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_older_ok\nSetErrorLevel 1\nQuit\nlegacy_older_ok:\nnsis_tauri_utils::SemverCompare "0.1.24" "0.1.23+1"\nPop $0\nStrCmp $0 1 legacy_newer_ok\nSetErrorLevel 1\nQuit\nlegacy_newer_ok:\nSetErrorLevel 0\nSectionEnd\n`);
|
||||
const legacyBuilt = spawnSync(compiler, ['/V2', legacyScript], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(legacyBuilt.status, 0, legacyBuilt.stdout + legacyBuilt.stderr);
|
||||
const legacyChecked = spawnSync(legacyExe, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
|
||||
assert.equal(legacyChecked.status, 0, 'Older installers must detect the encoded hotfix as newer.');
|
||||
} 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<string, string> = {};
|
||||
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<string, string>) => {
|
||||
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<string, string>();
|
||||
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 "$TEMP"
|
||||
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<string, string>[]) {
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user