1 import { WEBSITE_RULES_SUPPORTED_VERSION } from '@proton/pass/constants';
2 import type { ExclusionRules, MaybeNull, WebsiteRules } from '@proton/pass/types';
3 import { isObject } from '@proton/pass/utils/object/is-object';
5 export const validateRules = (data: unknown): data is WebsiteRules => {
6 if (!isObject(data)) return false;
7 if (!('rules' in data) || !('version' in data)) return false;
8 if (data.version !== WEBSITE_RULES_SUPPORTED_VERSION) return false;
10 const { rules } = data;
12 if (!isObject(rules)) return false;
14 return Object.values(rules).every((value) => Array.isArray(value) && value.every((val) => typeof val === 'string'));
17 export const parseRules = (data: MaybeNull<string>): MaybeNull<WebsiteRules> => {
19 if (!data) throw new Error();
20 const rules = JSON.parse(data);
21 if (!validateRules(rules)) throw new Error();
28 /* We will always strip the trailing `/` in order to match
29 * `example.com/path/` to `example.com/path` */
30 export const getRulesForURL = ({ rules }: WebsiteRules, { hostname, pathname }: URL): ExclusionRules => {
31 const withPath = pathname !== '/' ? hostname + pathname.replace(/\/$/, '') : null;
32 const match = rules[hostname] ?? [];
33 return withPath ? match.concat(rules[withPath] ?? []) : match;