diff --git a/CHANGELOG.md b/CHANGELOG.md index 6df5940..c185d45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +## [0.2.7] - unreleased + +Release date will be set at publish time. + +### Fixed +- Align update-manifest URLs with uploaded asset filenames for KeepMind and Corp on macOS and Windows (#16). +- Guard both editions with real electron-builder macro expansion for macOS DMG/ZIP and Windows NSIS names, plus post-build exact filename, size and SHA-512 manifest validation. + +### Release preparation notes +- Includes `2869b3e` (#16, "fix: align Windows installer names with update manifests"); both builder configs define explicit `artifactName` for macOS, NSIS and Linux. +- Both desktop editions use the root package version 0.2.7. The Corp server version (`corp/lib.mjs`, 0.8.0) and the standalone MCP package (`tools/package.json`, 0.1.1) are versioned separately and stay unchanged. + ### Added - Project continuity in the desktop app, native chat and bundled MCP: versioned objectives, decisions, alternatives, attempts, artifacts, expected/observed outcomes and questions. - Evidence digests, changed/unavailable source checks, dependent artifact impacts, human review history and usefulness feedback. diff --git a/package-lock.json b/package-lock.json index 1b964f7..584fbd1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "keepmind", - "version": "0.2.6", + "version": "0.2.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "keepmind", - "version": "0.2.6", + "version": "0.2.7", "license": "MIT", "dependencies": { "@whiskeysockets/baileys": "^6.7.9", diff --git a/package.json b/package.json index 056f51b..5204f5f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "keepmind", - "version": "0.2.6", + "version": "0.2.7", "description": "KeepMind — open-source installable second brain. Connects your apps, remembers everything, learns while you sleep.", "license": "MIT", "main": "./out/main/index.js", @@ -15,6 +15,7 @@ "typecheck": "tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.web.json", "dist": "electron-vite build && electron-builder", "test": "vitest run", + "check:update-manifests": "node scripts/check-update-manifests.mjs", "check:release-gates": "node scripts/check-release-gates.mjs", "corp": "node corp/server.mjs", "corp:build-brain": "vite build --config vite.corp.config.mts", diff --git a/scripts/check-update-manifests.mjs b/scripts/check-update-manifests.mjs new file mode 100644 index 0000000..fd8737c --- /dev/null +++ b/scripts/check-update-manifests.mjs @@ -0,0 +1,47 @@ +import { createReadStream } from 'node:fs' +import { readdir, readFile, stat } from 'node:fs/promises' +import { createHash } from 'node:crypto' +import { resolve, join } from 'node:path' +import { pathToFileURL } from 'node:url' +import yaml from 'js-yaml' + +export async function checkUpdateManifests(distDir) { + const names = await readdir(distDir) + const manifests = names.filter(name => /^latest.*\.yml$/.test(name)) + if (!manifests.length) throw new Error(`No latest*.yml manifests in ${distDir}`) + for (const manifest of manifests) { + const data = yaml.load(await readFile(join(distDir, manifest), 'utf8')) + const fail = message => { throw new Error(`${manifest}: ${message}`) } + if (!data || !Array.isArray(data.files) || !data.files.length) fail('missing files entries') + const verify = async (name, size, sha512) => { + if (typeof name !== 'string' || !/^[A-Za-z0-9._-]+$/.test(name) || name === '.' || name === '..') fail(`unsafe asset name: ${JSON.stringify(name)}`) + if (!names.includes(name)) fail(`exact asset filename missing: ${name}`) + const info = await stat(join(distDir, name)) + if (!info.isFile()) fail(`asset is not a file: ${name}`) + if (!Number.isSafeInteger(size) || size < 0 || info.size !== size) fail(`size mismatch for ${name}: manifest ${size}, actual ${info.size}`) + const hash = createHash('sha512') + for await (const chunk of createReadStream(join(distDir, name))) hash.update(chunk) + if (typeof sha512 !== 'string' || hash.digest('base64') !== sha512) fail(`sha512 mismatch for ${name}`) + } + for (const file of data.files) { + if (!file || typeof file !== 'object') fail('invalid files entry') + await verify(file.url, file.size, file.sha512) + } + if (data.path !== undefined) { + const entry = data.files.find(file => file.url === data.path) + if (!entry) fail(`path has no matching files entry: ${data.path}`) + await verify(data.path, data.size ?? entry.size, data.sha512) + } + } + return manifests.length +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + try { + if (!process.argv[2]) throw new Error('Usage: node scripts/check-update-manifests.mjs ') + console.log(`Validated ${await checkUpdateManifests(process.argv[2])} update manifest(s)`) + } catch (error) { + console.error(`Update manifest check failed: ${error.message}`) + process.exitCode = 1 + } +} diff --git a/scripts/packaged-mac-smoke.mjs b/scripts/packaged-mac-smoke.mjs index f23d232..f0d58d9 100644 --- a/scripts/packaged-mac-smoke.mjs +++ b/scripts/packaged-mac-smoke.mjs @@ -16,11 +16,11 @@ async function identity(page){return edition==='personal'?page.evaluate(()=>wind try{ let page=await launch();await page.screenshot({path:join(out,'01-open.png')});if(edition==='personal'){assert(page.url().startsWith('file:'),'Wrong personal entrypoint');await page.evaluate(()=>window.sb.authRegister('fixture@example.invalid','synthetic-password','Test'))}else{assert(page.url().startsWith('http://127.0.0.1:'),'Wrong Corp entrypoint');const setup=await page.evaluate(async()=>{const r=await fetch('/api/setup',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({orgName:'Synthetic Org',name:'Test',email:'fixture@example.invalid',password:'synthetic-password',confirm:'synthetic-password'})});return{status:r.status,body:await r.json()}});assert(setup.status===201,'Corp setup failed '+JSON.stringify(setup));await main.eval("process.mainModule.require('electron').session.defaultSession.cookies.flushStore()")} let account=await identity(page);assert(account.user?.email==='fixture@example.invalid','Account setup failed');const userId=account.user.id;log('Packaged opening and synthetic account creation');await stop();rmSync(target,{recursive:true});install();page=await launch();account=await identity(page);assert(account.user?.id===userId,'Reinstall lost session/account');assert(readFileSync(sentinel,'utf8')==='preserve synthetic data','Reinstall lost data');log('Removal/reinstall preserves account, session and data');await page.screenshot({path:join(out,'02-reinstalled.png')}); -const fixture=join(root,'fixture');mkdirSync(fixture);const newApp=join(fixture,name+'.app');cpSync(target,newApp,{recursive:true});writeFileSync(join(newApp,'Contents/Resources/update-proof'),'new-build');const archive=join(root,'update.zip');execFileSync('ditto',['-c','-k','--sequesterRsrc','--keepParent',newApp,archive]);const content=readFileSync(archive),digest='sha256:'+createHash('sha256').update(content).digest('hex'),assetName=edition==='corp'?`KeepMind-Corp-0.2.6-${process.arch}-mac.zip`:`KeepMind-SB-0.2.6-${process.arch}-mac.zip`,repo=edition==='corp'?'keepmind-corp':'keepmind'; +const fixture=join(root,'fixture');mkdirSync(fixture);const newApp=join(fixture,name+'.app');cpSync(target,newApp,{recursive:true});writeFileSync(join(newApp,'Contents/Resources/update-proof'),'new-build');const archive=join(root,'update.zip');execFileSync('ditto',['-c','-k','--sequesterRsrc','--keepParent',newApp,archive]);const content=readFileSync(archive),digest='sha256:'+createHash('sha256').update(content).digest('hex'),assetName=edition==='corp'?`KeepMind-Corp-0.2.7-${process.arch}-mac.zip`:`KeepMind-SB-0.2.7-${process.arch}-mac.zip`,repo=edition==='corp'?'keepmind-corp':'keepmind'; server=createServer((req,res)=>{if(req.url==='/meta'){res.setHeader('Content-Type','application/json');res.end(JSON.stringify({updated_at:'fixture-new-build',assets:[{name:assetName,digest,size:content.length,browser_download_url:`https://github.com/criptogus/${repo}/releases/download/continuous/${assetName}`}]}))}else if(req.url==='/archive'){res.setHeader('Content-Length',String(content.length));createReadStream(archive).pipe(res)}else{res.writeHead(404);res.end()}});await new Promise(r=>server.listen(0,'127.0.0.1',r));const origin=`http://127.0.0.1:${server.address().port}`; writeFileSync(join(profile,'continuous-state.json'),JSON.stringify({seen:'old-build'})); await main.eval(`globalThis.auditElectron=process.mainModule.require('electron');globalThis.auditFetch=auditOriginalFetch;auditElectron.net.fetch=(url,opts)=>auditFetch(${JSON.stringify(origin)}+(String(url).includes('api.github.com')?'/meta':'/archive'),opts);globalThis.auditFs=process.mainModule.require('fs');globalThis.auditDir=auditElectron.app.getAppPath()+'/out/main/chunks';globalThis.auditModule=auditFs.readdirSync(auditDir).find(f=>auditFs.readFileSync(auditDir+'/'+f,'utf8').includes('exports.checkForUpdates'));globalThis.auditUpdater=process.mainModule.require(auditDir+'/'+auditModule);auditUpdater.initUpdater({edition:${JSON.stringify(edition)}});`); -let downloaded=await main.eval('auditUpdater.checkForUpdates()');for(let i=0;downloaded.busy&&i<600;i++){await sleep(200);downloaded=await main.eval('auditUpdater.checkForUpdates()')}assert(downloaded.continuous==='0.2.6','Download failed '+JSON.stringify(downloaded));log('Real updater downloads and verifies controlled archive');const oldPort=readFileSync(join(profile,'DevToolsActivePort'),'utf8');assert(await main.eval('auditUpdater.installUpdate()'),'Installer refused');main.ws.close();main=undefined;await browser.close().catch(()=>{});browser=undefined; +let downloaded=await main.eval('auditUpdater.checkForUpdates()');for(let i=0;downloaded.busy&&i<600;i++){await sleep(200);downloaded=await main.eval('auditUpdater.checkForUpdates()')}assert(downloaded.continuous==='0.2.7','Download failed '+JSON.stringify(downloaded));log('Real updater downloads and verifies controlled archive');const oldPort=readFileSync(join(profile,'DevToolsActivePort'),'utf8');assert(await main.eval('auditUpdater.installUpdate()'),'Installer refused');main.ws.close();main=undefined;await browser.close().catch(()=>{});browser=undefined; for(let i=0;i<300;i++){if(existsSync(join(target,'Contents/Resources/update-proof'))&&readNewDebugPort(join(profile,'DevToolsActivePort'),oldPort)!==null)break;await sleep(200)} assert(existsSync(join(target,'Contents/Resources/update-proof')),'Updated bundle was not installed');const port=readNewDebugPort(join(profile,'DevToolsActivePort'),oldPort);assert(port,'Relaunched debugging endpoint is not ready');browser=await chromium.connectOverCDP('http://127.0.0.1:'+port);page=browser.contexts()[0].pages()[0] ?? await browser.contexts()[0].waitForEvent('page',{timeout:45000});await page.waitForFunction(()=>document.body?.innerText.trim().length>0);account=await identity(page);assert(account.user?.id===userId,'Update lost session/account');assert(readFileSync(sentinel,'utf8')==='preserve synthetic data','Update lost profile data');assert(existsSync(target+'.previous'),'Missing recovery bundle');assert(!existsSync(join(profile,'update/pending.json')),'Update receipt not committed');log('Automatic swap/relaunch preserves account, session and data');await page.screenshot({path:join(out,'03-updated.png')}); // Stop only our relaunched disposable application via its own isolated process path. diff --git a/scripts/packaged-platform-smoke.mjs b/scripts/packaged-platform-smoke.mjs index c473b5b..8797404 100644 --- a/scripts/packaged-platform-smoke.mjs +++ b/scripts/packaged-platform-smoke.mjs @@ -13,7 +13,7 @@ async function stop(){if(main){void main.eval("process.mainModule.require('elect const identity=p=>edition==='personal'?p.evaluate(()=>window.sb.authState()):p.evaluate(async()=>await(await fetch('/api/session')).json()); try{install();let page=await launch();await page.screenshot({path:join(out,'01-open.png')});if(edition==='personal')await page.evaluate(()=>window.sb.authRegister('fixture@example.invalid','synthetic-password','Test'));else{const status=await page.evaluate(async()=>{const r=await fetch('/api/setup',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({orgName:'Fixture',name:'Test',email:'fixture@example.invalid',password:'synthetic-password',confirm:'synthetic-password'})});return r.status});assert(status===201,'Corp setup failed');await main.eval("process.mainModule.require('electron').session.defaultSession.cookies.flushStore()")};const account=await identity(page),id=account.user?.id;assert(id,'Missing account');writeFileSync(join(profile,'sentinel'),'preserve');log('Native installation, opening and synthetic account creation');await stop(); if(win){const uninstaller=join(target,`Uninstall ${name}.exe`);assert(existsSync(uninstaller),'Missing native uninstaller');execFileSync(uninstaller,['/S'],{env,timeout:180000});await sleep(3000)}else rmSync(target);install();page=await launch();assert((await identity(page)).user?.id===id,'Reinstall lost account/session');log('Uninstall/reinstall preserves account and session'); -const artifact=readFileSync(resolve(source)),digest='sha256:'+createHash('sha256').update(artifact).digest('hex'),prefix=edition==='corp'?'KeepMind-Corp':'KeepMind-SB',assetName=win?`${prefix}-Setup-0.2.6.exe`:`${prefix}-0.2.6.AppImage`,repo=edition==='corp'?'keepmind-corp':'keepmind';server=createServer((req,res)=>{if(req.url==='/meta'){res.setHeader('Content-Type','application/json');res.end(JSON.stringify({updated_at:'fixture-new',assets:[{name:assetName,digest,size:artifact.length,browser_download_url:`https://github.com/criptogus/${repo}/releases/download/continuous/${assetName}`}]}))}else{res.setHeader('Content-Length',String(artifact.length));createReadStream(resolve(source)).pipe(res)}});await new Promise(r=>server.listen(0,'127.0.0.1',r));const origin=`http://127.0.0.1:${server.address().port}`;writeFileSync(join(profile,'continuous-state.json'),JSON.stringify({seen:'old'})); -await main.eval(`globalThis.auditElectron=process.mainModule.require('electron');globalThis.auditFetch=auditOriginalFetch;auditElectron.net.fetch=(url,opts)=>auditFetch(${JSON.stringify(origin)}+(String(url).includes('api.github.com')?'/meta':'/archive'),opts);globalThis.auditFs=process.mainModule.require('fs');globalThis.auditDir=auditElectron.app.getAppPath()+'/out/main/chunks';globalThis.auditModule=auditFs.readdirSync(auditDir).find(f=>auditFs.readFileSync(auditDir+'/'+f,'utf8').includes('exports.checkForUpdates'));globalThis.auditUpdater=process.mainModule.require(auditDir+'/'+auditModule);auditUpdater.initUpdater({edition:${JSON.stringify(edition)}});`);let downloaded=await main.eval('auditUpdater.checkForUpdates()');for(let i=0;downloaded.busy&&i<600;i++){await sleep(200);downloaded=await main.eval('auditUpdater.checkForUpdates()')}assert(downloaded.continuous==='0.2.6','Update download failed '+JSON.stringify(downloaded));log('Real updater downloads and verifies installer');const oldPort=readFileSync(join(profile,'DevToolsActivePort'),'utf8');assert(await main.eval('auditUpdater.installUpdate()'),'Installer refused');main.ws.close();main=undefined;await browser.close().catch(()=>{});browser=undefined; +const artifact=readFileSync(resolve(source)),digest='sha256:'+createHash('sha256').update(artifact).digest('hex'),prefix=edition==='corp'?'KeepMind-Corp':'KeepMind-SB',assetName=win?`${prefix}-Setup-0.2.7.exe`:`${prefix}-0.2.7.AppImage`,repo=edition==='corp'?'keepmind-corp':'keepmind';server=createServer((req,res)=>{if(req.url==='/meta'){res.setHeader('Content-Type','application/json');res.end(JSON.stringify({updated_at:'fixture-new',assets:[{name:assetName,digest,size:artifact.length,browser_download_url:`https://github.com/criptogus/${repo}/releases/download/continuous/${assetName}`}]}))}else{res.setHeader('Content-Length',String(artifact.length));createReadStream(resolve(source)).pipe(res)}});await new Promise(r=>server.listen(0,'127.0.0.1',r));const origin=`http://127.0.0.1:${server.address().port}`;writeFileSync(join(profile,'continuous-state.json'),JSON.stringify({seen:'old'})); +await main.eval(`globalThis.auditElectron=process.mainModule.require('electron');globalThis.auditFetch=auditOriginalFetch;auditElectron.net.fetch=(url,opts)=>auditFetch(${JSON.stringify(origin)}+(String(url).includes('api.github.com')?'/meta':'/archive'),opts);globalThis.auditFs=process.mainModule.require('fs');globalThis.auditDir=auditElectron.app.getAppPath()+'/out/main/chunks';globalThis.auditModule=auditFs.readdirSync(auditDir).find(f=>auditFs.readFileSync(auditDir+'/'+f,'utf8').includes('exports.checkForUpdates'));globalThis.auditUpdater=process.mainModule.require(auditDir+'/'+auditModule);auditUpdater.initUpdater({edition:${JSON.stringify(edition)}});`);let downloaded=await main.eval('auditUpdater.checkForUpdates()');for(let i=0;downloaded.busy&&i<600;i++){await sleep(200);downloaded=await main.eval('auditUpdater.checkForUpdates()')}assert(downloaded.continuous==='0.2.7','Update download failed '+JSON.stringify(downloaded));log('Real updater downloads and verifies installer');const oldPort=readFileSync(join(profile,'DevToolsActivePort'),'utf8');assert(await main.eval('auditUpdater.installUpdate()'),'Installer refused');main.ws.close();main=undefined;await browser.close().catch(()=>{});browser=undefined; for(let i=0;i<900;i++){if(!existsSync(join(profile,'update/pending.json'))&&readNewDebugPort(join(profile,'DevToolsActivePort'),oldPort)!==null)break;await sleep(200)}assert(!existsSync(join(profile,'update/pending.json')),'Update helper did not complete');const port=readNewDebugPort(join(profile,'DevToolsActivePort'),oldPort);assert(port,'Relaunched debugging endpoint is not ready');browser=await chromium.connectOverCDP('http://127.0.0.1:'+port);const context=browser.contexts()[0];page=context.pages()[0]??await context.waitForEvent('page',{timeout:45000});await page.waitForFunction(()=>document.body?.innerText.trim().length>0);assert((await identity(page)).user?.id===id,'Update lost account/session');assert(readFileSync(join(profile,'sentinel'),'utf8')==='preserve','Update lost profile data');log('Native automatic update and relaunch preserve data and session');await page.screenshot({path:join(out,'03-updated.png')});writeFileSync(join(out,'report.json'),JSON.stringify({edition,platform:process.platform,root,checks,passed:checks.length,failed:0,scope:'Packaged source build; controlled update feed'},null,2)); }catch(error){for(const file of ['install.ps1','install.log','helper.log','swap.sh']){const path=join(profile,'update',file);if(existsSync(path))cpSync(path,join(out,file))}if(win){try{writeFileSync(join(out,'processes.json'),execFileSync('powershell.exe',['-NoProfile','-Command',"Get-CimInstance Win32_Process | Where-Object {$_.Name -match 'KeepMind|powershell'} | Select-Object Name,ProcessId,ParentProcessId,CommandLine | ConvertTo-Json"],{encoding:'utf8'}))}catch{}}writeFileSync(join(out,'report.json'),JSON.stringify({edition,platform:process.platform,root,checks,failed:1,error:String(error)},null,2));throw error}finally{await stop();server?.close();if(win){try{execFileSync('powershell.exe',['-NoProfile','-Command',`Get-Process | Where-Object {$_.Path -eq '${exe.replaceAll("'","''")}'} | Stop-Process -Force`])}catch{}}} diff --git a/tests/check-update-manifests.test.ts b/tests/check-update-manifests.test.ts new file mode 100644 index 0000000..c0992aa --- /dev/null +++ b/tests/check-update-manifests.test.ts @@ -0,0 +1,46 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { mkdtempSync, writeFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createHash } from 'node:crypto' +import { checkUpdateManifests } from '../scripts/check-update-manifests.mjs' +import { createRequire } from 'node:module' +const { dump } = createRequire(import.meta.url)('js-yaml') +const dirs: string[] = [] +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) }) +function fixture(options: { actual?: string; url?: string; size?: number; sha512?: string; path?: string; legacySha?: string } = {}) { + const dir = mkdtempSync(join(tmpdir(), 'keepmind-manifest-')); dirs.push(dir) + const bytes = Buffer.from('installer fixture') + const url = options.url ?? 'KeepMind-SB-Setup-0.2.7.exe' + const sha512 = createHash('sha512').update(bytes).digest('base64') + writeFileSync(join(dir, options.actual ?? url), bytes) + const manifest = { files: [{ url, size: options.size ?? bytes.length, sha512: options.sha512 ?? sha512 }], path: options.path ?? url, sha512: options.legacySha ?? sha512 } + for (const name of ['latest.yml', 'latest-mac.yml']) writeFileSync(join(dir, name), dump(manifest)) + return dir +} +describe('post-build update manifest checker', () => { + it('accepts exact names, sizes and base64 SHA-512 in every manifest', async () => { + await expect(checkUpdateManifests(fixture())).resolves.toBe(2) + }) + it.each([ + ['KeepMind-Setup-0.2.6.exe', 'KeepMind.Setup.0.2.6.exe'], + ['KeepMind-Corp-0.2.6-arm64.dmg', 'KeepMind.Corp-0.2.6-arm64.dmg'], + ['KeepMind-Corp-Setup-0.2.6.exe', 'KeepMind.Corp.Setup.0.2.6.exe'] + ])('rejects historical manifest %s when GitHub uploaded %s', async (url, actual) => { + await expect(checkUpdateManifests(fixture({ url, actual }))).rejects.toThrow('exact asset filename missing') + }) + it.each([ + [{ size: 1 }, 'size mismatch'], + [{ sha512: 'wrong' }, 'sha512 mismatch'], + [{ legacySha: 'wrong' }, 'sha512 mismatch'], + [{ path: 'missing.exe' }, 'path has no matching'], + [{ url: 'KeepMind Setup.exe' }, 'unsafe asset name'], + [{ url: 'KeepMind+Setup.exe' }, 'unsafe asset name'] + ] as const)('rejects invalid metadata %j', async (options, message) => { + await expect(checkUpdateManifests(fixture(options))).rejects.toThrow(message) + }) + it('rejects a directory without manifests', async () => { + const dir = fixture(); rmSync(join(dir, 'latest.yml')); rmSync(join(dir, 'latest-mac.yml')) + await expect(checkUpdateManifests(dir)).rejects.toThrow('No latest*.yml') + }) +}) diff --git a/tests/release-artifact-names.test.ts b/tests/release-artifact-names.test.ts index a244715..b88219c 100644 --- a/tests/release-artifact-names.test.ts +++ b/tests/release-artifact-names.test.ts @@ -10,16 +10,35 @@ const { NsisTarget } = require('app-builder-lib/out/targets/nsis/NsisTarget') const defaultPattern = Object.getOwnPropertyDescriptor(NsisTarget.prototype, 'installerFilenamePattern')!.get!.call({ isPortable: false }) const expand = (pattern: string, productName: string) => expandMacro(pattern, 'x64', { productName, version: '0.2.6' }, { ext: 'exe' }, false) -describe('Windows installer names used by external GitHub publication', () => { +describe('Artifact names used by external GitHub publication', () => { it('reproduces the default NSIS filename/manifest mismatch', () => { const filename = expand(defaultPattern, 'KeepMind') expect(filename).toBe('KeepMind Setup 0.2.6.exe') expect(computeSafeArtifactNameIfNeeded(filename, () => '')).toBe('KeepMind-Setup-0.2.6.exe') }) - it.each(['electron-builder.yml', 'electron-builder.corp.yml'])('%s produces the same on-disk and update-manifest filename', file => { + const version = JSON.parse(readFileSync('package.json', 'utf8')).version + for (const file of ['electron-builder.yml', 'electron-builder.corp.yml']) { const config = load(readFileSync(file, 'utf8')) - const filename = expand(config.nsis?.artifactName ?? defaultPattern, config.productName) - expect(filename).toMatch(/^[A-Za-z0-9._-]+\.exe$/) - expect(computeSafeArtifactNameIfNeeded(filename, () => '')).toBeNull() - }) + for (const platform of ['mac', 'win']) { + for (const targetEntry of config[platform].target) { + const target = typeof targetEntry === 'string' ? targetEntry : targetEntry.target + const arches = new Set(['arm64', 'x64', ...(platform === 'mac' ? ['universal'] : []), ...(targetEntry.arch ?? [])]) + const ext = target === 'nsis' ? 'exe' : target + const pattern = config[target]?.artifactName ?? config[platform]?.artifactName + for (const arch of arches) { + it(`${file}: ${target}/${arch} has an explicit GitHub-safe artifact name`, () => { + expect(pattern).toBeTypeOf('string') + expect(pattern.length).toBeGreaterThan(0) + const filename = expandMacro(pattern, arch, { + productName: config.productName, sanitizedProductName: config.productName, + name: 'keepmind', version + }, { ext, os: platform }, true) + expect(filename).toMatch(/^[A-Za-z0-9._-]+$/) + expect(filename.endsWith(`.${ext}`)).toBe(true) + expect(computeSafeArtifactNameIfNeeded(filename, () => '')).toBeNull() + }) + } + } + } + } }) diff --git a/tests/updater-download.test.ts b/tests/updater-download.test.ts index 073cc72..6b00e51 100644 --- a/tests/updater-download.test.ts +++ b/tests/updater-download.test.ts @@ -4,20 +4,20 @@ import { join } from 'node:path' import { tmpdir } from 'node:os' import { createHash } from 'node:crypto' const fake=vi.hoisted(()=>({profile:'',fetch:vi.fn(),send:vi.fn()})) -vi.mock('electron',()=>({app:{isPackaged:true,getPath:()=>fake.profile,getVersion:()=> '0.2.6'},BrowserWindow:{getAllWindows:()=>[{webContents:{send:fake.send}}]},net:{fetch:fake.fetch}})) +vi.mock('electron',()=>({app:{isPackaged:true,getPath:()=>fake.profile,getVersion:()=> '0.2.7'},BrowserWindow:{getAllWindows:()=>[{webContents:{send:fake.send}}]},net:{fetch:fake.fetch}})) vi.mock('electron-updater',()=>({autoUpdater:{on:vi.fn()}})) beforeEach(()=>{vi.resetModules();fake.profile=mkdtempSync(join(tmpdir(),'km-update-'));fake.fetch.mockReset();fake.send.mockReset();writeFileSync(join(fake.profile,'continuous-state.json'),JSON.stringify({seen:'previous-build'}))}) afterEach(()=>{vi.useRealTimers();rmSync(fake.profile,{recursive:true,force:true})}) const bytes=Buffer.from('synthetic update bytes'),digest='sha256:'+createHash('sha256').update(bytes).digest('hex') -const name=process.platform==='darwin'?'KeepMind-0.2.6-universal-mac.zip':process.platform==='win32'?'KeepMind-Setup-0.2.6.exe':'KeepMind-0.2.6.AppImage' +const name=process.platform==='darwin'?'KeepMind-SB-0.2.7-universal-mac.zip':process.platform==='win32'?'KeepMind-SB-Setup-0.2.7.exe':'KeepMind-SB-0.2.7.AppImage' const url='https://github.com/criptogus/keepmind/releases/download/continuous/'+name function responses(body:Buffer){fake.fetch.mockImplementation(async(input:string)=>input.includes('api.github.com')?Response.json({updated_at:'2026-11-13',assets:[{name,browser_download_url:url,digest,size:bytes.length}]}):new Response(body))} it('downloads verified bytes and restores a pending update after restarting without consuming its marker',async()=>{ - responses(bytes);let updater=await import('../src/main/services/updater');expect((await updater.checkForUpdates()).continuous).toBe('0.2.6') + responses(bytes);let updater=await import('../src/main/services/updater');expect((await updater.checkForUpdates()).continuous).toBe('0.2.7') expect(readFileSync(join(fake.profile,'continuous-state.json'),'utf8')).toContain('previous-build') expect(existsSync(join(fake.profile,'update','pending.json'))).toBe(true) vi.resetModules();updater=await import('../src/main/services/updater');fake.fetch.mockClear() - expect((await updater.checkForUpdates()).continuous).toBe('0.2.6');expect(fake.fetch).not.toHaveBeenCalled() + expect((await updater.checkForUpdates()).continuous).toBe('0.2.7');expect(fake.fetch).not.toHaveBeenCalled() }) it('rejects corrupt downloads before offering installation',async()=>{ responses(Buffer.from('tampered'));const updater=await import('../src/main/services/updater');expect((await updater.checkForUpdates()).error).toContain('integrity')