Skip to content

Commit

Permalink
Merge pull request #66 from kairi003/develop
Browse files Browse the repository at this point in the history
release v0.6.0
  • Loading branch information
kairi003 authored May 19, 2024
2 parents 34116c3 + e07a979 commit f78ef3c
Show file tree
Hide file tree
Showing 17 changed files with 258 additions and 206 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,5 @@ dist
# TernJS port file
.tern-port

dst/
*.zip
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ Specifically, it now needs "Download management" to execute a more appropriate f
3. Enable "Developer mode".
4. Click on "Load Unpacked" and open the directory `Get-cookies.txt-LOCALLY/src`.

## Build for Firefox
1. Download and unzip this repository.
2. Merge `src/manifest.json` and `src/manifest-firefox.json` using one of the following methods:
- `npm install && npm run build:firfox` and install generated `.zip` file from the `dist` directory.
- `jq -s '.[0] + .[1]' src/manifest.json src/manifest-firefox.json > src/manifest.json` and install the extension from the `src` rectory.
- Merge manually.



## Example of extension installation directory (Google Chrome)
Expand Down
46 changes: 26 additions & 20 deletions build.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
#!/usr/bin/env node

const fs = require('fs');
const process = require('process');
const path = require('path');
const archiver = require('archiver');
const { exec } = require('child_process');

const { execSync } = require('child_process');
const { program } = require('commander');

const getBranch = () => new Promise((resolve, reject) => {
exec('git rev-parse --abbrev-ref HEAD', (err, stdout, stderr) => {
if (typeof stdout === 'string') {
resolve(stdout.trim());
} else {
reject(TypeError);
}
});
});
const options = program.option('-f --firefox', 'Build for Firefox').parse(process.argv).opts();

const getGitInfo = () => {
const branch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
const commitHash = execSync('git rev-parse HEAD').toString().trim();
return { branch, commitHash };
};

const build = async (name) => {
const dt = new Date().toLocaleString('sv').replace(/\D/g, '');
const zipPath = `${name.replace('/', '_')}_${dt}.zip`;
const output = fs.createWriteStream(path.join(__dirname, zipPath));
const build = async ({ branch, commitHash }) => {
const mode = options.firefox ? 'firefox' : 'chrome';
const zipName = `${branch.replace('/', '_')}_${commitHash.slice(0,5)}_${mode}.zip`;
fs.mkdirSync(path.join(__dirname, 'dst'), { recursive: true });
const output = fs.createWriteStream(path.join(__dirname, 'dst', zipName));

process.chdir(path.join(__dirname, 'src'));

Expand All @@ -28,11 +28,17 @@ const build = async (name) => {
});

archive.pipe(output);
archive.glob('**/*');
archive.glob('**/*', { ignore: ['**/*.json'] });

await archive.finalize();
console.log('BUILD', zipPath);
}
const manifest = JSON.parse(fs.readFileSync('manifest.json'));
if (options.firefox) {
const manifestFirefox = JSON.parse(fs.readFileSync('manifest-firefox.json'));
Object.assign(manifest, manifestFirefox);
}
archive.append(JSON.stringify(manifest, null, 2), { name: 'manifest.json' });

archive.finalize();
console.log('BUILD', zipName);
};

getBranch().then(build);
build(getGitInfo());
19 changes: 14 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
"@types/chrome": "^0.0.218",
"@types/wicg-file-system-access": "^2020.9.5",
"archiver": "^5.3.1",
"commander": "^12.1.0",
"icon-gen": "^3.0.1",
"prettier": "^3.2.5"
},
"scripts": {
"format": "npx prettier --write src",
"build": "npm run format && node build.js"
"build": "npm run build:chrome && npm run build:firefox",
"build:chrome": "node build.js",
"build:firefox": "node build.js --firefox"
}
}
5 changes: 5 additions & 0 deletions src/@types/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
type Format = {
ext: string;
mimeType: string;
serializer: (cookies: chrome.cookies.Cookie[]) => string;
};
2 changes: 2 additions & 0 deletions src/background.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<!-- This file is used to load the background script on Firefox. -->
<script type="module" src="background.mjs"></script>
22 changes: 1 addition & 21 deletions src/background.js → src/background.mjs
Original file line number Diff line number Diff line change
@@ -1,24 +1,4 @@
/**
* Retrieves both cookies with and without a partition key and returns the merged list
* @param {chrome.cookies.GetAllDetails} details
* @returns {chrome.cookies.Cookie[]}
*/
const getAllCookies = async (details) => {
const { partitionKey, ...detailsWithoutPartitionKey } = details;
const cookiesWithPartitionKey = partitionKey ? await chrome.cookies.getAll(details) : [];
const cookies = await chrome.cookies.getAll(detailsWithoutPartitionKey);
return [...cookies, ...cookiesWithPartitionKey];
};

// Listen for messages from popup.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'requestAllCookies') {
const { details } = message;
getAllCookies(details).then(sendResponse);
return true;
}
return false;
});
import getAllCookies from './modules/get_all_cookies.mjs';

/**
* Update icon badge counter on active page
Expand Down
11 changes: 11 additions & 0 deletions src/manifest-firefox.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"incognito": "spanning",
"background": {
"page": "background.html"
},
"browser_specific_settings": {
"gecko": {
"id": "{ac87cfd8-47b1-4401-b32e-f033af5ed96b}"
}
}
}
5 changes: 3 additions & 2 deletions src/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "Get cookies.txt LOCALLY",
"description": "Get cookies.txt, NEVER send information outside with open-source",
"version": "0.5.7",
"version": "0.6.2",
"manifest_version": 3,
"permissions": ["activeTab", "cookies", "downloads", "notifications"],
"host_permissions": ["<all_urls>"],
Expand All @@ -22,6 +22,7 @@
},
"incognito": "split",
"background": {
"service_worker": "background.js"
"service_worker": "background.mjs",
"type": "module"
}
}
38 changes: 38 additions & 0 deletions src/modules/cookie_format.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Convert Chrome's JSON format cookies data to a string array for Netscape format
* @param {chrome.cookies.Cookie[]} cookies
* @returns {string[][]}
*/
export const jsonToNetscapeMapper = (cookies) => {
return cookies.map(({ domain, expirationDate, path, secure, name, value }) => {
const includeSubDomain = !!domain?.startsWith('.');
const expiry = expirationDate?.toFixed() ?? '0';
const arr = [domain, includeSubDomain, path, secure, expiry, name, value];
return arr.map((v) => (typeof v === 'boolean' ? v.toString().toUpperCase() : v));
});
};

/** @type {Record<string, Format>} */
export const formatMap = {
netscape: {
ext: '.txt',
mimeType: 'text/plain',
serializer: (cookies) => {
const netscapeTable = jsonToNetscapeMapper(cookies);
const text = [
'# Netscape HTTP Cookie File',
'# http://curl.haxx.se/rfc/cookie_spec.html',
'# This is a generated file! Do not edit.',
'',
...netscapeTable.map((row) => row.join('\t')),
'' // Add a new line at the end
].join('\n');
return text;
}
},
json: {
ext: '.json',
mimeType: 'application/json',
serializer: JSON.stringify
}
};
29 changes: 29 additions & 0 deletions src/modules/get_all_cookies.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Get all cookies that match the given criteria.
* @param {chrome.cookies.GetAllDetails} details
* @returns {Promise<chrome.cookies.Cookie[]>}
*/
export default async function getAllCookies(details) {
details.storeId ??= await getCurrentCookieStoreId();
const { partitionKey, ...detailsWithoutPartitionKey } = details;
const cookiesWithPartitionKey = partitionKey ? await chrome.cookies.getAll(details) : [];
const cookies = await chrome.cookies.getAll(detailsWithoutPartitionKey);
return [...cookies, ...cookiesWithPartitionKey];
}

/**
* Get the current cookie store ID.
* @returns {Promise<string | undefined>}
*/
const getCurrentCookieStoreId = async () => {
// If the extension is in split incognito mode, return undefined to choose the default store.
if (chrome.runtime.getManifest().incognito === 'split') return undefined;

// Firefox supports the `tab.cookieStoreId` property.
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab.cookieStoreId) return tab.cookieStoreId;

// Chrome does not support the `tab.cookieStoreId` property.
const stores = await chrome.cookies.getAllCookieStores();
return stores.find((store) => store.tabIds.includes(tab.id))?.id;
};
2 changes: 1 addition & 1 deletion src/popup-options.css
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
gap: 0.5em;
}

.netscape-table.nowrap {
.netscape-table.nowrap tbody {
white-space: nowrap;
}
2 changes: 1 addition & 1 deletion src/popup.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<link rel="stylesheet" href="popup-options.css" />
<link rel="stylesheet" href="iconfont/material-icons.css" />
<link rel="stylesheet" href="donation.css" />
<script src="popup.js" defer></script>
<script src="popup.mjs" type="module" defer></script>
<script src="table-nowrap.js" defer></script>
</head>

Expand Down
Loading

0 comments on commit f78ef3c

Please sign in to comment.