Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: List cookies set via document.cookie #146

Merged
merged 19 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/extension/src/icons/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,4 @@ export { default as RelatedWebsiteSetsIcon } from './related-website-sets.svg';
export { default as RelatedWebsiteSetsIconWhite } from './related-website-sets-white.svg';
export { default as AntiCovertTrackingIcon } from './anti-covert-tracking.svg';
export { default as AntiCovertTrackingIconWhite } from './anti-covert-tracking-white.svg';
export { default as Refresh } from './refresh-icon.svg';
3 changes: 3 additions & 0 deletions packages/extension/src/icons/refresh-icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 4 additions & 1 deletion packages/extension/src/localStore/cookieStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ const CookieStore = {
if (_updatedCookies?.[cookieKey]) {
_updatedCookies[cookieKey] = {
...cookie,
headerType:
_updatedCookies[cookieKey].headerType === 'javascript'
? _updatedCookies[cookieKey].headerType
: cookie.headerType,
frameIdList: Array.from(
new Set<number>([
...cookie.frameIdList,
Expand Down Expand Up @@ -84,7 +88,6 @@ const CookieStore = {
*/
async updateTabFocus(tabId: string) {
const storage = await chrome.storage.local.get();

if (storage[tabId]) {
storage[tabId].focusedAt = Date.now();
}
Expand Down
2 changes: 1 addition & 1 deletion packages/extension/src/localStore/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export type CookieData = {
parsedCookie: ParsedCookie;
analytics: CookieAnalytics | null;
url: string;
headerType: 'response' | 'request';
headerType: 'response' | 'request' | 'javascript'; // @todo Change headerType key name.
isFirstParty: boolean | null;
frameIdList: number[];
};
Expand Down
149 changes: 149 additions & 0 deletions packages/extension/src/utils/setDocumentCookies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { isFirstParty } from '@cookie-analysis-tool/common';

/**
* Internal dependencies.
*/
import { createCookieObject } from '../worker/createCookieObject';
import { fetchDictionary, type CookieDatabase } from './fetchCookieDictionary';
import findAnalyticsMatch from '../worker/findAnalyticsMatch';
import { CookieStore, type CookieData } from '../localStore';

interface ProcessAndStoreDucmentCookiesProps {
tabUrlResult: string;
tabId: string;
documentCookies: string[];
dictionary: CookieDatabase;
isException: object;
}

const processAndStoreDocumentCookies = async ({
tabUrlResult,
tabId,
documentCookies,
dictionary,
isException,
}: ProcessAndStoreDucmentCookiesProps) => {
if (!isException && typeof tabUrlResult === 'string') {
const tabUrl = tabUrlResult;

const frames = await chrome.webNavigation.getAllFrames({
tabId: Number(tabId),
});

const outerMostFrame = frames?.filter(
(frame) => frame.frameType === 'outermost_frame'
);

const parsedCookieData: CookieData[] = await Promise.all(
documentCookies.map(async (singleCookie: string) => {
const cookieValue = singleCookie.split('=')[1]?.trim();
const cookieName = singleCookie.split('=')[0]?.trim();
let analytics;

const parsedCookie = await createCookieObject(
{
name: cookieName,
value: cookieValue,
},
tabUrl
);

if (dictionary) {
analytics = findAnalyticsMatch(parsedCookie.name, dictionary);
}

const isFirstPartyCookie = isFirstParty(
parsedCookie.domain || '',
tabUrl
);

return Promise.resolve({
parsedCookie,
analytics:
analytics && Object.keys(analytics).length > 0 ? analytics : null,
url: tabUrl,
headerType: 'javascript', // @todo Update headerType name.
isFirstParty: isFirstPartyCookie || null,
frameIdList: [
outerMostFrame && outerMostFrame[0]
? outerMostFrame[0]?.frameId
: 0,
],
});
})
);

await CookieStore.update(tabId, parsedCookieData);
}
};

/**
* Utility function to get the cookies from result and send it for processing.
* @param result the evaluated value of array of string.
* @param exceptionGenerated Boolean value which specifies if an exception was generated during evaluating the javascript.
* @param tabId Tab ID from which the JS cookies have to be read.
* @param dictionary JSON object which is used to classify cookie based on their use.
*/
const getJSCookiesForProcessing = (
result: string[],
exceptionGenerated: object,
tabId: string,
dictionary: CookieDatabase
) => {
let documentCookies: string[] = [];

if (!exceptionGenerated && result.length > 1) {
documentCookies = result;

chrome.devtools.inspectedWindow.eval(
'window.location.href',
(tabUrlResult: string, isException) =>
processAndStoreDocumentCookies({
tabUrlResult,
tabId,
documentCookies,
dictionary,
isException,
})
);
} else {
return;
}
};

/**
* Adds the cookies set via document.cookie.
* @param tabId Id of the tab being listened to.
*/
async function setDocumentCookies(tabId: string) {
if (!tabId) {
return;
}

const dictionary = await fetchDictionary();

chrome.devtools.inspectedWindow.eval(
'document.cookie.split(";")',
(result: string[], isException) =>
getJSCookiesForProcessing(result, isException, tabId, dictionary)
);
}
export default setDocumentCookies;
101 changes: 26 additions & 75 deletions packages/extension/src/view/devtools/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,90 +22,41 @@ import { Resizable } from 're-resizable';
/**
* Internal dependencies.
*/
import './app.css';
import TABS from './tabs';
import { Sidebar } from './components';
import { useCookieStore } from './stateProviders/syncCookieStore';
import { Button, ProgressBar } from '../design-system/components';
import './app.css';

const App: React.FC = () => {
const [selectedTabIndex, setSelectedTabIndex] = useState<number>(0);
const {
isCurrentTabBeingListenedTo,
returningToSingleTab,
changeListeningToThisTab,
allowedNumberOfTabs,
loading,
} = useCookieStore(({ state, actions }) => ({
isCurrentTabBeingListenedTo: state.isCurrentTabBeingListenedTo,
returningToSingleTab: state.returningToSingleTab,
changeListeningToThisTab: actions.changeListeningToThisTab,
allowedNumberOfTabs: state.allowedNumberOfTabs,
loading: state.loading,
}));
const TabContent = TABS[selectedTabIndex].component;

if (
loading ||
(loading &&
isCurrentTabBeingListenedTo &&
allowedNumberOfTabs &&
allowedNumberOfTabs === 'single')
) {
return (
<div className="w-full h-screen flex items-center justify-center overflow-hidden bg-white dark:bg-raisin-black">
<ProgressBar additionalStyles="w-full" />
</div>
);
}

if (
(isCurrentTabBeingListenedTo &&
allowedNumberOfTabs &&
allowedNumberOfTabs === 'single') ||
(allowedNumberOfTabs && allowedNumberOfTabs === 'unlimited')
) {
return (
<div className="w-full h-screen overflow-hidden bg-white dark:bg-raisin-black">
<div className="w-full h-full flex flex-row">
<Resizable
defaultSize={{ width: '200px', height: '100%' }}
minWidth={'150px'}
maxWidth={'98%'}
enable={{
top: false,
right: true,
bottom: false,
left: false,
topRight: false,
bottomRight: false,
bottomLeft: false,
topLeft: false,
}}
className="h-full flex flex-col pt-0.5 border border-l-0 border-t-0 border-b-0 border-gray-300 dark:border-quartz"
>
<Sidebar
selectedIndex={selectedTabIndex}
setIndex={setSelectedTabIndex}
/>
</Resizable>
<main className="h-full flex-1 overflow-auto">
<TabContent />
</main>
</div>
</div>
);
}

return (
<div className="w-full h-screen overflow-hidden bg-white dark:bg-raisin-black">
<div className="w-full h-full flex flex-col items-center justify-center">
{!returningToSingleTab && (
<p className="dark:text-bright-gray text-chart-label text-base mb-5">
This tool works best with a single tab.
</p>
)}
<Button onClick={changeListeningToThisTab} text="Analyze this tab" />
<div className="w-full h-full flex flex-row">
<Resizable
defaultSize={{ width: '200px', height: '100%' }}
minWidth={'150px'}
maxWidth={'98%'}
enable={{
top: false,
right: true,
bottom: false,
left: false,
topRight: false,
bottomRight: false,
bottomLeft: false,
topLeft: false,
}}
className="h-full flex flex-col pt-0.5 border border-l-0 border-t-0 border-b-0 border-gray-300 dark:border-quartz"
>
<Sidebar
selectedIndex={selectedTabIndex}
setIndex={setSelectedTabIndex}
/>
</Resizable>
<main className="h-full flex-1 overflow-auto">
<TabContent />
</main>
</div>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,22 @@ import FilterIcon from '../../../../../../../../third_party/icons/filter-icon.sv
// eslint-disable-next-line import/no-relative-packages
import CrossIcon from '../../../../../../../../third_party/icons/cross-icon.svg';
import { useFilterManagementStore } from '../../../stateProviders/filterManagementStore';
import { Refresh } from '../../../../../icons';
import { useCookieStore } from '../../../stateProviders/syncCookieStore';
import { type CookieTableData } from '../../../cookies.types';

interface CookieSearchProps {
cookiesAvailable: boolean;
isFilterMenuOpen: boolean;
toggleFilterMenu: () => void;
filteredCookies: CookieTableData[];
}

const CookieSearch = ({
cookiesAvailable,
isFilterMenuOpen,
toggleFilterMenu,
filteredCookies,
}: CookieSearchProps) => {
const { searchTerm, setSearchTerm } = useFilterManagementStore(
({ state, actions }) => ({
Expand All @@ -47,6 +52,10 @@ const CookieSearch = ({
})
);

const { getCookiesSetByJavascript } = useCookieStore(({ actions }) => ({
getCookiesSetByJavascript: actions.getCookiesSetByJavascript,
}));

const handleInput = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setSearchTerm(event.target.value);
Expand Down Expand Up @@ -88,6 +97,13 @@ const CookieSearch = ({
>
<CrossIcon className="text-mischka" />
</button>
<div className="h-full w-px bg-american-silver dark:bg-quartz mx-3" />
<button onClick={getCookiesSetByJavascript} title="Refresh">
<Refresh className="text-mischka" />
</button>
<div className="text-right w-full text-xxxs text-secondary">
Count: {Number(filteredCookies?.length) || 0}
</div>
</div>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const CookiesListing = () => {
cookiesAvailable={cookiesAvailable}
isFilterMenuOpen={isFilterMenuOpen}
toggleFilterMenu={toggleFilterMenu}
filteredCookies={filteredCookies}
/>
{cookiesAvailable && <ChipsBar />}
<div className="w-full flex-1 overflow-hidden">
Expand Down
Loading
Loading