diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 183e554..36ad0d7 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -21,7 +21,7 @@ jobs: - name: IndexedDB codec tests run: node tests/test_indexeddb_codec.cjs - name: Python syntax - run: python3 -m py_compile tools/list_firefox_idb_origins.py tools/firefox_localstorage.py + run: python3 -m py_compile tools/list_firefox_idb_origins.py tools/firefox_localstorage.py tools/firefox_cookie_stream.py - name: JavaScript syntax run: | node --check chrome/dashboard.js @@ -31,5 +31,7 @@ jobs: node --check tools/indexeddb_migrate.cjs node --check tools/indexeddb_codec.js node --check tests/e2e_indexeddb.cjs + node --check tools/chromium_cookie_import.cjs + node --check tests/e2e_cookie_cli.cjs - name: CLI help run: node tools/chromium_localstorage_import.cjs --help diff --git a/tests/e2e_cookie_cli.cjs b/tests/e2e_cookie_cli.cjs new file mode 100644 index 0000000..d798f41 --- /dev/null +++ b/tests/e2e_cookie_cli.cjs @@ -0,0 +1,22 @@ +'use strict'; +const cp=require('node:child_process'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),assert=require('node:assert/strict'); +const {transfer}=require('../tools/chromium_cookie_import.cjs'); +const pp=require('../tools/node_modules/puppeteer-core'); +(async()=>{const root=fs.mkdtempSync(path.join(os.tmpdir(),'portage-cookie-cli-')); + const src=path.join(root,'firefox'),dst=path.join(root,'brave');fs.mkdirSync(src); + try{ + const code=`import sqlite3,sys; c=sqlite3.connect(sys.argv[1]);c.execute('CREATE TABLE moz_cookies (name TEXT,value TEXT,host TEXT,path TEXT,expiry INTEGER,isSecure INTEGER,isHttpOnly INTEGER,sameSite INTEGER,originAttributes TEXT)');c.executemany('INSERT INTO moz_cookies VALUES(?,?,?,?,?,?,?,?,?)',[ + ('hello','test-value','example.com','/',1999999999,1,1,1,''), + ('divided','test-value','example.org','/',1999999999,1,1,2,'^userContextId=1'), + ('invalid','test-value','example.org','/',1999999999,0,0,0,''), + ]);c.commit()`; + const p=cp.spawnSync('python3',['-c',code,path.join(src,'cookies.sqlite')],{encoding:'utf8'});assert.equal(p.status,0,p.stderr); + const result=await transfer({sourceProfile:src,targetProfile:dst,browserPath:'/usr/bin/brave-browser'}); + assert.equal(result.candidate,1);assert.equal(result.accepted,1);assert.equal(result.failed,0); + assert.equal(result.skipped.partitioned_or_containers,1);assert.equal(result.skipped.insecure_none,1); + const browser=await pp.launch({executablePath:'/usr/bin/brave-browser',userDataDir:dst,headless:true,args:['--disable-background-networking']}); + try{const page=await browser.newPage(),session=await page.createCDPSession();let r=await session.send('Storage.getCookies');assert(r.cookies.some(c=>c.name==='hello'&&c.httpOnly&&c.secure));} + finally{await browser.close()} + console.log('PASS native Brave cookie CLI: 1 persisted; unsafe/partitioned skipped'); + }finally{fs.rmSync(root,{recursive:true,force:true})} +})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/tools/README.md b/tools/README.md index b1fd167..98b1856 100644 --- a/tools/README.md +++ b/tools/README.md @@ -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. diff --git a/tools/chromium_cookie_import.cjs b/tools/chromium_cookie_import.cjs new file mode 100644 index 0000000..c0db759 --- /dev/null +++ b/tools/chromium_cookie_import.cjs @@ -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}; diff --git a/tools/firefox_cookie_stream.py b/tools/firefox_cookie_stream.py new file mode 100644 index 0000000..550fd0a --- /dev/null +++ b/tools/firefox_cookie_stream.py @@ -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