import fs from 'node:fs';import path from 'node:path';import os from 'node:os';import{createHash}from'node:crypto';import{fileURLToPath}from'node:url';import{workspace,run}from'./lib.mjs'; const hash=b=>createHash('sha256').update(b).digest('hex'); export function inspect(file){ const names=run('unzip',['-Z1',file]).trim().split('\n'); const allowed=['owner-keys.json','companion.keystore','games-debug.keystore']; if(names.length!==3||names.some(n=>!allowed.includes(n)))throw new Error('Not the expected three-file owner-key transfer ZIP.'); const manifest=JSON.parse(run('unzip',['-p',file,'owner-keys.json'])); if(manifest.schema!==1)throw new Error('Unknown owner-key manifest.'); for(const name of allowed.slice(1)){ const bytes=run('unzip',['-p',file,name],{encoding:null}); if(hash(bytes)!==manifest.sha256[name])throw new Error('Key-transfer checksum mismatch.'); } return manifest; } export function importKeys(file,root=workspace(),home=os.homedir()){ const manifest=inspect(file),pairs=[['companion.keystore',path.join(root,'companion/chloe-local.keystore')],['games-debug.keystore',path.join(home,'.android/debug.keystore')]]; for(const [name,to]of pairs)if(fs.existsSync(to)&&hash(fs.readFileSync(to))!==manifest.sha256[name])throw new Error('A different key already exists at '+to+'. Back it up and choose its location before importing; no file was overwritten.'); for(const [name,to]of pairs){fs.mkdirSync(path.dirname(to),{recursive:true});if(!fs.existsSync(to))fs.writeFileSync(to,run('unzip',['-p',file,name],{encoding:null}),{mode:0o600});} return {imported:true,paths:pairs.map(p=>p[1])}; } if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url)){ try{const [action,file]=process.argv.slice(2);if(!['inspect','import'].includes(action)||!file)throw new Error('Use keys.mjs inspect|import PRIVATE-owner-keys.zip');console.log(JSON.stringify(action==='import'?importKeys(path.resolve(file)):inspect(path.resolve(file)),null,2));}catch(e){console.error(e.message);process.exitCode=1;} }