mirror of
https://github.com/pvrzz/Portage.git
synced 2026-11-29 05:22:26 +00:00
feat: offline Firefox cookie migration; privacy-safe real-profile diagnostics
This commit is contained in:
@@ -127,3 +127,27 @@ For an actual two-origin cross-browser IndexedDB test with disposable profiles:
|
||||
node tests/test_indexeddb_codec.cjs
|
||||
node tests/e2e_indexeddb.cjs
|
||||
```
|
||||
|
||||
## Offline cookie migration (experimental)
|
||||
|
||||
The `chromium_cookie_import.cjs` companion can transfer Firefox cookies into a
|
||||
closed Chromium/Brave profile without creating a plaintext cookie bundle on
|
||||
disk. Python reads the backed-up Firefox `cookies.sqlite` and passes the
|
||||
records through a **local subprocess pipe** to Chrome's native cookie API.
|
||||
Only aggregate counts are printed. The entire profile should be backed up.
|
||||
|
||||
```bash
|
||||
node tools/chromium_cookie_import.cjs \
|
||||
"$HOME/.mozilla/firefox/dev-edition-default" \
|
||||
"$HOME/.config/BraveSoftware/Brave-Browser" \
|
||||
/usr/bin/brave-browser
|
||||
```
|
||||
|
||||
Firefox containers, origin-attribute partitions and expired cookies are
|
||||
conservatively excluded, rather than incorrectly combining isolated sessions.
|
||||
Some cookies or logins remain tied to browser/device-bound secrets; a successful
|
||||
CDP `Network.setCookie` result does **not** guarantee continued authentication.
|
||||
Never collect or paste exported cookie values into bug reports.
|
||||
|
||||
`node tests/e2e_cookie_cli.cjs` verifies this transfer with synthetic cookie
|
||||
values and disposable Brave profiles only.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
/** Private-process Firefox -> Chromium cookie transfer. Do not print cookie values. */
|
||||
const cp=require('node:child_process'),path=require('node:path'),fs=require('node:fs'),os=require('node:os');
|
||||
async function transfer({sourceProfile,targetProfile,browserPath}) {
|
||||
const source=path.resolve(sourceProfile),target=path.resolve(targetProfile);
|
||||
if(!fs.existsSync(source)||!fs.existsSync(browserPath))throw Error('Source or browser missing');
|
||||
if(fs.existsSync(path.join(target,'SingletonLock')))throw Error('Target browser lock present');
|
||||
const p=cp.spawnSync('python3',[path.join(__dirname,'firefox_cookie_stream.py'),source],{
|
||||
encoding:'utf8',maxBuffer:32*1024*1024,timeout:20000,stdio:['ignore','pipe','pipe']});
|
||||
if(p.status!==0)throw Error('Cookie decoding failed; no destination modifications');
|
||||
const parsed=JSON.parse(p.stdout);p.stdout='';
|
||||
let puppeteer=require('puppeteer-core'),browser;
|
||||
const result={candidate:parsed.cookies.length,skipped:parsed.skipped,accepted:0,failed:0};
|
||||
try{
|
||||
browser=await puppeteer.launch({executablePath:browserPath,userDataDir:target,headless:true,
|
||||
args:['--disable-background-networking','--disable-sync','--disable-extensions','--no-first-run']});
|
||||
const page=await browser.newPage(),session=await page.createCDPSession();
|
||||
for(const cookie of parsed.cookies){
|
||||
try{
|
||||
let {success}=await session.send('Network.setCookie',cookie);
|
||||
if(success)result.accepted++;else result.failed++;
|
||||
}catch(e){result.failed++;}
|
||||
}
|
||||
}finally{if(browser)await browser.close();}
|
||||
return result;
|
||||
}
|
||||
if(require.main===module){
|
||||
const args=process.argv.slice(2);
|
||||
if(args.length!==3){console.error('Usage: node chromium_cookie_import.cjs FIREFOX_CLOSED_PROFILE CHROMIUM_CLOSED_PROFILE CHROME_EXECUTABLE');process.exit(2)}
|
||||
transfer({sourceProfile:args[0],targetProfile:args[1],browserPath:args[2]}).then(r=>{
|
||||
console.log('Cookies (counts only):',JSON.stringify(r));if(r.failed)process.exitCode=2;
|
||||
}).catch(e=>{console.error('Cookie import failed:',e.message);process.exitCode=1});
|
||||
}
|
||||
module.exports={transfer};
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Output an in-memory migration stream of standard Firefox cookies to a local process.
|
||||
Never redirect stdout to a file or issue tracker: it contains session credentials.
|
||||
"""
|
||||
import json, sqlite3, sys, time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def collect(profile):
|
||||
file=Path(profile)/'cookies.sqlite'
|
||||
if not file.is_file():
|
||||
raise FileNotFoundError('Firefox cookies.sqlite not found')
|
||||
uri=file.resolve().as_uri()+'?mode=ro'
|
||||
included=[]
|
||||
reason={'partitioned_or_containers':0,'expired':0,'invalid':0,'insecure_none':0}
|
||||
now=time.time()
|
||||
with sqlite3.connect(uri, uri=True, timeout=10) as conn:
|
||||
for name,value,host,path,expiry,secure,http_only,same_site,attrs in conn.execute(
|
||||
'SELECT name,value,host,path,expiry,isSecure,isHttpOnly,sameSite,originAttributes FROM moz_cookies'
|
||||
):
|
||||
if attrs:
|
||||
reason['partitioned_or_containers']+=1
|
||||
continue
|
||||
if not host or not isinstance(name,str) or not isinstance(value,str) or not host.strip('.') or not path.startswith('/'):
|
||||
reason['invalid']+=1
|
||||
continue
|
||||
if expiry and expiry<now:
|
||||
reason['expired']+=1
|
||||
continue
|
||||
if same_site==0 and not secure:
|
||||
reason['insecure_none']+=1
|
||||
continue
|
||||
cookie={'name':name,'value':value,'domain':host,'path':path,
|
||||
'secure':bool(secure),'httpOnly':bool(http_only),
|
||||
'expires':float(expiry) if expiry else -1}
|
||||
if same_site in (0,1,2):cookie['sameSite']={0:'None',1:'Lax',2:'Strict'}[same_site]
|
||||
included.append(cookie)
|
||||
return {'cookies':included,'skipped':reason}
|
||||
|
||||
if __name__=='__main__':
|
||||
if len(sys.argv)!=2:
|
||||
print('Usage: firefox_cookie_stream.py FIREFOX_PROFILE',file=sys.stderr);sys.exit(2)
|
||||
json.dump(collect(sys.argv[1]),sys.stdout,ensure_ascii=False,separators=(',',':'))
|
||||
@@ -117,7 +117,7 @@ def export_profile(profile: Path):
|
||||
with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=3)) as conn:
|
||||
row = conn.execute('SELECT origin FROM "database" LIMIT 1').fetchone()
|
||||
if not row or not valid_origin(row[0]):
|
||||
warnings.append(f'Skipped partitioned or invalid origin: {db.parent.parent.name}')
|
||||
warnings.append('Skipped partitioned or invalid origin (name omitted for privacy)')
|
||||
continue
|
||||
origin = row[0].rstrip('/')
|
||||
entries = conn.execute('SELECT key, value, conversion_type, compression_type FROM data').fetchall()
|
||||
@@ -130,7 +130,7 @@ def export_profile(profile: Path):
|
||||
items[key] = decode_value(value, conversion, compression)
|
||||
sites.append({'origin': origin, 'items': items})
|
||||
except (sqlite3.Error, ValueError, TypeError, UnicodeError, OSError) as exc:
|
||||
warnings.append(f'Skipped {db.parent.parent.name}: {exc}')
|
||||
warnings.append(f'Skipped unreadable/unsupported origin (details omitted): {type(exc).__name__}')
|
||||
return sites, warnings
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user