diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0a7050b..4adaed2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,50 +1,154 @@ -name: build +name: Build desktop release -on: workflow_dispatch +on: + workflow_dispatch: + inputs: + renderer_ref: + description: "Approved Showcode commit SHA (blank uses master)" + required: false + default: "" -jobs: - release: - runs-on: ${{ matrix.os }} +permissions: + contents: read - permissions: - contents: write +concurrency: + group: desktop-release + cancel-in-progress: false + +jobs: + prepare: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.prepare.outputs.version }} + commit: ${{ steps.commit.outputs.sha }} + steps: + - uses: actions/create-github-app-token@v2 + id: app + with: + app-id: ${{ vars.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + repositories: showcode-app + permission-contents: write + - uses: actions/checkout@v5 + with: + ref: master + submodules: recursive + fetch-depth: 0 + token: ${{ steps.app.outputs.token }} + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: npm + cache-dependency-path: | + package-lock.json + showcode/package-lock.json + - name: Pin the approved renderer + env: + RENDERER_REF: ${{ inputs.renderer_ref }} + run: | + mkdir -p .release + git rev-parse HEAD:showcode > .release/previous-ref + git -C showcode fetch origin master + if [ -z "$RENDERER_REF" ]; then + RENDERER_REF=$(git -C showcode rev-parse origin/master) + fi + [[ "$RENDERER_REF" =~ ^[0-9a-f]{40}$ ]] || { echo 'Use a full Showcode commit SHA.'; exit 1; } + git -C showcode merge-base --is-ancestor "$RENDERER_REF" origin/master + git -C showcode checkout --detach "$RENDERER_REF" + printf '%s' "$RENDERER_REF" > .release/renderer-ref + - name: Read approved release notes + run: | + npm ci --prefix showcode + node showcode/scripts/releases/catalog.mjs json > .release/metadata.json + - name: Update desktop version + id: prepare + run: node scripts/releases/prepare.mjs "$(cat .release/previous-ref)" "$(cat .release/renderer-ref)" + - name: Refuse to rebuild a published release + uses: actions/github-script@v7 + env: + RELEASE_VERSION: ${{ steps.prepare.outputs.version }} + with: + script: | + try { + const {data} = await github.rest.repos.getReleaseByTag({ + ...context.repo, tag: `v${process.env.RELEASE_VERSION}`, + }); + if (!data.draft) throw new Error('This version is already published. Prepare a new version.'); + } catch (error) { + if (error.status !== 404) throw error; + } + - name: Record the desktop release commit and tag + id: commit + env: + RELEASE_VERSION: ${{ steps.prepare.outputs.version }} + run: | + git config user.name 'Showcode Release Bot' + git config user.email 'release-bot@users.noreply.github.com' + git add package.json package-lock.json showcode + if ! git diff --cached --quiet; then + git commit -m "Release Showcode $RELEASE_VERSION" + fi + RELEASE_COMMIT=$(git rev-parse HEAD) + RELEASE_TAG="v$RELEASE_VERSION" + if git show-ref --verify --quiet "refs/tags/$RELEASE_TAG"; then + test "$(git rev-parse "$RELEASE_TAG^{commit}")" = "$RELEASE_COMMIT" + else + git tag "$RELEASE_TAG" "$RELEASE_COMMIT" + fi + git push --atomic origin HEAD:master "refs/tags/$RELEASE_TAG" + echo "sha=$RELEASE_COMMIT" >> "$GITHUB_OUTPUT" + - uses: actions/upload-artifact@v4 + with: + name: release-notes + path: | + .release/metadata.json + .release/notes.md + include-hidden-files: true + build: + needs: prepare + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [macos-latest, ubuntu-latest, windows-latest] - steps: - - name: Check out Git repository - uses: actions/checkout@v5 + - uses: actions/checkout@v5 with: + ref: ${{ needs.prepare.outputs.commit }} submodules: recursive - - - name: Setup Node - uses: actions/setup-node@v5 + - uses: actions/setup-node@v5 with: node-version: 22 - - - uses: actions/cache@v5 + cache: npm + cache-dependency-path: | + package-lock.json + showcode/package-lock.json + - uses: actions/download-artifact@v4 with: - path: "**/node_modules" - key: ${{ runner.os }}-modules-${{ hashFiles('**/package-lock.json') }} - - - name: Install Showcode Dependencies - run: (cd ./showcode && npm install) - - - name: Generate Showcode - run: (cd ./showcode && npm run generate) + name: release-notes + path: .release + - name: Install dependencies + shell: bash + run: | + npm ci --prefix showcode + npm ci + - name: Test renderer + if: runner.os == 'Linux' + working-directory: showcode + run: | + npx nuxi prepare + npm run test:releases + npx vitest run + - name: Generate renderer + working-directory: showcode + run: npm run generate env: IS_DESKTOP: true NODE_OPTIONS: --max-old-space-size=4096 - - - name: Install App Dependencies - run: npm install - - - name: Test App + - name: Test desktop app run: npm test - - name: Import macOS signing certificate if: startsWith(matrix.os, 'macos') env: @@ -68,21 +172,92 @@ jobs: echo "CSC_KEYCHAIN=$SIGNING_KEYCHAIN_PATH" >> "$GITHUB_ENV" rm "$SIGNING_CERTIFICATE_PATH" - - name: Build & Publish Application + - name: Package application without publishing shell: bash run: | if [[ "$RUNNER_OS" == "macOS" ]]; then - unset CSC_LINK - npx electron-builder --publish always --config.forceCodeSigning=true + unset CSC_LINK + npx electron-builder --publish never --config.forceCodeSigning=true -c.releaseInfo.releaseNotesFile=.release/notes.md else - npx electron-builder --publish always + npx electron-builder --publish never -c.releaseInfo.releaseNotesFile=.release/notes.md fi env: RELEASE: true NODE_ENV: production CSC_LINK: ${{ secrets.CSC_LINK }} CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} APPLE_ID: ${{ secrets.APPLE_ID }} APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }} APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + - uses: actions/upload-artifact@v4 + with: + name: installers-${{ runner.os }} + if-no-files-found: error + compression-level: 0 + path: | + dist/*.dmg + dist/*.zip + dist/*.exe + dist/*.AppImage + dist/*.blockmap + dist/latest*.yml + + draft: + needs: [prepare, build] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v5 + with: + ref: ${{ needs.prepare.outputs.commit }} + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: npm + - run: npm ci --ignore-scripts + - uses: actions/download-artifact@v4 + with: + pattern: installers-* + path: dist + merge-multiple: true + - uses: actions/download-artifact@v4 + with: + name: release-notes + path: .release + - name: Verify all installers and updater manifests + env: + RELEASE_VERSION: ${{ needs.prepare.outputs.version }} + run: node scripts/releases/artifacts.mjs dist "$RELEASE_VERSION" + - name: Create or update the draft release + uses: actions/github-script@v7 + env: + RELEASE_VERSION: ${{ needs.prepare.outputs.version }} + RELEASE_COMMIT: ${{ needs.prepare.outputs.commit }} + with: + script: | + const fs = require('node:fs'); + const notes = fs.readFileSync('.release/notes.md', 'utf8'); + const tag = `v${process.env.RELEASE_VERSION}`; + let release; + try { + release = (await github.rest.repos.getReleaseByTag({...context.repo, tag})).data; + } catch (error) { + if (error.status !== 404) throw error; + } + if (release && !release.draft) throw new Error('Refusing to modify a published release.'); + const options = { + ...context.repo, name: `Showcode ${process.env.RELEASE_VERSION}`, + body: notes, draft: true, prerelease: false, + }; + if (release) await github.rest.repos.updateRelease({...options, release_id: release.id}); + else await github.rest.repos.createRelease({ + ...options, tag_name: tag, target_commitish: process.env.RELEASE_COMMIT, + }); + - name: Upload verified assets + env: + GH_TOKEN: ${{ github.token }} + RELEASE_VERSION: ${{ needs.prepare.outputs.version }} + run: | + gh release upload "v$RELEASE_VERSION" dist/* --clobber + printf '## Showcode %s is ready for review\n\nAll platform builds and updater manifests passed. Download an installer from the draft release, test it, then click **Publish release**. No rebuild is required.\n' "$RELEASE_VERSION" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..b3beea9 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,21 @@ +name: Test + +on: + pull_request: + push: + branches: [master] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: npm + - run: npm ci --ignore-scripts + - run: npm test diff --git a/.gitignore b/.gitignore index 03014b9..8d55365 100755 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ yarn-debug.log* # Electron build artifacts out/ release/ +.release/ diff --git a/docs/releases.md b/docs/releases.md new file mode 100644 index 0000000..e6afc35 --- /dev/null +++ b/docs/releases.md @@ -0,0 +1,48 @@ +# Desktop releases + +The release starts in [Showcode's Prepare release workflow](https://github.com/stevebauman/showcode/actions/workflows/prepare-release.yml). Follow the full [release guide](https://github.com/stevebauman/showcode/blob/master/docs/releases.md) for the release entry format and GitHub App setup. + +After the Showcode release PR merges, **Build desktop release** receives its exact commit SHA. It: + +1. Verifies that the renderer SHA belongs to Showcode master and that its notes match its package version. +2. Updates the submodule, this repository's `package.json`, and both version fields in `package-lock.json`. +3. Commits those changes to master and creates `vVERSION` at the desktop commit. Existing tags must point to that same commit. +4. Builds macOS arm64/x64, Windows x64, and Linux x64 from that immutable commit. macOS signing and notarization use the existing Apple credentials. +5. Verifies required files, updater versions, and the size/SHA-512 of files referenced by updater manifests, and creates `SHA256SUMS.txt`. +6. Uploads installers, updater files, checksums, and the approved notes to a **draft** release after every build succeeds. + +Download and test the draft installer, then publish it in GitHub. This makes the existing binaries available to users without rebuilding them. The workflow never publishes automatically. + +## GitHub setup + +Both repositories need the Actions variable `RELEASE_APP_ID` and Actions secret `RELEASE_APP_PRIVATE_KEY`. The GitHub App must be installed on both repositories with Contents, Pull requests, and Actions read/write permissions. In this repository, allow its mechanical pushes to master and `v*` tag creation under any branch/tag rules. See the upstream guide for the exact scope and rollout order. + +Keep these existing Actions secrets here: + +- `APPLE_ID` +- `APPLE_ID_PASSWORD` +- `APPLE_TEAM_ID` +- `CSC_LINK` (base64 P12) +- `CSC_KEY_PASSWORD` + +Merge this automation before the Showcode automation. The existing 3.0.0 version is intentionally unchanged by this setup. + +## Local preview + +```sh +npm run release:local +``` + +This uses the currently checked-out renderer, installs locked dependencies, generates the UI, runs the desktop tests, packages a local app for the host architecture (ad-hoc signed on macOS), and opens it on macOS/Windows. On Linux it prints the executable path. For packaging without opening the app: + +```sh +npm run release:local -- --no-open +``` + +The package has a `-local.0` suffix and disables automatic update checks. It never uses distribution signing, notarizes, publishes, or changes tracked versions/submodule references. For production-like signed installers, use the CI draft release. + +## Retry a release + +Prefer **Re-run failed jobs** on the original workflow run. To manually start the workflow, supply the same approved full Showcode SHA in `renderer_ref`. Leaving it blank selects Showcode master, which must already contain prepared release notes and a matching version. + +The same version can be retried only with the same renderer SHA; changes require a new version. Published releases are never overwritten. Runs are serialized to avoid two releases changing master or tags at the same time. diff --git a/main/updater.js b/main/updater.js index b6e6995..35c723c 100644 --- a/main/updater.js +++ b/main/updater.js @@ -62,6 +62,8 @@ async function promptToInstall() { } export async function checkForUpdates({notifyIfCurrent = false} = {}) { + if (app.getVersion().includes("-local.")) return; + if (updateReady) { if (notifyIfCurrent) await promptToInstall(); return; @@ -141,7 +143,7 @@ function resumeChecks() { } app.whenReady().then(() => { - if (!app.isPackaged) return; + if (!app.isPackaged || app.getVersion().includes("-local.")) return; scheduleCheck(startupDelay); powerMonitor.on("resume", resumeChecks); diff --git a/package-lock.json b/package-lock.json index ff2d192..d98cdce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,8 @@ "electron": "^41.2.1", "electron-builder": "^26.8.1", "prettier": "^3.8.3", - "wait-on": "^9.0.5" + "wait-on": "^9.0.5", + "yaml": "^2.8.3" } }, "node_modules/@develar/schema-utils": { @@ -4311,6 +4312,22 @@ "dev": true, "license": "ISC" }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, "node_modules/yargs": { "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", diff --git a/package.json b/package.json index 0aa7a5c..a160430 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,8 @@ "format:check": "prettier --check .", "generate": "cd showcode && cross-env IS_DESKTOP=true npm run generate", "start": "electron .", - "test": "node --experimental-test-module-mocks --test tests/*.test.js" + "test": "node --experimental-test-module-mocks --test tests/*.test.js", + "release:local": "node scripts/releases/local.mjs" }, "dependencies": { "electron-log": "^5.4.3", @@ -30,7 +31,8 @@ "electron": "^41.2.1", "electron-builder": "^26.8.1", "prettier": "^3.8.3", - "wait-on": "^9.0.5" + "wait-on": "^9.0.5", + "yaml": "^2.8.3" }, "build": { "files": [ @@ -41,7 +43,8 @@ "publish": { "provider": "github", "owner": "stevebauman", - "repo": "showcode-app" + "repo": "showcode-app", + "releaseType": "draft" }, "productName": "Showcode", "appId": "com.showcode.app", diff --git a/readme.md b/readme.md index e40e4e6..5468ed7 100644 --- a/readme.md +++ b/readme.md @@ -70,10 +70,12 @@ This concurrently runs the Nuxt dev server on `http://localhost:3000` and launch ## Building +For the automated release flow and required GitHub configuration, see the [release guide](docs/releases.md). For a local preview in one command, run `npm run release:local`. + To produce a distributable build for your current platform: ```bash -npm run generate # builds the Nuxt renderer into showcode/dist +npm run generate # builds the Nuxt renderer into showcode/.output/public npm run build # packages the Electron app via electron-builder ``` diff --git a/scripts/releases/artifacts.mjs b/scripts/releases/artifacts.mjs new file mode 100644 index 0000000..fd57e32 --- /dev/null +++ b/scripts/releases/artifacts.mjs @@ -0,0 +1,79 @@ +import {createHash} from "node:crypto"; +import {createReadStream} from "node:fs"; +import {readFile, readdir, stat, writeFile} from "node:fs/promises"; +import path from "node:path"; +import {pathToFileURL} from "node:url"; +import {parse} from "yaml"; + +async function checksum(filename, algorithm, encoding) { + const hash = createHash(algorithm); + for await (const chunk of createReadStream(filename)) hash.update(chunk); + return hash.digest(encoding); +} + +export async function validateArtifacts(directory, version) { + const files = await readdir(directory); + const required = [ + `Showcode-${version}-mac-arm64.dmg`, + `Showcode-${version}-mac-x64.dmg`, + `Showcode-${version}-mac-arm64.zip`, + `Showcode-${version}-mac-x64.zip`, + `Showcode-${version}-win-x64.exe`, + `Showcode-${version}-linux-x64.AppImage`, + "latest.yml", + "latest-mac.yml", + "latest-linux.yml", + ]; + for (const filename of required) { + if (!files.includes(filename) || !(await stat(path.join(directory, filename))).size) { + throw new Error(`Missing release artifact: ${filename}`); + } + } + for (const filename of ["latest.yml", "latest-mac.yml", "latest-linux.yml"]) { + const manifest = parse(await readFile(path.join(directory, filename), "utf8")); + if (manifest.version !== version || !manifest.files?.length) { + throw new Error(`Invalid updater manifest: ${filename}`); + } + const platformFiles = { + "latest.yml": [`Showcode-${version}-win-x64.exe`], + "latest-mac.yml": [ + `Showcode-${version}-mac-arm64.zip`, + `Showcode-${version}-mac-x64.zip`, + ], + "latest-linux.yml": [`Showcode-${version}-linux-x64.AppImage`], + }; + for (const file of platformFiles[filename]) { + if (!manifest.files.some((entry) => decodeURIComponent(entry.url) === file)) { + throw new Error(`${filename} is missing updater metadata for ${file}`); + } + } + for (const entry of manifest.files) { + const basename = decodeURIComponent(entry.url); + if (basename !== path.basename(basename) || !files.includes(basename)) { + throw new Error(`${filename} references a missing artifact: ${entry.url}`); + } + const file = path.join(directory, basename); + if ( + (await checksum(file, "sha512", "base64")) !== entry.sha512 || + (await stat(file)).size !== entry.size + ) { + throw new Error(`${filename} has an incorrect checksum or size for ${basename}`); + } + } + } + const checksums = await Promise.all( + files + .filter((file) => /\.(dmg|zip|exe|AppImage|blockmap|yml)$/.test(file)) + .sort() + .map( + async (file) => + `${await checksum(path.join(directory, file), "sha256", "hex")} ${file}`, + ), + ); + await writeFile(path.join(directory, "SHA256SUMS.txt"), `${checksums.join("\n")}\n`); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await validateArtifacts(process.argv[2], process.argv[3]); + console.log("All platform installers and updater manifests verified."); +} diff --git a/scripts/releases/local.mjs b/scripts/releases/local.mjs new file mode 100644 index 0000000..539231f --- /dev/null +++ b/scripts/releases/local.mjs @@ -0,0 +1,62 @@ +import {spawnSync} from "node:child_process"; +import {readFile} from "node:fs/promises"; +import path from "node:path"; +import {fileURLToPath} from "node:url"; + +const root = fileURLToPath(new URL("../../", import.meta.url)); +const npm = process.env.npm_execpath; +const output = path.join(root, "dist/local-preview"); +const {version} = JSON.parse(await readFile(path.join(root, "package.json"), "utf8")); + +function run(command, args, options = {}) { + const result = spawnSync(command, args, {cwd: root, stdio: "inherit", ...options}); + if (result.error) throw result.error; + if (result.status !== 0) process.exit(result.status || 1); +} + +// A local preview never publishes or requires distribution signing credentials. +run(process.execPath, [npm, "ci"], {cwd: path.join(root, "showcode")}); +run(process.execPath, [npm, "ci"]); +run(process.execPath, [npm, "run", "generate"]); +run(process.execPath, [npm, "test"]); +// Use the API so electron-builder.env cannot inject distribution credentials. +for (const name of [ + "CSC_LINK", + "CSC_KEY_PASSWORD", + "CSC_INSTALLER_LINK", + "CSC_INSTALLER_KEY_PASSWORD", + "CSC_KEYCHAIN", + "WIN_CSC_LINK", + "WIN_CSC_KEY_PASSWORD", +]) { + delete process.env[name]; +} +process.env.CSC_IDENTITY_AUTO_DISCOVERY = "false"; +const {build, Platform, Arch} = await import("electron-builder"); +await build({ + projectDir: root, + targets: Platform.current().createTarget(["dir"], Arch[process.arch]), + publish: "never", + config: { + directories: {output}, + extraMetadata: {version: `${version}-local.0`}, + mac: {identity: "-", notarize: false}, + }, +}); + +const directory = path.join( + output, + process.platform === "darwin" + ? process.arch === "arm64" + ? "mac-arm64" + : "mac" + : process.platform === "win32" + ? "win-unpacked" + : "linux-unpacked", +); +console.log(`Local preview: ${directory}`); +if (process.argv.includes("--no-open")) process.exit(0); +if (process.platform === "darwin") run("open", [path.join(directory, "Showcode.app")]); +else if (process.platform === "win32") + run(path.join(directory, "Showcode.exe"), [], {detached: true, stdio: "ignore"}); +else console.log(`Run ${path.join(directory, "showcode")} to open the preview.`); diff --git a/scripts/releases/prepare.mjs b/scripts/releases/prepare.mjs new file mode 100644 index 0000000..9f3479b --- /dev/null +++ b/scripts/releases/prepare.mjs @@ -0,0 +1,44 @@ +import {readFile, writeFile, mkdir} from "node:fs/promises"; +import path from "node:path"; +import {pathToFileURL} from "node:url"; + +export async function prepareDesktopRelease(root, previousRef, rendererRef) { + const directory = path.join(root, ".release"); + const release = JSON.parse(await readFile(path.join(directory, "metadata.json"), "utf8")); + const pkg = JSON.parse(await readFile(path.join(root, "package.json"), "utf8")); + if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(release.version)) { + throw new Error("A stable release version is required."); + } + const compare = release.version.localeCompare(pkg.version, "en", {numeric: true}); + if (compare < 0 || (compare === 0 && previousRef !== rendererRef)) { + throw new Error( + "New renderer changes require a new release version. Prepare a release in Showcode first.", + ); + } + for (const filename of ["package.json", "package-lock.json"]) { + const file = path.join(root, filename); + const source = await readFile(file, "utf8"); + const data = JSON.parse(source); + data.version = release.version; + if (filename === "package-lock.json") data.packages[""].version = release.version; + const indentation = source.match(/\n( +)"/)?.[1].length ?? 4; + await writeFile(file, `${JSON.stringify(data, null, indentation)}\n`); + } + await writeReleaseNotes(root, release); + return release.version; +} + +export async function writeReleaseNotes(root, release) { + await mkdir(path.join(root, ".release"), {recursive: true}); + await writeFile( + path.join(root, ".release/notes.md"), + `# ${release.title}\n\n${release.description}\n\n${release.content}\n`, + ); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const version = await prepareDesktopRelease(process.cwd(), process.argv[2], process.argv[3]); + if (process.env.GITHUB_OUTPUT) + await writeFile(process.env.GITHUB_OUTPUT, `version=${version}\n`, {flag: "a"}); + console.log(`Prepared desktop release ${version}`); +} diff --git a/tests/releaseAutomation.test.js b/tests/releaseAutomation.test.js new file mode 100644 index 0000000..3d8da34 --- /dev/null +++ b/tests/releaseAutomation.test.js @@ -0,0 +1,93 @@ +import assert from "node:assert/strict"; +import {createHash} from "node:crypto"; +import {mkdtemp, mkdir, readFile, writeFile, rm} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import {test} from "node:test"; +import {stringify} from "yaml"; +import {prepareDesktopRelease} from "../scripts/releases/prepare.mjs"; +import {validateArtifacts} from "../scripts/releases/artifacts.mjs"; + +test("desktop releases update both versions and reuse the approved notes", async (t) => { + const root = await mkdtemp(path.join(os.tmpdir(), "showcode-desktop-release-")); + t.after(() => rm(root, {recursive: true, force: true})); + await mkdir(path.join(root, ".release")); + await writeFile( + path.join(root, ".release/metadata.json"), + JSON.stringify({ + version: "3.0.1", + title: "Smoother editing", + description: "Small improvements.", + content: "**Fixed**\n\n- Editor transitions.", + }), + ); + await writeFile(path.join(root, "package.json"), JSON.stringify({version: "3.0.0"})); + await writeFile( + path.join(root, "package-lock.json"), + JSON.stringify({version: "3.0.0", packages: {"": {version: "3.0.0"}}}), + ); + + assert.equal(await prepareDesktopRelease(root, "old", "approved"), "3.0.1"); + assert.equal(JSON.parse(await readFile(path.join(root, "package.json"))).version, "3.0.1"); + assert.equal( + JSON.parse(await readFile(path.join(root, "package-lock.json"))).packages[""].version, + "3.0.1", + ); + assert.match( + await readFile(path.join(root, ".release/notes.md"), "utf8"), + /# Smoother editing\n\nSmall improvements\.\n\n\*\*Fixed\*\*/, + ); + assert.equal(await prepareDesktopRelease(root, "approved", "approved"), "3.0.1"); + await assert.rejects( + prepareDesktopRelease(root, "approved", "different"), + /new release version/, + ); +}); + +test("desktop releases cannot downgrade the packaged version", async (t) => { + const root = await mkdtemp(path.join(os.tmpdir(), "showcode-desktop-downgrade-")); + t.after(() => rm(root, {recursive: true, force: true})); + await mkdir(path.join(root, ".release")); + await writeFile(path.join(root, ".release/metadata.json"), JSON.stringify({version: "3.0.9"})); + await writeFile(path.join(root, "package.json"), JSON.stringify({version: "3.0.10"})); + await assert.rejects(prepareDesktopRelease(root, "same", "same"), /new release version/); + assert.equal(JSON.parse(await readFile(path.join(root, "package.json"))).version, "3.0.10"); +}); + +test("release validation requires all platforms and verifies updater hashes before upload", async (t) => { + const root = await mkdtemp(path.join(os.tmpdir(), "showcode-artifacts-")); + t.after(() => rm(root, {recursive: true, force: true})); + const filenames = [ + "Showcode-3.0.1-mac-arm64.dmg", + "Showcode-3.0.1-mac-x64.dmg", + "Showcode-3.0.1-mac-arm64.zip", + "Showcode-3.0.1-mac-x64.zip", + "Showcode-3.0.1-win-x64.exe", + "Showcode-3.0.1-linux-x64.AppImage", + ]; + for (const file of filenames) await writeFile(path.join(root, file), file); + const entry = (file) => ({ + url: file, + size: Buffer.byteLength(file), + sha512: createHash("sha512").update(file).digest("base64"), + }); + for (const [manifest, assets] of [ + ["latest-mac.yml", filenames.slice(0, 4)], + ["latest.yml", [filenames[4]]], + ["latest-linux.yml", [filenames[5]]], + ]) + await writeFile( + path.join(root, manifest), + stringify({version: "3.0.1", files: assets.map(entry)}), + ); + + await validateArtifacts(root, "3.0.1"); + assert.match( + await readFile(path.join(root, "SHA256SUMS.txt"), "utf8"), + /Showcode-3\.0\.1-mac-arm64\.zip/, + ); + await writeFile(path.join(root, filenames[4]), "corrupted installer"); + await assert.rejects(validateArtifacts(root, "3.0.1"), /incorrect checksum or size/); + await rm(path.join(root, filenames[0])); + await assert.rejects(validateArtifacts(root, "3.0.1"), /Missing release artifact/); +}); diff --git a/tests/updater.test.js b/tests/updater.test.js index ee9e001..7d39d27 100644 --- a/tests/updater.test.js +++ b/tests/updater.test.js @@ -4,6 +4,7 @@ import {beforeEach, mock, test} from "node:test"; const app = new EventEmitter(); app.whenReady = async () => {}; +app.getVersion = () => "3.0.0"; const powerMonitor = new EventEmitter(); const autoUpdater = new EventEmitter(); autoUpdater.checkForUpdates = mock.fn(); @@ -31,6 +32,7 @@ beforeEach(() => { powerMonitor.removeAllListeners(); autoUpdater.removeAllListeners(); app.isPackaged = true; + app.getVersion = () => "3.0.0"; winHandler.quitting = false; autoUpdater.checkForUpdates.mock.resetCalls(); autoUpdater.checkForUpdates.mock.mockImplementation(async () => { @@ -44,6 +46,17 @@ beforeEach(() => { winHandler.browserWindow.setProgressBar.mock.resetCalls(); }); +test("local preview builds never check for or install production updates", async (t) => { + t.mock.timers.enable({apis: ["setTimeout"]}); + app.getVersion = () => "3.0.1-local.0"; + const {checkForUpdates} = await import("../main/updater.js?local-preview"); + t.mock.timers.tick(10 * 60 * 1000); + await new Promise(setImmediate); + await checkForUpdates({notifyIfCurrent: true}); + assert.equal(autoUpdater.checkForUpdates.mock.callCount(), 0); + assert.equal(autoUpdater.quitAndInstall.mock.callCount(), 0); +}); + test("packaged apps check after startup and every ten minutes without current-version dialogs", async (t) => { t.mock.timers.enable({apis: ["setTimeout"]}); await import("../main/updater.js?startup");