diff --git a/.agents/skills/release-validation/SKILL.md b/.agents/skills/release-validation/SKILL.md index 9e86bb2..16e3859 100644 --- a/.agents/skills/release-validation/SKILL.md +++ b/.agents/skills/release-validation/SKILL.md @@ -14,3 +14,5 @@ Run from the repository root. Never trigger a release or create a tag merely to Use the existing checker and smoke scripts; do not duplicate them. See `docs/RELEASE-VALIDATION.md` for scope and limitations. After a continuous release, check the current commit in the release body, successful validation/build/publish ordering, nonempty uploaded assets, and every `latest*.yml` file URL against the literal published asset name and size. Download manifest files to verify their GitHub digest, and verify installer SHA-512 before repairing a manifest. A green publisher job alone does not prove updater URLs work. Never silently normalize mismatching names; an HTTP 404 is a failure. Record repairs separately from the original workflow run. + +For installer/updater/profile changes, run the packaged lifecycle tests in `docs/INSTALLED-APP-VALIDATION.md`, and inspect the three-platform Installed application lifecycle workflow. Require actual app opening, account/session continuity after reinstall, and successful update/relaunch; checksum-only publication checks are insufficient. Use disposable profiles and installations. Keep production application identity/profile paths stable when changing branding. Never interpret an expired session as a missing account. diff --git a/.github/workflows/continuous.yml b/.github/workflows/continuous.yml index 7a96a45..50ca337 100644 --- a/.github/workflows/continuous.yml +++ b/.github/workflows/continuous.yml @@ -44,7 +44,12 @@ jobs: python-version: '3.11' - run: npm ci - run: npm run typecheck + - name: Prepare Corp resources + if: github.repository == 'criptogus/keepmind-corp' + run: npm run corp:build-brain - run: npm run build + env: + KEEPMIND_EDITION: ${{ github.repository == 'criptogus/keepmind-corp' && 'corp' || '' }} - name: Prune onnxruntime to target platform run: node scripts/prune-onnxruntime.mjs ${{ matrix.onnx }} - name: Drop optional ws natives @@ -55,7 +60,7 @@ jobs: # `ws` falls back to pure JS. Removing them lets the installer publish. run: node -e "const fs=require('fs'); for (const p of ['node_modules/bufferutil','node_modules/utf-8-validate']) fs.rmSync(p,{recursive:true,force:true})" - name: Build installers - run: npx electron-builder ${{ matrix.args }} --publish never + run: npx electron-builder ${{ github.repository == 'criptogus/keepmind-corp' && '--config electron-builder.corp.yml' || '' }} ${{ matrix.args }} --publish never env: CSC_IDENTITY_AUTO_DISCOVERY: false - name: Upload installers @@ -63,12 +68,12 @@ jobs: with: name: dist-${{ matrix.os }} path: | - dist/*.dmg - dist/*.zip - dist/*.exe - dist/*.AppImage - dist/latest*.yml - dist/*.blockmap + ${{ github.repository == 'criptogus/keepmind-corp' && 'dist-corp' || 'dist' }}/*.dmg + ${{ github.repository == 'criptogus/keepmind-corp' && 'dist-corp' || 'dist' }}/*.zip + ${{ github.repository == 'criptogus/keepmind-corp' && 'dist-corp' || 'dist' }}/*.exe + ${{ github.repository == 'criptogus/keepmind-corp' && 'dist-corp' || 'dist' }}/*.AppImage + ${{ github.repository == 'criptogus/keepmind-corp' && 'dist-corp' || 'dist' }}/latest*.yml + ${{ github.repository == 'criptogus/keepmind-corp' && 'dist-corp' || 'dist' }}/*.blockmap if-no-files-found: error publish: diff --git a/.github/workflows/installed-apps.yml b/.github/workflows/installed-apps.yml new file mode 100644 index 0000000..6a815a2 --- /dev/null +++ b/.github/workflows/installed-apps.yml @@ -0,0 +1,65 @@ +name: Installed application lifecycle +on: + pull_request: + paths: + - 'src/main/**' + - 'electron-builder*.yml' + - 'scripts/packaged-*.mjs' + - '.github/workflows/installed-apps.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + installed: + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-2022, ubuntu-latest] + edition: [personal, corp] + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - run: npm ci + - run: npm run corp:build-brain + - run: npm run build + - name: Build native installation fixture + shell: bash + env: + EDITION: ${{ matrix.edition }} + CSC_IDENTITY_AUTO_DISCOVERY: 'false' + run: | + node scripts/prune-onnxruntime.mjs "$(node -p process.platform)" + node -e "for(const p of ['bufferutil','utf-8-validate'])require('fs').rmSync('node_modules/'+p,{recursive:true,force:true})" + config=electron-builder.yml + if [ "$EDITION" = corp ]; then config=electron-builder.corp.yml; fi + case "$RUNNER_OS" in + macOS) npx electron-builder --config "$config" --mac --dir --publish never ;; + Windows) npx electron-builder --config "$config" --win nsis --x64 --publish never ;; + Linux) npx electron-builder --config "$config" --linux AppImage --x64 --publish never ;; + esac + - name: Test real installation and update with disposable profiles + shell: bash + env: + EDITION: ${{ matrix.edition }} + run: | + dir=dist + if [ "$EDITION" = corp ]; then dir=dist-corp; fi + case "$RUNNER_OS" in + macOS) source=$(find "$dir" -maxdepth 2 -name '*.app' -type d | head -1); node scripts/packaged-mac-smoke.mjs "$source" "$EDITION" artifacts/installed ;; + Windows) source=$(find "$dir" -maxdepth 1 -name '*.exe' | head -1); node scripts/packaged-platform-smoke.mjs "$source" "$EDITION" artifacts/installed ;; + Linux) source=$(find "$dir" -maxdepth 1 -name '*.AppImage' | head -1); xvfb-run -a node scripts/packaged-platform-smoke.mjs "$source" "$EDITION" artifacts/installed ;; + esac + - uses: actions/upload-artifact@v4 + if: always() + with: + name: installed-${{ matrix.os }}-${{ matrix.edition }} + path: artifacts/installed/ + if-no-files-found: warn diff --git a/docs/INSTALLED-APP-VALIDATION.md b/docs/INSTALLED-APP-VALIDATION.md new file mode 100644 index 0000000..e620e3c --- /dev/null +++ b/docs/INSTALLED-APP-VALIDATION.md @@ -0,0 +1,33 @@ +# Installed application validation + +KeepMind SB is the personal second-brain application, not KeepMind OS. Its existing internal package name (`keepmind`), bundle identifier (`com.keepmind.app`) and profile directory remain stable. The macOS bundle remains `KeepMind.app` for compatibility with already-installed updaters; its display name, UI and new artifact names identify KeepMind SB. Corp keeps its own identity and profile. + +## Account persistence + +Accounts and sessions belong to the profile, outside the installed app. On macOS the personal default remains `~/Library/Application Support/keepmind`; Corp uses `keepmind-corp`. Replacing or removing the application bundle does not remove these directories. Windows NSIS explicitly retains application data on uninstall. A local SB session expires after 30 days; expiration requires login, not registration. Removing profile data with a cleaner is different from uninstalling the application. No password or account is copied between SB and Corp. + +Explicit `--user-data-dir` and `KEEPMIND_USER_DATA_DIR` profiles survive updater relaunches. Neither changes HOME. Regression tests preserve a synthetic account across app replacement and confirm an expired session leaves the account intact. + +## Publication finding + +The old `continuous.yml` used the personal packaging configuration even inside `keepmind-corp`. Both published macOS 0.2.6 DMGs contained `name: keepmind`, `main: out/main/index.js`. The workflow now chooses the Corp config, builds Corp resources, uploads the correct output folder and includes shared main-process chunks. Corp polls only its own repository and accepts only Corp-prefixed artifacts. + +## Update guarantees and limits + +Downloads require the expected repository, edition-specific filename, positive size and SHA-256 digest. Partial or corrupted downloads are not installable. Pending metadata persists across restart. The macOS helper stages the replacement on the installation volume, keeps the old bundle for recovery, and preserves the profile when launching directly. It does not use LaunchServices to choose another app. Linux requires a real AppImage path and stages a replacement. Windows waits for the old process, installs to its existing directory, checks the installer exit status, then relaunches with the same profile. A receipt is written after replacement, not after download. + +These changes do not add signing/notarization or remote account recovery. Existing unsigned application restrictions still apply. A local source-package smoke is not evidence that a published release contains the fix. + +## Reusable tests + +- `node scripts/packaged-mac-smoke.mjs APP_PATH personal|corp EVIDENCE_DIR`: copy a built app into a fresh temporary installation, create a synthetic account, remove/reinstall the app, then exercise the real updater against a controlled local archive, verifying relaunch, session, sentinel data and recovery bundle. An outer macOS sandbox denies writes to the user's home; Electron's nested sandbox is disabled only for this test process because nested seatbelt sandboxes conflict. +- `node scripts/packaged-platform-smoke.mjs INSTALLER personal|corp EVIDENCE_DIR`: Windows/Linux equivalent, restricted to disposable CI runners. Uses the native NSIS installer/uninstaller or AppImage and preserves a temporary profile. +- `.github/workflows/installed-apps.yml`: builds and tests both editions on macOS, Windows and Linux. Screenshots, reports and process logs are retained as workflow artifacts. + +The fixture feed is injected through the test process's inspector; production builds contain no arbitrary update-server override. Never test update application against a user's installation, account, vault or credentials. Reports distinguish published artifacts from newly packaged source builds. + +## Windows helper startup + +The native regression exposed `powershell.exe` exiting with code 0 before executing its script when launched with Node's `detached` option. A hidden `cmd /c start /b /wait` bootstrap supplies a console and starts PowerShell outside the parent's libuv job. The app waits for a readiness file before quitting; startup failures keep the app open. See [libuv Windows process handling](https://github.com/libuv/libuv/blob/v1.x/src/win/process.c) and the [matching upstream reproduction](https://github.com/oven-sh/bun/issues/31603). Native lifecycle CI exercises the real helper after the parent exits. + +Auth database writes use an atomic replacement and propagate disk errors. Failed mutations restore the in-memory database so a later read cannot silently save a failed registration. The regression verifies both retry and reopen behavior. diff --git a/electron-builder.corp.yml b/electron-builder.corp.yml index ef73175..529d257 100644 --- a/electron-builder.corp.yml +++ b/electron-builder.corp.yml @@ -5,7 +5,7 @@ extends: electron-builder.yml directories: output: dist-corp files: - - out/main/index-corp.js + - out/main/** - package.json - LICENSE - NOTICE @@ -24,18 +24,28 @@ extraResources: - "**/*" - "!data/**" asar: true +publish: + provider: github + owner: criptogus + repo: keepmind-corp mac: + extendInfo: + CFBundleDisplayName: KeepMind Corp + artifactName: KeepMind-Corp-${version}-${arch}-mac.${ext} category: public.app-category.productivity target: - dmg - zip nsis: + uninstallDisplayName: KeepMind Corp + deleteAppDataOnUninstall: false # Keep the physical filename identical to the update manifest and GitHub asset. artifactName: KeepMind-Corp-Setup-${version}.${ext} win: target: - nsis linux: + artifactName: KeepMind-Corp-${version}.${ext} category: Office target: - AppImage diff --git a/electron-builder.yml b/electron-builder.yml index b192371..1478183 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -1,4 +1,5 @@ appId: com.keepmind.app +# Keep the legacy bundle name for compatibility with already-installed updaters. productName: KeepMind icon: build/icon publish: @@ -17,17 +18,23 @@ files: - node_modules/** asar: true mac: + extendInfo: + CFBundleDisplayName: KeepMind SB + artifactName: KeepMind-SB-${version}-${arch}-mac.${ext} category: public.app-category.productivity target: - dmg - zip nsis: + uninstallDisplayName: KeepMind SB + deleteAppDataOnUninstall: false # Keep the physical filename identical to the update manifest and GitHub asset. - artifactName: KeepMind-Setup-${version}.${ext} + artifactName: KeepMind-SB-Setup-${version}.${ext} win: target: - nsis linux: + artifactName: KeepMind-SB-${version}.${ext} category: Utility target: - AppImage diff --git a/scripts/packaged-mac-smoke.mjs b/scripts/packaged-mac-smoke.mjs new file mode 100644 index 0000000..f23d232 --- /dev/null +++ b/scripts/packaged-mac-smoke.mjs @@ -0,0 +1,29 @@ +import { readNewDebugPort } from './packaged-test-support.mjs' +// Runs only disposable copies/profiles. Never launches or edits /Applications. +import {spawn,execFileSync} from 'node:child_process';import {mkdtempSync,mkdirSync,cpSync,writeFileSync,readFileSync,existsSync,rmSync,createReadStream} from 'node:fs';import{join,resolve}from'node:path';import{tmpdir,homedir}from'node:os';import{createHash}from'node:crypto';import{createServer}from'node:http';import{chromium}from'playwright'; +const [source,edition,evidence]=process.argv.slice(2);if(process.platform!=='darwin'||!source||!['personal','corp'].includes(edition)||!evidence)throw Error('Usage on macOS: node scripts/packaged-mac-smoke.mjs APP_PATH personal|corp EVIDENCE_DIR'); +const out=resolve(evidence);mkdirSync(out,{recursive:true});const root=mkdtempSync(join('/private/tmp/','km-installed-')),name=edition==='corp'?'KeepMind Corp':'KeepMind',target=join(root,name+'.app'),profile=join(root,'profile'),install=()=>cpSync(resolve(source),target,{recursive:true});mkdirSync(profile);install(); +const sentinel=join(profile,'user-sentinel');writeFileSync(sentinel,'preserve synthetic data');const checks=[];const sleep=n=>new Promise(r=>setTimeout(r,n));let child,browser,main,server; +const log=check=>{checks.push(check);console.log(check)}; +const assert=(value,message)=>{if(!value)throw Error(message)}; +async function inspector(url){const ws=new WebSocket(url);await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j});let id=0;const pending=new Map();ws.onmessage=e=>{const m=JSON.parse(e.data);if(pending.has(m.id)){pending.get(m.id)(m);pending.delete(m.id)}};ws.onclose=()=>{for(const cb of pending.values())cb({result:{exceptionDetails:{exception:{description:'Inspector closed'}}}});pending.clear()};return{ws,eval:expression=>new Promise((r,j)=>{const key=++id;const timer=setTimeout(()=>j(Error('Inspector timeout')),60000);pending.set(key,m=>{clearTimeout(timer);if(m.result?.exceptionDetails)j(Error(m.result.exceptionDetails.exception?.description));else r(m.result?.result?.value)});ws.send(JSON.stringify({id:key,method:'Runtime.evaluate',params:{expression,awaitPromise:true,returnByValue:true}}))})}} +async function launch(){let stderr='';const policy=`(version 1)(allow default)(deny file-write* (subpath "${homedir()}"))(deny file-read* (subpath "${homedir()}/Library/Application Support") (subpath "${homedir()}/Documents"))`; +child=spawn('/usr/bin/sandbox-exec',['-p',policy,join(target,'Contents/MacOS',name),'--no-sandbox','--disable-gpu',`--user-data-dir=${profile}`,'--remote-debugging-port=0','--inspect=0'],{env:{...process.env,KEEPMIND_USER_DATA_DIR:profile},stdio:['ignore','pipe','pipe']});child.stderr.on('data',d=>{stderr+=d;writeFileSync(join(out,'process.log'),stderr)});child.stdout.on('data',d=>{stderr+=d}); +for(let i=0;i<150&&!stderr.includes('DevTools listening on');i++){assert(child.exitCode===null,'Packaged process exited: '+stderr);await sleep(200)} +const dev=stderr.match(/DevTools listening on (ws:\/\/\S+)/)?.[1],debug=stderr.match(/Debugger listening on (ws:\/\/\S+)/)?.[1];assert(dev&&debug,'Missing packaged debug endpoints: '+stderr);browser=await chromium.connectOverCDP(dev);main=await inspector(debug);await main.eval("globalThis.auditOriginalFetch=process.mainModule.require('electron').net.fetch.bind(process.mainModule.require('electron').net);process.mainModule.require('electron').net.fetch=async()=>new Response(JSON.stringify({assets:[]}))");const actual=await main.eval("process.mainModule.require('electron').app.getPath('userData')");assert(actual===profile,'Profile escaped isolation');const context=browser.contexts()[0];const page=context.pages()[0] ?? await context.waitForEvent('page',{timeout:45000});await page.waitForFunction(()=>document.body?.innerText.trim().length>0);return page} +async function stop(){if(main){void main.eval("process.mainModule.require('electron').app.exit(0)").catch(()=>{});main.ws.close();main=undefined}await browser?.close().catch(()=>{});browser=undefined;child?.kill('SIGTERM');await sleep(500)} +async function identity(page){return edition==='personal'?page.evaluate(()=>window.sb.authState()):page.evaluate(async()=>await(await fetch('/api/session')).json())} +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'; +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; +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. +execFileSync('pkill',['-f',`^${target.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')}/Contents/MacOS/`]); +writeFileSync(join(out,'report.json'),JSON.stringify({edition,root,checks,passed:checks.length,failed:0,scope:'macOS packaged source build; controlled update feed, not live publication'},null,2)); +}catch(error){writeFileSync(join(out,'report.json'),JSON.stringify({edition,root,checks,failed:1,error:String(error)},null,2));throw error}finally{await stop();try{execFileSync('pkill',['-f','^'+target+'/Contents/MacOS/'])}catch{}server?.close();} diff --git a/scripts/packaged-platform-smoke.mjs b/scripts/packaged-platform-smoke.mjs new file mode 100644 index 0000000..c473b5b --- /dev/null +++ b/scripts/packaged-platform-smoke.mjs @@ -0,0 +1,19 @@ +import { readNewDebugPort } from './packaged-test-support.mjs' +// Windows/Linux native installation smoke on disposable CI runners only. +import {spawn,execFileSync} from 'node:child_process';import{mkdtempSync,mkdirSync,cpSync,writeFileSync,readFileSync,existsSync,rmSync,chmodSync,createReadStream}from'node:fs';import{join,resolve}from'node:path';import{tmpdir}from'node:os';import{createHash}from'node:crypto';import{createServer}from'node:http';import{chromium}from'playwright'; +const [source,edition,evidence]=process.argv.slice(2);if(process.env.CI!=='true'||!['win32','linux'].includes(process.platform)||!source||!['personal','corp'].includes(edition)||!evidence)throw Error('Use on a disposable CI runner: SOURCE personal|corp EVIDENCE_DIR'); +const win=process.platform==='win32',out=resolve(evidence),root=mkdtempSync(join(tmpdir(),'km-installed-')),profile=join(root,'profile'),name=edition==='corp'?'KeepMind Corp':'KeepMind',target=join(root,win?'application':'KeepMind.AppImage'),exe=win?join(target,name+'.exe'):target;mkdirSync(out,{recursive:true});mkdirSync(profile); +const env={...process.env,KEEPMIND_USER_DATA_DIR:profile,APPIMAGE_EXTRACT_AND_RUN:'1'};delete env.ELECTRON_RUN_AS_NODE; +const install=()=>{if(win)execFileSync(resolve(source),['/S','/D='+target],{env,timeout:180000});else{cpSync(resolve(source),target);chmodSync(target,0o755)}}; +const checks=[],sleep=n=>new Promise(r=>setTimeout(r,n)),assert=(x,m)=>{if(!x)throw Error(m)};let child,browser,main,server,pid; +function log(s){checks.push(s);console.log(s)} +async function inspector(url){const ws=new WebSocket(url);await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j});let id=0;const pending=new Map();ws.onmessage=e=>{const m=JSON.parse(e.data);pending.get(m.id)?.(m);pending.delete(m.id)};ws.onclose=()=>{for(const cb of pending.values())cb({error:'closed'});pending.clear()};return{ws,eval:expression=>new Promise((r,j)=>{const key=++id,timer=setTimeout(()=>j(Error('Inspector timeout')),180000);pending.set(key,m=>{clearTimeout(timer);if(m.error||m.result?.exceptionDetails)j(Error(JSON.stringify(m.error||m.result.exceptionDetails)));else r(m.result?.result?.value)});ws.send(JSON.stringify({id:key,method:'Runtime.evaluate',params:{expression,awaitPromise:true,returnByValue:true}}))})}} +async function launch(){let stderr='';child=spawn(exe,['--no-sandbox','--disable-gpu',`--user-data-dir=${profile}`,'--remote-debugging-port=0','--inspect=0'],{env,stdio:['ignore','pipe','pipe']});for(const stream of [child.stdout,child.stderr])stream.on('data',d=>{stderr+=d;writeFileSync(join(out,'process.log'),stderr)});for(let i=0;i<300&&!stderr.includes('DevTools listening on');i++){assert(child.exitCode===null,'App exited: '+stderr);await sleep(200)}const dev=stderr.match(/DevTools listening on (ws:\/\/\S+)/)?.[1],debug=stderr.match(/Debugger listening on (ws:\/\/\S+)/)?.[1];assert(dev&&debug,'Missing endpoints: '+stderr);browser=await chromium.connectOverCDP(dev);main=await inspector(debug);await main.eval("globalThis.auditOriginalFetch=process.mainModule.require('electron').net.fetch.bind(process.mainModule.require('electron').net);process.mainModule.require('electron').net.fetch=async()=>new Response(JSON.stringify({assets:[]}))");assert(await main.eval("process.mainModule.require('electron').app.getPath('userData')")===profile,'Profile escaped isolation');pid=await main.eval('process.pid');const context=browser.contexts()[0],page=context.pages()[0]??await context.waitForEvent('page',{timeout:45000});await page.waitForFunction(()=>document.body?.innerText.trim().length>0);return page} +async function stop(){if(main){void main.eval("process.mainModule.require('electron').app.exit(0)").catch(()=>{});main.ws.close();main=undefined}await browser?.close().catch(()=>{});browser=undefined;child?.kill();await sleep(1000)} +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; +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/scripts/packaged-test-support.mjs b/scripts/packaged-test-support.mjs new file mode 100644 index 0000000..6074a27 --- /dev/null +++ b/scripts/packaged-test-support.mjs @@ -0,0 +1,11 @@ +import { existsSync, readFileSync } from 'node:fs' + +// Chromium truncates this file before writing the new debugging endpoint. +// A changed-but-empty file does not mean the relaunched app is ready. +export function readNewDebugPort(file, previous) { + if (!existsSync(file)) return null + const text = readFileSync(file, 'utf8') + if (text === previous || !/^\d+\r?\n\/devtools\/browser\/\S+/.test(text)) return null + const port = Number(text.split('\n')[0]) + return port > 0 && port <= 65535 ? port : null +} diff --git a/src/main/index-corp.ts b/src/main/index-corp.ts index 6df2f0e..014791e 100644 --- a/src/main/index-corp.ts +++ b/src/main/index-corp.ts @@ -1,8 +1,12 @@ +import { initUpdater, checkForUpdates, installUpdate } from './services/updater' +import { configureProfile } from './services/profile' // KeepMind Corp desktop — embeds the corporate second-brain server and opens the web UI. -import { app, BrowserWindow, shell } from 'electron' +import { app, BrowserWindow, shell, Menu, dialog } from 'electron' import { join } from 'node:path' import { startEmbeddedCorpServer, type CorpServerHandle } from './services/corp-server' +configureProfile('corp') + let mainWindow: BrowserWindow | null = null let corp: CorpServerHandle | null = null @@ -46,6 +50,22 @@ app.whenReady().then(async () => { try { corp = await startEmbeddedCorpServer(log) createWindow(corp.baseUrl) + let updatePromptOpen = false + initUpdater({ edition: 'corp', onDownloaded: async version => { + if (updatePromptOpen) return + updatePromptOpen = true + try { + const choice = await dialog.showMessageBox({ type: 'info', message: `KeepMind Corp ${version} pronto para instalar`, detail: 'Seus dados serão preservados. Reiniciar agora?', buttons: ['Depois', 'Reiniciar e atualizar'], defaultId: 0, cancelId: 0 }) + if (choice.response === 1) installUpdate() + } finally { updatePromptOpen = false } + } }) + Menu.setApplicationMenu(Menu.buildFromTemplate([ + ...(process.platform === 'darwin' ? [{ role: 'appMenu' as const }] : []), + { label: 'Atualizações', submenu: [{ label: 'Verificar atualizações', click: async () => { + const result = await checkForUpdates() + if (!result.continuous) await dialog.showMessageBox({ message: result.error || 'Nenhuma atualização disponível.', type: result.error ? 'error' : 'info' }) + } }] } + ])) } catch (e) { log(`startup failed: ${e}`) app.quit() diff --git a/src/main/index.ts b/src/main/index.ts index 13c51fa..4defdb2 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,3 +1,4 @@ +import { configureProfile } from './services/profile' import { randomUUID } from 'node:crypto' import { configureEgressContext, type Consent } from './services/security/egress' import { RefreshScheduler } from './services/ingest/scheduler' @@ -20,6 +21,9 @@ import { attachVaultCrypto } from './services/security' import { initUpdater } from './services/updater' import { TRAY_ICON_B64 } from './tray-icon' +configureProfile() +app.setName('KeepMind SB') + let mainWindow: BrowserWindow | null = null let tray: Tray | null = null let store: Store @@ -64,12 +68,12 @@ function setupTray() { const icon = nativeImage.createFromDataURL(`data:image/png;base64,${TRAY_ICON_B64}`) if (process.platform === 'darwin') icon.setTemplateImage(true) tray = new Tray(icon) - tray.setToolTip('KeepMind — your second brain is running') + tray.setToolTip('KeepMind SB — your second brain is running') const rebuild = () => { if (!tray) return const login = app.getLoginItemSettings().openAtLogin tray.setContextMenu(Menu.buildFromTemplate([ - { label: 'Open KeepMind', click: showWindow }, + { label: 'Open KeepMind SB', click: showWindow }, { type: 'separator' }, { label: 'Sync & automations running', @@ -86,7 +90,7 @@ function setupTray() { } }, { type: 'separator' }, - { label: 'Quit KeepMind', click: () => app.quit() } + { label: 'Quit KeepMind SB', click: () => app.quit() } ])) } rebuild() diff --git a/src/main/services/auth.ts b/src/main/services/auth.ts index 9fece6a..1ce4da2 100644 --- a/src/main/services/auth.ts +++ b/src/main/services/auth.ts @@ -1,6 +1,6 @@ import initSqlJs, { type Database } from 'sql.js' import { scryptSync, randomBytes, timingSafeEqual } from 'node:crypto' -import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { existsSync, readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs' import { join } from 'node:path' // ── Local auth: SQLite (sql.js/WASM) + scrypt password hashing ── @@ -23,6 +23,7 @@ export class AuthService { private db: Database | null = null private ready: Promise private dbFile: string + private restoreDatabase!: (bytes: Uint8Array) => Database constructor(dir: string) { this.dbFile = join(dir, 'auth.db') @@ -33,6 +34,7 @@ export class AuthService { const SQL = await initSqlJs({ locateFile: (f: string) => join(__dirname, '../../node_modules/sql.js/dist', f) }) + this.restoreDatabase = bytes => new SQL.Database(bytes) this.db = existsSync(this.dbFile) ? new SQL.Database(new Uint8Array(readFileSync(this.dbFile))) : new SQL.Database() @@ -57,14 +59,26 @@ export class AuthService { } private persist() { - try { writeFileSync(this.dbFile, Buffer.from(this.db!.export())) } catch { /* noop */ } + const temporary = this.dbFile + '.tmp' + try { + writeFileSync(temporary, Buffer.from(this.db!.export()), { mode: 0o600 }) + renameSync(temporary, this.dbFile) + } finally { rmSync(temporary, { force: true }) } } private async q(fn: (db: Database) => T): Promise { await this.ready - const res = fn(this.db!) - this.persist() - return res + const previous = this.db!.export() + try { + const res = fn(this.db!) + this.persist() + return res + } catch (error) { + // A failed save must not leave an account that a later read could persist. + this.db!.close() + this.db = this.restoreDatabase(previous) + throw error + } } // sql.js exec() returns rows as positional arrays, not objects: diff --git a/src/main/services/profile.ts b/src/main/services/profile.ts new file mode 100644 index 0000000..01c50e2 --- /dev/null +++ b/src/main/services/profile.ts @@ -0,0 +1,11 @@ +import { app } from 'electron' +import { mkdirSync } from 'node:fs' +import { isAbsolute, join } from 'node:path' +// An explicit portable/test profile survives updater relaunches. Never override HOME. +export function configureProfile(edition: 'personal' | 'corp' = 'personal') { + // Pin existing storage identities independently of presentation/product names. + const profile = process.env.KEEPMIND_USER_DATA_DIR || app.commandLine.getSwitchValue('user-data-dir') || join(app.getPath('appData'), edition === 'corp' ? 'keepmind-corp' : 'keepmind') + if (!isAbsolute(profile)) throw new Error('KEEPMIND_USER_DATA_DIR must be absolute') + mkdirSync(profile, { recursive: true }) + app.setPath('userData', profile) +} diff --git a/src/main/services/update-helper.ts b/src/main/services/update-helper.ts new file mode 100644 index 0000000..93fddd5 --- /dev/null +++ b/src/main/services/update-helper.ts @@ -0,0 +1,23 @@ +import type { ChildProcess } from 'node:child_process' +import { existsSync } from 'node:fs' + +// Do not close the application until the external installer can take over. +export function waitForHelperStart(child: ChildProcess, readyFile: string, timeoutMs = 30000): Promise { + return new Promise((resolve, reject) => { + const finish = (error?: Error) => { + clearInterval(poll) + clearTimeout(deadline) + child.removeListener('exit', exited) + child.removeListener('error', failed) + error ? reject(error) : resolve() + } + const exited = (code: number | null, signal: string | null) => finish(new Error(`Update helper exited before startup (code ${code}, signal ${signal})`)) + const failed = (error: Error) => finish(error) + const poll = setInterval(() => { if (existsSync(readyFile)) finish() }, 50) + const deadline = setTimeout(() => { child.kill(); finish(new Error('Update helper startup timed out')) }, timeoutMs) + child.once('exit', exited) + child.once('error', failed) + if (child.exitCode !== null || child.signalCode !== null) exited(child.exitCode, child.signalCode) + else if (existsSync(readyFile)) finish() + }) +} diff --git a/src/main/services/update-policy.ts b/src/main/services/update-policy.ts new file mode 100644 index 0000000..2c816de --- /dev/null +++ b/src/main/services/update-policy.ts @@ -0,0 +1,38 @@ +export type Edition = 'personal' | 'corp' +export const updateIdentity = (edition: Edition) => edition === 'corp' + ? { repo: 'criptogus/keepmind-corp', appName: 'KeepMind Corp', prefix: 'KeepMind-Corp' } + : { repo: 'criptogus/keepmind', appName: 'KeepMind', prefix: 'KeepMind(?:-SB)?' } +export type ReleaseAsset = { name: string; updated_at?: string; digest?: string; id?: number; size?: number; browser_download_url?: string } +const version = (v: string) => (v.match(/\d+/g) ?? []).slice(0, 3).map(Number) +export function compareVersions(a: string, b: string): number { + const x = version(a), y = version(b) + for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0) + return 0 +} +export function selectUpdate(assets: ReleaseAsset[], edition: Edition, platform: string, arch: string, installed: string) { + const prefix = updateIdentity(edition).prefix + const suffix = platform === 'darwin' ? `(?:universal|${arch})-mac\\.zip` : platform === 'win32' ? 'exe' : 'AppImage' + const pattern = platform === 'win32' ? new RegExp(`^${prefix}(?:-Setup-|\\.Setup\\.)(\\d+\\.\\d+\\.\\d+)\\.exe$`) : new RegExp(`^${prefix}-(\\d+\\.\\d+\\.\\d+)(?:-${suffix}|\\.${suffix})$`) + return assets.filter(a => pattern.test(a.name) && compareVersions(a.name, installed) >= 0).sort((a,b) => compareVersions(b.name,a.name) || String(b.updated_at ?? '').localeCompare(String(a.updated_at ?? '')))[0] +} +export function validateUpdateAsset(asset: ReleaseAsset, edition: Edition) { + const repo = updateIdentity(edition).repo + const url = new URL(asset.browser_download_url ?? '') + if (url.origin !== 'https://github.com' || url.username || url.password || !url.pathname.startsWith(`/${repo}/releases/download/continuous/`) || decodeURIComponent(url.pathname.split('/').pop()!) !== asset.name || !/^sha256:[a-f0-9]{64}$/.test(asset.digest ?? '') || !Number.isSafeInteger(asset.size) || asset.size! <= 0) throw new Error('Invalid update asset or missing integrity metadata') + return { url: url.href, sha256: asset.digest!.slice(7), size: asset.size! } +} +export const shellQuote = (value: string) => "'" + value.replace(/'/g, "'\\''") + "'" +export type UpdateReceipt = { stateFile: string; pendingFile: string; marker: string } +export const shellReceipt = (r: UpdateReceipt) => `printf '%s' ${shellQuote(JSON.stringify({ seen: r.marker }))} > ${shellQuote(r.stateFile)}\nrm -f ${shellQuote(r.pendingFile)}` +export function macSwapScript(target: string, staged: string, executable: string, profile: string, parentPid: number, receipt?: UpdateReceipt, relaunchArgs: string[] = []) { + const q = shellQuote + return ['#!/bin/bash', 'set -eu', `while kill -0 ${parentPid} 2>/dev/null; do sleep 0.2; done`, + `target=${q(target)}`, `staged=${q(staged)}`, `backup=${q(target + '.previous')}`, + 'test -d "$target" && test -d "$staged"', 'test ! -e "$backup"', + 'mv "$target" "$backup"', + 'if ! mv "$staged" "$target"; then mv "$backup" "$target"; exit 1; fi', + ...(receipt ? [shellReceipt(receipt)] : []), + `nohup ${q(executable)} ${q('--user-data-dir=' + profile)} ${relaunchArgs.map(q).join(' ')} >/dev/null 2>&1 &`, + // Keep the prior bundle for recovery; cleanup happens before the next staged update. + ''].join('\n') +} diff --git a/src/main/services/updater.ts b/src/main/services/updater.ts index f7fcac9..e83134d 100644 --- a/src/main/services/updater.ts +++ b/src/main/services/updater.ts @@ -1,10 +1,14 @@ import { app, BrowserWindow, net } from 'electron' import { autoUpdater } from 'electron-updater' -import { createWriteStream, existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync } from 'node:fs' +import { createWriteStream, openSync, closeSync, existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync, rmSync, renameSync, mkdtempSync } from 'node:fs' import { join, dirname } from 'node:path' -import { tmpdir } from 'node:os' import { execFile, spawn } from 'node:child_process' import { promisify } from 'node:util' +import { createHash } from 'node:crypto' +import { Readable } from 'node:stream' +import { pipeline } from 'node:stream/promises' +import { waitForHelperStart } from './update-helper' +import { updateIdentity, selectUpdate, validateUpdateAsset, macSwapScript, shellQuote, shellReceipt, type Edition } from './update-policy' const execFileP = promisify(execFile) @@ -14,7 +18,8 @@ const execFileP = promisify(execFile) // 2. "continuous" channel → rolling prerelease rebuilt on every push to // main. Custom downloader + self-swap installer that works unsigned. -const REPO = 'criptogus/keepmind' +let edition: Edition = 'personal' +let onDownloaded: ((version: string) => void) | undefined const CONTINUOUS_TAG = 'continuous' interface ContinuousUpdate { @@ -22,9 +27,16 @@ interface ContinuousUpdate { url: string name: string marker: string + sha256: string + size: number } -let pendingContinuous: { file: string; version: string } | null = null +type Pending = ContinuousUpdate & { file: string } +let pendingContinuous: Pending | null = null +const pendingFile = () => join(app.getPath('userData'), 'update', 'pending.json') +const receipt = () => ({ stateFile: stateFile(), pendingFile: pendingFile(), marker: pendingContinuous!.marker }) +// Preserve only process-isolation switches, never arbitrary caller arguments. +const relaunchArgs = () => process.argv.filter(a => ['--no-sandbox', '--disable-gpu'].includes(a) || /^--remote-debugging-port=\d+$/.test(a)) let checking = false // The continuous release keeps the same semver between version bumps, so we @@ -40,6 +52,7 @@ function markSeen(marker: string) { } function send(channel: string, payload?: any) { + if (channel === 'error') console.error('[updater]', payload?.message ?? 'Update failed') for (const win of BrowserWindow.getAllWindows()) { win.webContents.send('updater:event', { channel, ...payload }) } @@ -47,7 +60,9 @@ function send(channel: string, payload?: any) { // ── electron-updater (signed releases) ── -export function initUpdater() { +export function initUpdater(options: { edition?: Edition; onDownloaded?: (version: string) => void } = {}) { + edition = options.edition ?? 'personal' + onDownloaded = options.onDownloaded if (!app.isPackaged) return { packaged: false } autoUpdater.autoDownload = false // we drive downloads ourselves below @@ -70,100 +85,51 @@ export function updaterStatus() { return { version: app.getVersion(), packaged: app.isPackaged } } -// ── semver-ish compare ── - -function parseVersion(v: string): number[] { - return (v.match(/\d+/g) ?? []).slice(0, 3).map(Number) -} -function versionGt(a: string, b: string): boolean { - const [x, y] = [parseVersion(a), parseVersion(b)] - for (let i = 0; i < 3; i++) { - if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0) - } - return false -} - // ── continuous channel ── - -function assetVersion(name: string): string { - return name.match(/(\d+\.\d+\.\d+)/)?.[1] ?? '0.0.0' -} - -type ReleaseAsset = { - name: string - updated_at?: string - digest?: string - id?: number - browser_download_url?: string -} - -function pickNewestAsset(assets: ReleaseAsset[], re: RegExp): ReleaseAsset | undefined { - const matches = assets.filter((a) => re.test(a.name)) - matches.sort((a, b) => { - const va = assetVersion(a.name) - const vb = assetVersion(b.name) - if (versionGt(va, vb)) return -1 - if (versionGt(vb, va)) return 1 - return String(b.updated_at ?? '').localeCompare(String(a.updated_at ?? '')) - }) - return matches[0] -} - -function assetNameForPlatform(): RegExp { - if (process.platform === 'darwin') { - // universal build preferred; fall back to arch-specific - return process.arch === 'arm64' ? /-universal-mac\.zip$|-arm64-mac\.zip$/ : /-universal-mac\.zip$|-x64-mac\.zip$/ - } - if (process.platform === 'win32') return /\.exe$/ - return /\.AppImage$/ -} - async function findContinuousUpdate(): Promise { - const res = await net.fetch(`https://api.github.com/repos/${REPO}/releases/tags/${CONTINUOUS_TAG}`, { - headers: { 'User-Agent': 'keepmind-updater', Accept: 'application/vnd.github+json' } + const identity = updateIdentity(edition) + const res = await net.fetch(`https://api.github.com/repos/${identity.repo}/releases/tags/${CONTINUOUS_TAG}`, { + headers: { 'User-Agent': 'KeepMind-updater', Accept: 'application/vnd.github+json' } }) if (res.status === 404) return null if (!res.ok) throw new Error(`github api ${res.status}`) const rel = await res.json() as any - const re = assetNameForPlatform() - // Older installers stay on the rolling release. The first name match is - // the stale 0.2.0 file, so pick the highest semver for this platform. - const asset = pickNewestAsset(rel.assets ?? [], re) - if (!asset?.browser_download_url) return null - const m = asset.name.match(/(\d+\.\d+\.\d+)/) - const version = m?.[1] ?? rel.tag_name - const marker = `${rel.updated_at ?? rel.created_at}:${asset.digest ?? asset.id}` - // Newer semver always wins. Same version = update only when the release - // marker changed (new push to main) and we've already recorded a baseline. - if (!versionGt(version, app.getVersion())) { - if (!existsSync(stateFile())) { markSeen(marker); return null } - if (marker === seenMarker()) return null - } - return { version, url: asset.browser_download_url, name: asset.name, marker } + const asset = selectUpdate(rel.assets ?? [], edition, process.platform, process.arch, app.getVersion()) + if (!asset) return null + const integrity = validateUpdateAsset(asset, edition) + const version = asset.name.match(/(\d+\.\d+\.\d+)/)![1] + const marker = `${rel.updated_at ?? rel.created_at}:${asset.digest}` + if (version === app.getVersion() && !existsSync(stateFile())) { markSeen(marker); return null } + if (marker === seenMarker()) return null + return { version, name: asset.name, marker, ...integrity } +} + +async function verifyFile(file: string, expected: { sha256: string; size: number }) { + const { createReadStream } = await import('node:fs') + const hash = createHash('sha256'); let size = 0 + for await (const chunk of createReadStream(file)) { hash.update(chunk); size += chunk.length } + if (size !== expected.size || hash.digest('hex') !== expected.sha256) throw new Error('Update integrity check failed') } -async function downloadToFile(url: string, dest: string): Promise { - const res = await net.fetch(url, { headers: { 'User-Agent': 'keepmind-updater' } }) +async function downloadToFile(update: ContinuousUpdate, dest: string): Promise { + const res = await net.fetch(update.url, { headers: { 'User-Agent': 'KeepMind-updater' } }) if (!res.ok || !res.body) throw new Error(`download failed: ${res.status}`) - const total = Number(res.headers.get('content-length') ?? 0) mkdirSync(dirname(dest), { recursive: true }) - const out = createWriteStream(dest) - const reader = res.body.getReader() - let transferred = 0, lastPct = -1 + const partial = dest + '.partial' try { - for (;;) { - const { done, value } = await reader.read() - if (done) break - out.write(Buffer.from(value)) - transferred += value.byteLength - if (total) { - const pct = Math.round((transferred / total) * 100) - if (pct !== lastPct) { lastPct = pct; send('progress', { percent: pct, transferred, total }) } + let transferred = 0, lastPercent = -1 + await pipeline(Readable.fromWeb(res.body as any), async function* (source) { + for await (const chunk of source) { + transferred += chunk.length + if (transferred > update.size) throw new Error('Update integrity check failed: unexpected size') + const percent = Math.round(transferred / update.size * 100) + if (percent !== lastPercent) { lastPercent = percent; send('progress', { percent, transferred, total: update.size }) } + yield chunk } - } - } finally { - await new Promise((r) => out.end(r)) - } + }, createWriteStream(partial)) + await verifyFile(partial, update) + renameSync(partial, dest) + } catch (error) { rmSync(partial, { force: true }); throw error } } // ── self-install ── @@ -177,51 +143,86 @@ function appBundlePath(): string { // Works unsigned because we replace the bundle ourselves. async function installMac(updateFile: string, version: string): Promise { const work = join(app.getPath('userData'), 'update') - mkdirSync(work, { recursive: true }) - const dest = join(work, 'extracted') + const dest = mkdtempSync(join(work, 'extracted-')) await execFileP('ditto', ['-x', '-k', updateFile, dest]) - const newApp = join(dest, 'KeepMind.app') - if (!existsSync(newApp)) throw new Error('KeepMind.app not found in update archive') - + const name = updateIdentity(edition).appName + const newApp = join(dest, name + '.app') + const executableName = name + if (!existsSync(join(newApp, 'Contents', 'MacOS', executableName))) throw new Error('Expected edition not found in update archive') const target = appBundlePath() + // Stage on the installation volume before touching the working app. + const staged = target + '.staged' + rmSync(staged, { recursive: true, force: true }) + await execFileP('ditto', [newApp, staged]) + rmSync(target + '.previous', { recursive: true, force: true }) const script = join(work, 'swap.sh') - writeFileSync(script, [ - '#!/bin/bash', - 'sleep 2', - `rm -rf ${JSON.stringify(target)}`, - `cp -R ${JSON.stringify(newApp)} ${JSON.stringify(dirname(target))}/`, - `open -a ${JSON.stringify(join(dirname(target), 'KeepMind.app'))}`, - '' - ].join('\n')) - chmodSync(script, 0o755) + writeFileSync(script, macSwapScript(target, staged, join(target,'Contents','MacOS',executableName), app.getPath('userData'), process.pid, receipt(), relaunchArgs())) + chmodSync(script, 0o700) const child = spawn('nohup', ['bash', script], { detached: true, stdio: 'ignore' }) + await new Promise((resolve,reject) => { child.once('spawn',resolve); child.once('error',reject) }) child.unref() app.quit() } -// Windows: NSIS installer supports silent /S; it relaunches the app itself. +// Windows: the helper waits for app exit, runs NSIS, then relaunches the same profile. async function installWin(updateFile: string): Promise { - const child = spawn(updateFile, ['/S'], { detached: true, stdio: 'ignore' }) - child.unref() - app.quit() + const q = (v: string) => "'" + v.replace(/'/g, "''") + "'" + const script = join(app.getPath('userData'), 'update', 'install.ps1') + const r = receipt() + const ready = join(app.getPath('userData'), 'update', 'helper.ready') + rmSync(ready, { force: true }) + writeFileSync(script, [ + "$ErrorActionPreference = 'Stop'", + `Start-Transcript -Path ${q(join(app.getPath('userData'), 'update', 'install.log'))} -Append`, + `[System.IO.File]::WriteAllText(${q(ready)}, 'ready')`, + `Write-Output 'Waiting for application exit'`, + `Wait-Process -Id ${process.pid} -ErrorAction SilentlyContinue`, + `Write-Output 'Starting installer'`, + `$env:KEEPMIND_USER_DATA_DIR = ${q(app.getPath('userData'))}`, + `$installer = Start-Process -FilePath ${q(updateFile)} -ArgumentList @('/S', ${q('/D=' + dirname(process.execPath))}) -Wait -PassThru`, + 'Write-Output ("Installer exit: " + $installer.ExitCode)', + "if ($installer.ExitCode -ne 0) { exit $installer.ExitCode }", + `[System.IO.File]::WriteAllText(${q(r.stateFile)}, ${q(JSON.stringify({seen:r.marker}))})`, + `Remove-Item -LiteralPath ${q(r.pendingFile)} -Force`, + `Start-Process -FilePath ${q(process.execPath)} -ArgumentList ${q(['"--user-data-dir=' + app.getPath('userData') + '"', ...relaunchArgs()].join(' '))}` + ].join('\r\n')) + const helperLog = openSync(join(app.getPath('userData'), 'update', 'helper.log'), 'a', 0o600) + let child: ReturnType + try { + // DETACHED_PROCESS leaves Windows PowerShell without a console: it exits 0 + // without running the script. A hidden cmd console lets PowerShell start; + // its grandchild also escapes libuv's kill-on-parent-exit job object. + const command = 'start "" /b /wait powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "%KEEPMIND_UPDATE_SCRIPT%"' + child = spawn(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', command], { + windowsHide: true, windowsVerbatimArguments: true, + stdio: ['ignore', helperLog, helperLog], + env: { ...process.env, KEEPMIND_UPDATE_SCRIPT: script } + }) + } finally { closeSync(helperLog) } + await waitForHelperStart(child, ready) + child.unref(); app.quit() } // Linux: AppImage is a single file — swap it like the macOS bundle. async function installLinux(updateFile: string): Promise { - const target = process.env.APPIMAGE ?? process.execPath - const script = join(tmpdir(), `keepmind-update-${Date.now()}.sh`) + const target = process.env.APPIMAGE + if (!target) throw new Error('Automatic Linux updates require an AppImage installation') + const script = join(app.getPath('userData'), 'update', 'swap.sh') + const q = shellQuote writeFileSync(script, [ - '#!/bin/bash', - 'sleep 2', - `chmod +x ${JSON.stringify(updateFile)}`, - `cp ${JSON.stringify(updateFile)} ${JSON.stringify(target)}`, - `nohup ${JSON.stringify(target)} >/dev/null 2>&1 &`, - '' + '#!/bin/bash', 'set -eu', + `cp ${q(updateFile)} ${q(target + '.staged')}`, + `chmod +x ${q(target + '.staged')}`, + `while kill -0 ${process.pid} 2>/dev/null; do sleep 0.2; done`, + `cp ${q(target)} ${q(target + '.previous')}`, + `mv ${q(target + '.staged')} ${q(target)}`, + shellReceipt(receipt()), + `nohup ${q(target)} ${q('--user-data-dir=' + app.getPath('userData'))} ${relaunchArgs().map(q).join(' ')} >/dev/null 2>&1 &`, '' ].join('\n')) - chmodSync(script, 0o755) + chmodSync(script, 0o700) const child = spawn('nohup', ['bash', script], { detached: true, stdio: 'ignore' }) - child.unref() - app.quit() + await new Promise((resolve,reject) => {child.once('spawn',resolve);child.once('error',reject)}) + child.unref(); app.quit() } async function applyPending(): Promise { @@ -229,6 +230,7 @@ async function applyPending(): Promise { const { file, version } = pendingContinuous send('installing', { version }) try { + await verifyFile(file, pendingContinuous) if (process.platform === 'darwin') await installMac(file, version) else if (process.platform === 'win32') await installWin(file) else await installLinux(file) @@ -248,14 +250,27 @@ export async function checkForUpdates(): Promise { checking = true try { send('checking') + if (!pendingContinuous && existsSync(pendingFile())) { + const saved = JSON.parse(readFileSync(pendingFile(), 'utf8')) as Pending + validateUpdateAsset({name:saved.name,size:saved.size,digest:'sha256:'+saved.sha256,browser_download_url:saved.url},edition) + if (saved.file !== join(app.getPath('userData'), 'update', saved.name)) throw new Error('Invalid pending update path') + await verifyFile(saved.file, saved) + pendingContinuous = saved + } + if (pendingContinuous) { + send('downloaded', { version: pendingContinuous.version, channel: 'continuous' }) + onDownloaded?.(pendingContinuous.version) + return { packaged: true, continuous: pendingContinuous.version } + } const upd = await findContinuousUpdate() if (upd) { send('available', { version: upd.version, channel: 'continuous' }) const dest = join(app.getPath('userData'), 'update', upd.name) - await downloadToFile(upd.url, dest) - pendingContinuous = { file: dest, version: upd.version } - markSeen(upd.marker) // don't re-download every 6h while awaiting restart + await downloadToFile(upd, dest) + pendingContinuous = { ...upd, file: dest } + writeFileSync(pendingFile(), JSON.stringify(pendingContinuous), { mode: 0o600 }) send('downloaded', { version: upd.version, channel: 'continuous' }) + onDownloaded?.(upd.version) return { packaged: true, continuous: upd.version } } send('up-to-date') diff --git a/src/renderer/index.html b/src/renderer/index.html index 8557075..eb48788 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -4,8 +4,8 @@ - KeepMind - + KeepMind SB +
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index cc9338d..fea7b57 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -167,15 +167,15 @@ export default function App() { await loadConfig() if (intent) navigate(intent.view === 'graph' ? 'memory' : intent.view, { query: intent.query, path: intent.path }) } - if (startupError) return

Não foi possível abrir o KeepMind

Sua configuração ou sessão não pôde ser carregada.

- if (!config || !authState) return

Abrindo o KeepMind…

+ if (startupError) return

Não foi possível abrir o KeepMind SB

Sua configuração ou sessão não pôde ser carregada.

+ if (!config || !authState) return

Abrindo o KeepMind SB…

if (!authState.user) return { setAuthState(await window.sb.authState()); await loadConfig() }} /> if (!config.onboardingDone) return <>{config.corp ? : } setToasts(t => t.filter(x => x.id !== id))} /> const corp = config.corp as { org?: string; role?: string; adminUrl?: string | null } | undefined const primary = PRIMARY.filter(n => !(corp && n.id === 'projects')) const tools = TOOLS.filter(n => !(corp && ['connectors', 'automations'].includes(n.id))) - const label = ALL_VIEWS.find(n => n.id === view)?.label ?? 'KeepMind' + const label = ALL_VIEWS.find(n => n.id === view)?.label ?? 'KeepMind SB' const primaryView = view === 'graph' ? 'memory' : view const jobLine = job?.phase === 'start' ? `${job.name} em andamento` : job?.phase === 'error' ? 'Uma operação precisa de atenção' : 'Pronto para continuar' const memoryProps = { refreshToken: dataVersion, onCapture: () => setDialog('capture'), onAsk: (text: string) => navigate('chat', { query: text }), onOpenGraph: () => navigate('graph'), onOpenSource: (path: string) => navigate('memory', { path }) } @@ -187,12 +187,12 @@ export default function App() { {corp && } {view !== 'graph' && } -
KeepMind{label}
+
KeepMind SB{label}
{vaultLocked &&
Desbloqueie sua memória para guardar e consultar informações.
} {(window as any).__KEEPMIND_DEMO__ &&
Prévia com dados fictícios. Use o aplicativo para guardar sua memória.
}
@@ -213,7 +213,7 @@ export default function App() { {view === 'settings' && }
-
KeepMind ·
+
KeepMind SB ·
diff --git a/src/renderer/src/components/Login.tsx b/src/renderer/src/components/Login.tsx index 8d2f9ac..6972b24 100644 --- a/src/renderer/src/components/Login.tsx +++ b/src/renderer/src/components/Login.tsx @@ -49,7 +49,7 @@ export default function Login({ needsSetup, googleConfigured, onDone }: Props) {
-

KeepMind

+

KeepMind SB

{needsSetup ? 'Create this computer\'s account to begin' : 'Sign in to see what the brain did'}

diff --git a/tests/app-experience.test.tsx b/tests/app-experience.test.tsx index 38231af..5f74cb9 100644 --- a/tests/app-experience.test.tsx +++ b/tests/app-experience.test.tsx @@ -26,7 +26,7 @@ it('navigates primary views and tools, preserves capture and chat drafts, and op await click(findButton('Memória')); await click(findButton('Relacionamentos')); expect(document.body.textContent).toContain('Relacionamentos sintéticos'); await click(findButton('Ferramentas e configurações')); await click(findButton('RotinasConfigure as tarefas recorrentes dos seus agentes.→')); expect(document.body.textContent).toContain('Rotinas sintéticas') await click(findButton('Conversar')); expect((document.querySelector('label input') as HTMLInputElement).value).toBe('Rascunho preservado') await click(findButton('Abrir fonte sintética')); expect(document.body.textContent).toContain('Memória aberta: notes/synthetic.md') - await click(findButton('Hoje')); await click(findButton('KeepMind — início')) + await click(findButton('Hoje')); await click(findButton('KeepMind SB — início')) await click(findButton('Ferramentas e configurações')); await click(findButton('ConfiguraçõesAparência, modelo, sincronização e conta.→')); expect(document.body.textContent).toContain('Configurações sintéticas') await click(findButton('Capturar')); const capture = document.querySelector('textarea')!; await type(capture, 'Ideia sintética'); await click(findButton('Continuar depois')); await click(findButton('Capturar')); expect(document.querySelector('textarea')?.value).toBe('Ideia sintética') }) diff --git a/tests/auth-persistence.test.ts b/tests/auth-persistence.test.ts new file mode 100644 index 0000000..eb36ab4 --- /dev/null +++ b/tests/auth-persistence.test.ts @@ -0,0 +1,49 @@ +import { it, expect, vi } from 'vitest' +import { mkdtempSync, mkdirSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createRequire } from 'node:module' +vi.mock('sql.js', async () => { + const actual = await vi.importActual('sql.js') + return { default: () => actual.default({ locateFile: () => createRequire(import.meta.url).resolve('sql.js/dist/sql-wasm.wasm') }) } +}) +const disk = vi.hoisted(() => ({ fail: false, failOn: 0 })) +vi.mock('node:fs', async () => { + const fs = await vi.importActual('node:fs') + return { ...fs, writeFileSync: (...args: any[]) => { + if (disk.fail || (disk.failOn > 0 && --disk.failOn === 0)) throw new Error('Synthetic disk write failure') + return fs.writeFileSync(...args) + } } +}) +import { AuthService } from '../src/main/services/auth' +it('preserves the same account and valid session after application replacement, and asks login after expiration', async () => { + const root=mkdtempSync(join(tmpdir(),'km-auth-reinstall-')),profile=join(root,'profile'),installation=join(root,'app');mkdirSync(profile);mkdirSync(installation) + try { + const first=new AuthService(profile), user=await first.register('fixture@example.invalid','synthetic-password','Test') + const token=await first.createSession(user.id) + rmSync(installation,{recursive:true});mkdirSync(installation) + const reinstalled=new AuthService(profile) + expect(await reinstalled.hasUsers()).toBe(true) + expect((await reinstalled.userByToken(token))?.id).toBe(user.id) + expect((await reinstalled.verifyPassword('fixture@example.invalid','synthetic-password'))?.id).toBe(user.id) + const now=Date.now();vi.spyOn(Date,'now').mockReturnValue(now+31*864e5) + // Expiry uses Date construction; advance fake time with real async IO unaffected. + vi.useFakeTimers({toFake:['Date']});vi.setSystemTime(now+31*864e5) + expect(await reinstalled.userByToken(token)).toBeNull() + expect(await reinstalled.userCount()).toBe(1) + } finally {vi.useRealTimers();vi.restoreAllMocks();rmSync(root,{recursive:true,force:true})} +}) + +it('reports a persistence failure instead of claiming that an ephemeral account was saved', async () => { + const profile=mkdtempSync(join(tmpdir(),'km-auth-disk-')) + try { + const auth=new AuthService(profile) + await auth.userCount() + disk.failOn=2 + await expect(auth.register('fixture@example.invalid','synthetic-password','Test')).rejects.toThrow('Synthetic disk write failure') + disk.fail=false + expect(await new AuthService(profile).userCount()).toBe(0) + expect(await auth.userCount()).toBe(0) + await expect(auth.register('fixture@example.invalid','synthetic-password','Test')).resolves.toMatchObject({email:'fixture@example.invalid'}) + } finally {disk.fail=false;disk.failOn=0;rmSync(profile,{recursive:true,force:true})} +}) diff --git a/tests/installer-contract.test.ts b/tests/installer-contract.test.ts new file mode 100644 index 0000000..24f65e4 --- /dev/null +++ b/tests/installer-contract.test.ts @@ -0,0 +1,18 @@ +import { it, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +const {load}=createRequire(import.meta.url)('js-yaml') +it('preserves profiles on Windows uninstall for both editions',()=>{ + for(const file of ['electron-builder.yml','electron-builder.corp.yml'])expect(load(readFileSync(file,'utf8')).nsis.deleteAppDataOnUninstall).toBe(false) +}) +it('publishes the Corp desktop entrypoint/resources instead of the personal application',()=>{ + const corp=load(readFileSync('electron-builder.corp.yml','utf8')) + expect(corp.extraMetadata.main).toBe('./out/main/index-corp.js') + expect(corp.files).toContain('out/main/**') + expect(corp.publish.repo).toBe('keepmind-corp') + const flow=load(readFileSync('.github/workflows/continuous.yml','utf8')) + const steps=flow.jobs.build.steps + expect(steps.find((s:any)=>s.run?.startsWith('npx electron-builder')).run).toContain("github.repository == 'criptogus/keepmind-corp' && '--config electron-builder.corp.yml'") + expect(steps.some((s:any)=>s.run==='npm run corp:build-brain' && s.if.includes('keepmind-corp'))).toBe(true) + expect(steps.find((s:any)=>s.uses?.startsWith('actions/upload-artifact')).with.path).toContain("'dist-corp' || 'dist'") +}) diff --git a/tests/packaged-test-support.test.ts b/tests/packaged-test-support.test.ts new file mode 100644 index 0000000..6e085f2 --- /dev/null +++ b/tests/packaged-test-support.test.ts @@ -0,0 +1,17 @@ +import { it, expect } from 'vitest' +import { mkdtempSync, writeFileSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { readNewDebugPort } from '../scripts/packaged-test-support.mjs' +it('waits through a truncated or partial Chromium endpoint file during relaunch', () => { + const root = mkdtempSync(join(tmpdir(), 'km-cdp-')), file = join(root, 'DevToolsActivePort') + const previous = '1234\n/devtools/browser/old' + try { + for (const contents of ['', '5678', '5678\n', previous]) { + writeFileSync(file, contents) + expect(readNewDebugPort(file, previous)).toBeNull() + } + writeFileSync(file, '5678\n/devtools/browser/new') + expect(readNewDebugPort(file, previous)).toBe(5678) + } finally { rmSync(root, { recursive: true, force: true }) } +}) diff --git a/tests/profile.test.ts b/tests/profile.test.ts new file mode 100644 index 0000000..b2c6fa0 --- /dev/null +++ b/tests/profile.test.ts @@ -0,0 +1,16 @@ +import { it, expect, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +const fake=vi.hoisted(()=>({appData:'',switchValue:'',setPath:vi.fn()})) +vi.mock('electron',()=>({app:{getPath:()=>fake.appData,commandLine:{getSwitchValue:()=>fake.switchValue},setPath:fake.setPath}})) +import { configureProfile } from '../src/main/services/profile' +it('keeps existing data identities across the KeepMind SB rename, with separate Corp data',()=>{ + fake.appData=mkdtempSync(join(tmpdir(),'km-profile-'));const original=process.env.KEEPMIND_USER_DATA_DIR;delete process.env.KEEPMIND_USER_DATA_DIR + try { + configureProfile();expect(fake.setPath).toHaveBeenLastCalledWith('userData',join(fake.appData,'keepmind')) + configureProfile('corp');expect(fake.setPath).toHaveBeenLastCalledWith('userData',join(fake.appData,'keepmind-corp')) + fake.switchValue=join(fake.appData,'isolated');configureProfile();expect(fake.setPath).toHaveBeenLastCalledWith('userData',fake.switchValue) + process.env.KEEPMIND_USER_DATA_DIR=join(fake.appData,'inherited');configureProfile();expect(fake.setPath).toHaveBeenLastCalledWith('userData',process.env.KEEPMIND_USER_DATA_DIR) + }finally{fake.switchValue='';if(original===undefined)delete process.env.KEEPMIND_USER_DATA_DIR;else process.env.KEEPMIND_USER_DATA_DIR=original;rmSync(fake.appData,{recursive:true,force:true})} +}) diff --git a/tests/update-helper.test.ts b/tests/update-helper.test.ts new file mode 100644 index 0000000..f003455 --- /dev/null +++ b/tests/update-helper.test.ts @@ -0,0 +1,19 @@ +import { it, expect } from 'vitest' +import { spawn } from 'node:child_process' +import { mkdtempSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { waitForHelperStart } from '../src/main/services/update-helper' + +it('requires the installer helper startup signal before allowing app shutdown', async () => { + const root = mkdtempSync(join(tmpdir(), 'km-helper-')), ready = join(root, 'ready') + const child = spawn(process.execPath, ['-e', "require('fs').writeFileSync(process.argv[1], 'ready'); setInterval(()=>{},1000)", ready]) + try { await expect(waitForHelperStart(child, ready)).resolves.toBeUndefined() } + finally { child.kill(); rmSync(root, { recursive: true, force: true }) } +}) +it('rejects a helper that exits without starting instead of closing the app', async () => { + const root = mkdtempSync(join(tmpdir(), 'km-helper-')) + const child = spawn(process.execPath, ['-e', 'process.exit(17)']) + try { await expect(waitForHelperStart(child, join(root, 'ready'))).rejects.toThrow('code 17') } + finally { rmSync(root, { recursive: true, force: true }) } +}) diff --git a/tests/update-policy.test.ts b/tests/update-policy.test.ts new file mode 100644 index 0000000..28055c8 --- /dev/null +++ b/tests/update-policy.test.ts @@ -0,0 +1,41 @@ +import { describe, it, expect } from 'vitest' +import { execFileSync } from 'node:child_process' +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { selectUpdate, validateUpdateAsset, macSwapScript, updateIdentity } from '../src/main/services/update-policy' +const asset = (name: string, repo = 'keepmind') => ({ name, size: 123, digest: 'sha256:' + 'a'.repeat(64), browser_download_url: `https://github.com/criptogus/${repo}/releases/download/continuous/${name}` }) +describe('installed update boundaries', () => { + it('keeps Corp on its own repository and excludes personal binaries', () => { + expect(updateIdentity('corp').repo).toBe('criptogus/keepmind-corp') + expect(selectUpdate([asset('KeepMind-0.2.6-universal-mac.zip')], 'corp', 'darwin', 'arm64', '0.2.6')).toBeUndefined() + expect(selectUpdate([asset('KeepMind-Corp-0.2.6-universal-mac.zip')], 'corp', 'darwin', 'arm64', '0.2.6')?.name).toContain('Corp') + }) + it('never downgrades and rejects another architecture', () => { + expect(selectUpdate([asset('KeepMind-0.2.5-universal-mac.zip')], 'personal', 'darwin', 'arm64', '0.2.6')).toBeUndefined() + expect(selectUpdate([asset('KeepMind-0.2.6-x64-mac.zip')], 'personal', 'darwin', 'arm64', '0.2.6')).toBeUndefined() + }) + it('requires trusted URL, positive size and digest', () => { + const valid = asset('KeepMind-Setup-0.2.6.exe') + expect(validateUpdateAsset(valid,'personal').size).toBe(123) + for(const patch of [{digest:undefined},{size:0},{browser_download_url:'https://example.com/update.exe'}]) expect(()=>validateUpdateAsset({...valid,...patch},'personal')).toThrow() + expect(()=>validateUpdateAsset(valid,'corp')).toThrow() + }) + it('swaps an app transactionally and preserves a quoted profile without shell expansion', () => { + const dir = mkdtempSync(join(tmpdir(),'km-swap-')) + try { + const target=join(dir,"KeepMind's $(touch BAD).app"),stage=join(dir,'staged.app'),profile=join(dir,'private profile'),result=join(dir,'result') + mkdirSync(target);writeFileSync(join(target,'old'),'old');mkdirSync(stage);mkdirSync(profile);writeFileSync(join(profile,'sentinel'),'keep') + const exe=join(target,'launch');writeFileSync(join(stage,'launch'),`#!/bin/bash\nprintf '%s' "$1" > '${result}'\n`,{mode:0o755}) + execFileSync('bash',['-c',macSwapScript(target,stage,exe,profile,99999999)]) + expect(readFileSync(join(profile,'sentinel'),'utf8')).toBe('keep') + expect(existsSync(join(target+'.previous','old'))).toBe(true) + expect(existsSync(join(target,'launch'))).toBe(true) + expect(existsSync(join(dir,'BAD'))).toBe(false) + } finally { rmSync(dir,{recursive:true,force:true}) } + }) + it('leaves the previous installation intact if staging is missing', () => { + const dir=mkdtempSync(join(tmpdir(),'km-swap-'));const target=join(dir,'KeepMind.app');mkdirSync(target);writeFileSync(join(target,'old'),'intact') + try {expect(()=>execFileSync('bash',['-c',macSwapScript(target,join(dir,'missing'),'/unused','/unused',99999999)])).toThrow();expect(readFileSync(join(target,'old'),'utf8')).toBe('intact')}finally{rmSync(dir,{recursive:true,force:true})} + }) +}) diff --git a/tests/updater-download.test.ts b/tests/updater-download.test.ts new file mode 100644 index 0000000..073cc72 --- /dev/null +++ b/tests/updater-download.test.ts @@ -0,0 +1,34 @@ +import { beforeEach, afterEach, it, expect, vi } from 'vitest' +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs' +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-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 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') + 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() +}) +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') + expect(existsSync(join(fake.profile,'update','pending.json'))).toBe(false) + expect(existsSync(join(fake.profile,'update',name))).toBe(false) +}) +it('rejects tampered pending files after restart',async()=>{ + responses(bytes);let updater=await import('../src/main/services/updater');await updater.checkForUpdates();writeFileSync(join(fake.profile,'update',name),'tampered') + vi.resetModules();updater=await import('../src/main/services/updater');expect((await updater.checkForUpdates()).error).toContain('integrity') +}) +it('Corp updater requests the Corp repository and does not accept personal packages',async()=>{ + responses(bytes);vi.useFakeTimers();const updater=await import('../src/main/services/updater');updater.initUpdater({edition:'corp'});await updater.checkForUpdates() + expect(fake.fetch.mock.calls[0][0]).toContain('/criptogus/keepmind-corp/');expect(existsSync(join(fake.profile,'update','pending.json'))).toBe(false) +})