index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/mimetype.ts
import { getBrowser } from '@proton/shared/lib/helpers/browser'; import { MIME_TYPES } from '../constants'; import { SupportedMimeTypes } from '../drive/constants'; const isWebpSupported = () => { const { name, version } = getBrowser(); if (name === 'Safari') { /* * The support for WebP image format became available in Safari 14. * It is not possible to support webp images in older Safari versions. * https://developer.apple.com/documentation/safari-release-notes/safari-14-release-notes */ return Number(version?.split('.')[0]) >= 14; } return true; }; export const isImage = (mimeType: string) => mimeType.startsWith('image/'); export const isExcel = (mimeType: string) => mimeType.startsWith('application/vnd.ms-excel'); export const isWordDocument = (mimeType: string) => mimeType === SupportedMimeTypes.docx; export const isFont = (mimeType: string) => mimeType.startsWith('font/'); export const isSupportedImage = (mimeType: string) => [ SupportedMimeTypes.apng, SupportedMimeTypes.bmp, SupportedMimeTypes.gif, SupportedMimeTypes.ico, SupportedMimeTypes.vdnMicrosoftIcon, SupportedMimeTypes.jpg, SupportedMimeTypes.png, SupportedMimeTypes.svg, isWebpSupported() && SupportedMimeTypes.webp, ] .filter(Boolean) .includes(mimeType as SupportedMimeTypes); export const isSVG = (mimeType: string) => mimeType === SupportedMimeTypes.svg; export const isICS = (mimeType: string) => mimeType.startsWith(MIME_TYPES.ICS) || mimeType.includes(MIME_TYPES.APPLICATION_ICS); export const isSupportedText = (mimeType: string) => mimeType.startsWith('text/') || [ 'application/json', 'application/javascript', 'application/typescript', 'application/x-tex', 'application/x-csh', 'application/x-sh', 'application/x-httpd-php', 'application/xhtml+xml', ].includes(mimeType); export const isVideo = (mimeType: string) => mimeType.startsWith('video/'); export const isAudio = (mimeType: string) => mimeType.startsWith('audio/'); export const isPDF = (mimeType: string) => mimeType === 'application/pdf' || mimeType === 'x-pdf';
8,500
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/newsletter.ts
import { isNumber } from 'lodash'; import { NEWSLETTER_SUBSCRIPTIONS, NEWSLETTER_SUBSCRIPTIONS_BITS, NEWSLETTER_SUBSCRIPTIONS_BY_BITS, } from '../constants'; import { hasBit } from './bitset'; export type NewsletterSubscriptionUpdateData = Partial<Record<NEWSLETTER_SUBSCRIPTIONS, boolean>>; /** * if we have new value, we return it, else we return old value, if it is undefined we return null */ const isProductNewsEnabled = ( flag: NEWSLETTER_SUBSCRIPTIONS_BITS, currentNews: NewsletterSubscriptionUpdateData | number, updatedNews?: NewsletterSubscriptionUpdateData | number ) => { const strFlag = NEWSLETTER_SUBSCRIPTIONS_BY_BITS[flag]; const currentValue = isNumber(currentNews) ? hasBit(currentNews, flag) : currentNews[strFlag]; const updatedValue = isNumber(updatedNews) ? hasBit(updatedNews, flag) : updatedNews?.[strFlag]; return updatedValue ?? currentValue ?? null; }; /** * If one of the product newsletter (Inbox/Drive/Pass/VPN) is enabled, then returns true */ export const isGlobalFeatureNewsEnabled = ( currentNews: NewsletterSubscriptionUpdateData | number, updatedNews?: NewsletterSubscriptionUpdateData | number ) => { return Boolean( isProductNewsEnabled(NEWSLETTER_SUBSCRIPTIONS_BITS.INBOX_NEWS, currentNews, updatedNews) || isProductNewsEnabled(NEWSLETTER_SUBSCRIPTIONS_BITS.DRIVE_NEWS, currentNews, updatedNews) || isProductNewsEnabled(NEWSLETTER_SUBSCRIPTIONS_BITS.PASS_NEWS, currentNews, updatedNews) || isProductNewsEnabled(NEWSLETTER_SUBSCRIPTIONS_BITS.VPN_NEWS, currentNews, updatedNews) ); };
8,501
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/object.ts
/** * Convert { [key: string]: boolean } to bitmap * @param o ex: { announcements: true, features: false, newsletter: false, beta: false } * @returns bitmap */ export const toBitMap = (o: { [key: string]: boolean } = {}): number => Object.keys(o).reduce((acc, key, index) => acc + (Number(o[key]) << index), 0); /** * Define an Object from a bitmap value * @param value bitmap * @param keys ex: ['announcements', 'features', 'newsletter', 'beta'] * @returns ex: { announcements: true, features: false, newsletter: false, beta: false } */ export const fromBitmap = (value: number, keys: string[] = []) => keys.reduce<{ [key: string]: boolean }>((acc, key, index) => { acc[key] = !!(value & (1 << index)); return acc; }, {}); /** * This method creates an object composed of the own and inherited enumerable property paths of object that are not omitted. * @param model The source object. * @param properties Properties to omit. * @retuns Returns a new object. */ export const omit = <T extends object, K extends keyof T>(model: T, properties: readonly K[] = []): Omit<T, K> => { const result = { ...model }; for (let i = 0; i < properties.length; ++i) { delete result[properties[i]]; } return result; }; /** * Review of omit function * @param model The source object. * @param properties Properties to keep. * @return Returns a new object. */ export const pick = <T extends object, K extends keyof T>(model: T, properties: readonly K[] = []) => { const result: Pick<T, K> = {} as any; for (let i = 0; i < properties.length; ++i) { const key = properties[i]; if (key in model) { result[key] = model[key]; } } return result; }; /** * Compare two objects but not deeply */ export const isEquivalent = (a: { [key: string]: any }, b: { [key: string]: any }) => { const aProps = Object.getOwnPropertyNames(a); const bProps = Object.getOwnPropertyNames(b); if (aProps.length !== bProps.length) { return false; } for (let i = 0; i < aProps.length; i++) { const propName = aProps[i]; if (a[propName] !== b[propName]) { return false; } } return true; }; /** * Create a map from a collection */ export const toMap = <T extends { [key: string]: any }, K extends keyof T>( collection: T[] = [], key: K = 'ID' as K ) => { const result: { [key in T[K]]: T } = {} as any; for (let i = 0; i < collection.length; i++) { const item = collection[i]; result[item[key]] = item; } return result; };
8,502
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/onceWithQueue.ts
/** * Ensures that a function returning a promise is only called once at a time. * * If it is called while the previous promise is resolving, another call to the * function will be queued, and run once, with the arguments of the last call * after the previous promise has resolved. The returned promise resolves after * the queued promise resolves. * */ export const onceWithQueue = <R>(fn: () => Promise<R>): (() => Promise<R>) => { let STATE: { promise?: Promise<R>; queued?: Promise<R>; } = {}; const clear = () => { STATE = {}; }; const clearPromise = () => { STATE.promise = undefined; }; const next = (): Promise<R> => { clear(); // eslint-disable-next-line return run(); }; const run = () => { // If a queue has already been set up, update the arguments. if (STATE.queued) { return STATE.queued; } // If a promise is running, set up the queue. if (STATE.promise) { STATE.queued = STATE.promise.then(next); return STATE.queued; } // Cache the promise. STATE.promise = fn(); // Set up independent resolve handlers. STATE.promise.then(clearPromise).catch(clear); return STATE.promise; }; return run; };
8,503
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/organization.ts
import { MEMBER_PERMISSIONS, ORGANIZATION_FLAGS, ORGANIZATION_TWOFA_SETTING } from '../constants'; import { Organization } from '../interfaces'; import { hasBit } from './bitset'; export const isLoyal = (organization: Partial<Organization> = {}) => { return hasBit(organization.Flags, ORGANIZATION_FLAGS.LOYAL); }; export const hasCovid = (organization: Partial<Organization> = {}) => { return hasBit(organization.Flags, ORGANIZATION_FLAGS.COVID); }; export const hasSMTPSubmission = (organization: Partial<Organization> = {}) => { return hasBit(organization.Flags, ORGANIZATION_FLAGS.SMTP_SUBMISSION); }; export const isDissident = (organization: Partial<Organization> = {}) => { return hasBit(organization.Flags, ORGANIZATION_FLAGS.DISSIDENT); }; export const hasNoCycleScheduled = (organization: Partial<Organization> = {}) => { return hasBit(organization.Flags, ORGANIZATION_FLAGS.NO_CYCLE_SCHEDULED); }; export const isProtoneer = (organization: Partial<Organization> = {}) => { return hasBit(organization.Flags, ORGANIZATION_FLAGS.PROTON); }; export const hasBonuses = (organization: Partial<Organization> = {}) => { return !!organization.Flags || !!organization.LoyaltyCounter; }; export const hasTwoFARequiredForAdminOnly = (organization: Partial<Organization> = {}) => { return organization.TwoFactorRequired === ORGANIZATION_TWOFA_SETTING.REQUIRED_ADMIN_ONLY; }; export const hasTwoFARequiredForAll = (organization: Partial<Organization> = {}) => { return organization.TwoFactorRequired === ORGANIZATION_TWOFA_SETTING.REQUIRED_ALL; }; export const humanReadableFlags = (organization: Partial<Organization> = {}) => { let flags = []; if (isLoyal(organization)) { flags.push('Loyal'); } if (hasCovid(organization)) { flags.push('Covid'); } if (hasSMTPSubmission(organization)) { flags.push('SMTP Submission'); } if (isDissident(organization)) { flags.push('Dissident'); } if (hasNoCycleScheduled(organization)) { flags.push('No Cycle Scheduled'); } if (isProtoneer(organization)) { flags.push('Proton'); } return flags.length > 0 ? flags.join(', ') : '-'; }; export const humanReadablePermissions = (organization: Partial<Organization> = {}) => { let permissions = []; if (hasBit(organization.Permissions, MEMBER_PERMISSIONS.MANAGE_FORWARDING)) { permissions.push('Forwarding'); } return permissions.length > 0 ? permissions.join(', ') : '-'; }; export const hasFlag = (organization: Partial<Organization> = {}, mask: number) => { return hasBit(Number(organization.Flags), Number(mask)); }; export const hasPermission = (organization: Partial<Organization> = {}, mask: number) => { return hasBit(Number(organization.Permissions), Number(mask)); }; export const hasOrganizationSetup = (organization: Partial<Organization> = {}) => { return !organization.RequiresKey && !!organization.Name; }; export const hasOrganizationSetupWithKeys = (organization: Partial<Organization> = {}) => { return !!organization.RequiresKey && !!organization.HasKeys; };
8,504
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/planIDs.ts
import { ADDON_NAMES, MEMBER_ADDON_PREFIX, PLANS, PLAN_TYPES } from '../constants'; import { Organization, Plan, PlanIDs, PlansMap } from '../interfaces'; const { MAIL, DRIVE, PASS_PLUS, VPN, VPN_PASS_BUNDLE, FAMILY, NEW_VISIONARY, ENTERPRISE, BUNDLE, BUNDLE_PRO, MAIL_PRO, DRIVE_PRO, VPN_PRO, VPN_BUSINESS, } = PLANS; const NEW_PLANS = [ MAIL, DRIVE, PASS_PLUS, VPN, VPN_PASS_BUNDLE, FAMILY, NEW_VISIONARY, ENTERPRISE, BUNDLE, BUNDLE_PRO, MAIL_PRO, DRIVE_PRO, VPN_PRO, VPN_BUSINESS, ]; export const hasPlanIDs = (planIDs: PlanIDs) => Object.values(planIDs).some((quantity) => quantity > 0); export const clearPlanIDs = (planIDs: PlanIDs): PlanIDs => { return Object.entries(planIDs).reduce<PlanIDs>((acc, [planName, quantity = 0]) => { if (quantity <= 0) { return acc; } acc[planName as keyof PlanIDs] = quantity; return acc; }, {}); }; export const getHasPlanType = (planIDs: PlanIDs, plans: Plan[], planType: PLANS) => { const plan = plans.find(({ Name }) => Name === planType); return plan?.Name ? (planIDs?.[plan.Name] || 0) >= 1 : false; }; export const getPlanFromCheckout = (planIDs: PlanIDs, plansMap: PlansMap): Plan | null => { const planNames = Object.keys(planIDs) as (keyof PlanIDs)[]; for (const planName of planNames) { const plan = plansMap[planName]; if (plan?.Type === PLAN_TYPES.PLAN) { return plan; } } return null; }; export const getSupportedAddons = (planIDs: PlanIDs) => { const supported: Partial<Record<ADDON_NAMES, boolean>> = {}; if (planIDs[MAIL_PRO]) { supported[ADDON_NAMES.MEMBER_MAIL_PRO] = true; } if (planIDs[DRIVE_PRO]) { supported[ADDON_NAMES.MEMBER_DRIVE_PRO] = true; } if (planIDs[BUNDLE_PRO]) { supported[ADDON_NAMES.MEMBER_BUNDLE_PRO] = true; supported[ADDON_NAMES.DOMAIN_BUNDLE_PRO] = true; } if (planIDs[ENTERPRISE]) { supported[ADDON_NAMES.MEMBER_ENTERPRISE] = true; supported[ADDON_NAMES.DOMAIN_ENTERPRISE] = true; } if (planIDs[VPN_PRO]) { supported[ADDON_NAMES.MEMBER_VPN_PRO] = true; } if (planIDs[VPN_BUSINESS]) { supported[ADDON_NAMES.MEMBER_VPN_BUSINESS] = true; supported[ADDON_NAMES.IP_VPN_BUSINESS] = true; } return supported; }; /** * Transfer addons from one plan to another. In different plans, addons have different names * and potentially different resource limits, so they must be converted manually using this function. * * @returns */ export const switchPlan = ({ planIDs, planID, organization, plans, }: { planIDs: PlanIDs; planID?: PLANS | ADDON_NAMES; organization?: Organization; plans: Plan[]; }): PlanIDs => { if (planID === undefined) { return {}; } if (NEW_PLANS.includes(planID as PLANS)) { const newPlanIDs = { [planID]: 1 }; const supportedAddons = getSupportedAddons(newPlanIDs); // Transfer addons Object.keys(supportedAddons).forEach((addon) => { const quantity = planIDs[addon as keyof PlanIDs]; if (quantity) { newPlanIDs[addon] = quantity; } const plan = plans.find(({ Name }) => Name === planID); // Transfer member addons if (addon.startsWith(MEMBER_ADDON_PREFIX) && plan && organization) { const memberAddon = plans.find(({ Name }) => Name === addon); const diffAddresses = (organization.UsedAddresses || 0) - plan.MaxAddresses; const diffSpace = ((organization.UsedMembers > 1 ? organization.AssignedSpace : organization.UsedSpace) || 0) - plan.MaxSpace; // AssignedSpace is the space assigned to members in the organization which count for addon transfer const diffVPN = (organization.UsedVPN || 0) - plan.MaxVPN; const diffMembers = (organization.UsedMembers || 0) - plan.MaxMembers; const diffCalendars = (organization.UsedCalendars || 0) - plan.MaxCalendars; if (memberAddon) { // Find out the smallest number of member addons that could accommodate the previously known usage // of the resources. For example, if the user had 5 addresses, and each member addon only // provides 1 additional address, then we would need to add 5 member addons to cover the previous // usage. The maximum is chosen across all types of resources (space, addresses, VPNs, members, // calendars) so as to ensure that the new plan covers the maximum usage of any single resource. // In addition, we explicitely check how many members were used previously. newPlanIDs[addon] = Math.max( diffSpace > 0 && memberAddon.MaxSpace ? Math.ceil(diffSpace / memberAddon.MaxSpace) : 0, diffAddresses > 0 && memberAddon.MaxAddresses ? Math.ceil(diffAddresses / memberAddon.MaxAddresses) : 0, diffVPN > 0 && memberAddon.MaxVPN ? Math.ceil(diffVPN / memberAddon.MaxVPN) : 0, diffMembers > 0 && memberAddon.MaxMembers ? Math.ceil(diffMembers / memberAddon.MaxMembers) : 0, diffCalendars > 0 && memberAddon.MaxCalendars ? Math.ceil(diffCalendars / memberAddon.MaxCalendars) : 0, (planIDs[ADDON_NAMES.MEMBER_BUNDLE_PRO] || 0) + (planIDs[ADDON_NAMES.MEMBER_DRIVE_PRO] || 0) + (planIDs[ADDON_NAMES.MEMBER_MAIL_PRO] || 0) + (planIDs[ADDON_NAMES.MEMBER_ENTERPRISE] || 0) + (planIDs[ADDON_NAMES.MEMBER_VPN_PRO] || 0) + (planIDs[ADDON_NAMES.MEMBER_VPN_BUSINESS] || 0) ); } } // Transfer domain addons if (addon.startsWith('1domain') && plan && organization) { const domainAddon = plans.find(({ Name }) => Name === addon); const diffDomains = (organization.UsedDomains || 0) - plan.MaxDomains; if (domainAddon) { newPlanIDs[addon] = Math.max( diffDomains > 0 && domainAddon.MaxDomains ? Math.ceil(diffDomains / domainAddon.MaxDomains) : 0, (planIDs[ADDON_NAMES.DOMAIN_ENTERPRISE] || 0) + (planIDs[ADDON_NAMES.DOMAIN_BUNDLE_PRO] || 0) ); } } // '1ip' case remains unhandled. We currently have only one plan with an IP addon, so for now it is not transferable. // When/if we have the other plans with the same addon type, then it must be handled here. }); return clearPlanIDs(newPlanIDs); } return {}; }; export const setQuantity = (planIDs: PlanIDs, planID: PLANS | ADDON_NAMES, newQuantity: number) => { const { [planID]: removedPlan, ...restPlanIDs } = planIDs; if (!newQuantity || newQuantity <= 0) { return restPlanIDs; } return { ...restPlanIDs, [planID]: newQuantity, }; }; export const supportAddons = (planIDs: PlanIDs) => { const supportedAddons = getSupportedAddons(planIDs); return !!Object.keys(supportedAddons).length; }; export const getPlanFromPlanIDs = (plansMap: PlansMap, planIDs: PlanIDs = {}) => { const planID = Object.keys(planIDs).find((planID): planID is keyof PlansMap => { return plansMap[planID as keyof PlansMap]?.Type === PLAN_TYPES.PLAN; }); if (planID) { return plansMap[planID]; } };
8,505
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/preview.ts
// Will include more rules in the future import { hasPDFSupport } from './browser'; import { isAudio, isPDF, isSupportedImage, isSupportedText, isVideo, isWordDocument } from './mimetype'; // The reason to limit preview is because the file needs to be loaded // in memory. At this moment we don't even have any progress bar so // it is better to have reasonable lower limit. // It could be dropped once we support video streaming or dynamic // text loading and other tricks to avoid the need to load it all. export const MAX_PREVIEW_FILE_SIZE = 1024 * 1024 * 100; // Adding a lot of text to DOM crashes or slows down the browser. // Even just 2 MB is enough to hang the browser for a short amount of time. // Someday we'll do text windowing, but for now this will do. export const MAX_PREVIEW_TEXT_SIZE = 1024 * 1024 * 2; export const isPreviewTooLarge = (mimeType?: string, fileSize?: number) => { if (!mimeType || !fileSize) { return false; } const maxSize = isSupportedText(mimeType) ? MAX_PREVIEW_TEXT_SIZE : MAX_PREVIEW_FILE_SIZE; return fileSize >= maxSize; }; export const isPreviewAvailable = (mimeType: string, fileSize?: number) => { return ( (!fileSize || !isPreviewTooLarge(mimeType, fileSize)) && (isSupportedImage(mimeType) || isVideo(mimeType) || isAudio(mimeType) || isSupportedText(mimeType) || (hasPDFSupport() && isPDF(mimeType)) || isWordDocument(mimeType)) ); };
8,506
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/promise.ts
export const wait = (delay: number) => new Promise<void>((resolve) => setTimeout(resolve, delay)); /** * Runs each chunk from a chunks array and waits after each one has run (unless it's the last one). */ export const runChunksDelayed = async <T>( chunks: number[][] = [], cb: (index: number) => Promise<T>, delay: number ) => { const promises = []; for (let i = 0; i < chunks.length; ++i) { promises.push(...chunks[i].map(cb)); if (i !== chunks.length - 1) { await wait(delay); } } return Promise.all(promises); }; export const createPromise = <T>() => { let resolve!: (value: T | PromiseLike<T>) => void; let reject!: (reason?: any) => void; const promise = new Promise<T>((innerResolve, innerReject) => { resolve = innerResolve; reject = innerReject; }); return { promise, resolve, reject }; };
8,507
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/regex.ts
export const escapeRegex = (string: string) => { return string.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); }; export interface MatchChunk { start: number; end: number; } export const getMatches = (regex: RegExp, b: string): MatchChunk[] => { return [...b.matchAll(regex)].map((match) => { const { index = 0 } = match; return { start: index, end: index + match[0].length, }; }); };
8,508
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/runInQueue.ts
/** * Executes functions sequentially, at most `maxProcessing` functions at once. */ async function runInQueue<T>(functions: (() => Promise<T>)[], maxProcessing = 1): Promise<T[]> { const results: T[] = []; let resultIndex = 0; const runNext = async (): Promise<any> => { const index = resultIndex; const executor = functions[index]; if (executor) { resultIndex += 1; return executor().then((result) => { results[index] = result; return runNext(); }); } return Promise.resolve(); }; const promises: Promise<any>[] = []; for (let i = 0; i < maxProcessing; i++) { promises.push(runNext()); } await Promise.all(promises); return results; } export default runInQueue;
8,509
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/scope.ts
import JSBI from 'jsbi'; export const hasScope = (scope: string, mask: number | string) => { const scopeInt = JSBI.BigInt(scope); const maskInt = JSBI.BigInt(mask); return JSBI.equal(JSBI.bitwiseAnd(scopeInt, maskInt), maskInt); };
8,510
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/secureSessionStorage.ts
// Not using openpgp to allow using this without having to depend on openpgp being loaded import { stringToUint8Array, uint8ArrayToString } from './encoding'; import { hasStorage as hasSessionStorage } from './sessionStorage'; /** * Partially inspired by http://www.thomasfrank.se/sessionvars.html * However, we aim to deliberately be non-persistent. This is useful for * data that wants to be preserved across refreshes, but is too sensitive * to be safely written to disk. Unfortunately, although sessionStorage is * deleted when a session ends, major browsers automatically write it * to disk to enable a session recovery feature, so using sessionStorage * alone is inappropriate. * * To achieve this, we do two tricks. The first trick is to delay writing * any possibly persistent data until the user is actually leaving the * page (onunload). This already prevents any persistence in the face of * crashes, and severely limits the lifetime of any data in possibly * persistent form on refresh. * * The second, more important trick is to split sensitive data between * window.name and sessionStorage. window.name is a property that, like * sessionStorage, is preserved across refresh and navigation within the * same tab - however, it seems to never be stored persistently. This * provides exactly the lifetime we want. Unfortunately, window.name is * readable and transferable between domains, so any sensitive data stored * in it would leak to random other websites. * * To avoid this leakage, we split sensitive data into two shares which * xor to the sensitive information but which individually are completely * random and give away nothing. One share is stored in window.name, while * the other share is stored in sessionStorage. This construction provides * security that is the best of both worlds - random websites can't read * the data since they can't access sessionStorage, while disk inspections * can't read the data since they can't access window.name. The lifetime * of the data is therefore the smaller lifetime, that of window.name. */ const deserialize = (string: string) => { try { return JSON.parse(string); } catch (e: any) { return {}; } }; const serialize = (data: any) => JSON.stringify(data); const deserializeItem = (value: string | undefined) => { if (value === undefined) { return; } try { return stringToUint8Array(atob(value)); } catch (e: any) { return undefined; } }; const serializeItem = (value: Uint8Array) => { return btoa(uint8ArrayToString(value)); }; const mergePart = (serializedA: string | undefined, serializedB: string | undefined) => { const a = deserializeItem(serializedA); const b = deserializeItem(serializedB); if (a === undefined || b === undefined || a.length !== b.length) { return; } const xored = new Uint8Array(b.length); for (let j = 0; j < b.length; j++) { xored[j] = b[j] ^ a[j]; } // Strip off padding let unpaddedLength = b.length; while (unpaddedLength > 0 && xored[unpaddedLength - 1] === 0) { unpaddedLength--; } return uint8ArrayToString(xored.slice(0, unpaddedLength)); }; export const mergeParts = (share1: any, share2: any) => Object.keys(share1).reduce<{ [key: string]: string }>((acc, key) => { const value = mergePart(share1[key], share2[key]); if (value === undefined) { return acc; } acc[key] = value; return acc; }, {}); const separatePart = (value: string) => { const item = stringToUint8Array(value); const paddedLength = Math.ceil(item.length / 256) * 256; const share1 = crypto.getRandomValues(new Uint8Array(paddedLength)); const share2 = new Uint8Array(share1); for (let i = 0; i < item.length; i++) { share2[i] ^= item[i]; } return [serializeItem(share1), serializeItem(share2)]; }; export const separateParts = (data: any) => Object.keys(data).reduce<{ share1: { [key: string]: any }; share2: { [key: string]: any } }>( (acc, key) => { const value = data[key]; if (value === undefined) { return acc; } const [share1, share2] = separatePart(value); acc.share1[key] = share1; acc.share2[key] = share2; return acc; }, { share1: {}, share2: {} } ); const SESSION_STORAGE_KEY = 'proton:storage'; export const save = (data: any) => { if (!hasSessionStorage()) { return; } const [share1, share2] = separatePart(JSON.stringify(data)); window.name = serialize(share1); window.sessionStorage.setItem(SESSION_STORAGE_KEY, share2); }; export const load = () => { if (!hasSessionStorage()) { return {}; } try { const share1 = deserialize(window.name); const share2 = window.sessionStorage.getItem(SESSION_STORAGE_KEY) || ''; window.name = ''; window.sessionStorage.removeItem(SESSION_STORAGE_KEY); const string = mergePart(share1, share2) || ''; const parsedValue = JSON.parse(string) || {}; if (parsedValue === Object(parsedValue)) { return parsedValue; } return {}; } catch { return {}; } };
8,511
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/sentry.ts
import { BrowserOptions, Integrations as SentryIntegrations, captureException, configureScope, init, makeFetchTransport, captureMessage as sentryCaptureMessage, } from '@sentry/browser'; import { BrowserTransportOptions } from '@sentry/browser/types/transports/types'; import { VPN_HOSTNAME } from '../constants'; import { ApiError } from '../fetch/ApiError'; import { getUIDHeaders } from '../fetch/headers'; import { ProtonConfig } from '../interfaces'; import { isElectronApp } from './desktop'; type SentryContext = { authHeaders: { [key: string]: string }; enabled: boolean; }; type SentryConfig = { host: string; release: string; environment: string; }; type SentryDenyUrls = BrowserOptions['denyUrls']; type SentryIgnoreErrors = BrowserOptions['ignoreErrors']; type SentryOptions = { sessionTracking?: boolean; config: ProtonConfig; uid?: string; sentryConfig?: SentryConfig; ignore?: (config: SentryConfig) => boolean; denyUrls?: SentryDenyUrls; ignoreErrors?: SentryIgnoreErrors; }; const context: SentryContext = { authHeaders: {}, enabled: true, }; export const setUID = (uid: string | undefined) => { context.authHeaders = uid ? getUIDHeaders(uid) : {}; }; export const setSentryEnabled = (enabled: boolean) => { context.enabled = enabled; }; type FirstFetchParameter = Parameters<typeof fetch>[0]; export const getContentTypeHeaders = (input: FirstFetchParameter): HeadersInit => { const url = input.toString(); /** * The sentry library does not append the content-type header to requests. The documentation states * what routes accept what content-type. Those content-type headers are also expected through our sentry tunnel. */ if (url.includes('/envelope/')) { return { 'content-type': 'application/x-sentry-envelope' }; } if (url.includes('/store/')) { return { 'content-type': 'application/json' }; } return {}; }; const sentryFetch: typeof fetch = (input, init?) => { // Force the input type due to node.js fetch types not being compatible with libdom.d.ts // https://github.com/nodejs/undici/issues/1943 return globalThis.fetch(input as FirstFetchParameter, { ...init, headers: { ...init?.headers, ...getContentTypeHeaders(input as FirstFetchParameter), ...context.authHeaders, }, }); }; const makeProtonFetchTransport = (options: BrowserTransportOptions) => { return makeFetchTransport(options, sentryFetch); }; const isLocalhost = (host: string) => host.startsWith('localhost'); const isProduction = (host: string) => host.endsWith('.proton.me') || host === VPN_HOSTNAME; const getDefaultSentryConfig = ({ APP_VERSION, COMMIT }: ProtonConfig): SentryConfig => { const { host } = window.location; return { host, release: isProduction(host) ? APP_VERSION : COMMIT, environment: host.split('.').splice(1).join('.'), }; }; const getDefaultDenyUrls = (): SentryDenyUrls => { return [ // Google Adsense /pagead\/js/i, // Facebook flakiness /graph\.facebook\.com/i, // Facebook blocked /connect\.facebook\.net\/en_US\/all\.js/i, // Woopra flakiness /eatdifferent\.com\.woopra-ns\.com/i, /static\.woopra\.com\/js\/woopra\.js/i, // Chrome extensions /extensions\//i, /^chrome:\/\//i, /^chrome-extension:\/\//i, // Other plugins /127\.0\.0\.1:4001\/isrunning/i, // Cacaoweb /webappstoolbarba\.texthelp\.com\//i, /metrics\.itunes\.apple\.com\.edgesuite\.net\//i, ]; }; const getDefaultIgnoreErrors = (): SentryIgnoreErrors => { return [ // Ignore random plugins/extensions 'top.GLOBALS', 'canvas.contentDocument', 'MyApp_RemoveAllHighlights', 'atomicFindClose', // See http://toolbar.conduit.com/Developer/HtmlAndGadget/Methods/JSInjection.aspx 'conduitPage', // https://bugzilla.mozilla.org/show_bug.cgi?id=1678243 'XDR encoding failure', 'Request timed out', 'No network connection', 'Failed to fetch', 'Load failed', 'NetworkError when attempting to fetch resource.', 'webkitExitFullScreen', // Bug in Firefox for iOS. 'InactiveSession', 'UnhandledRejection', // Happens too often in extensions and we have lints for that, so should be safe to ignore. /chrome-extension/, /moz-extension/, 'TransferCancel', // User action to interrupt upload or download in Drive. 'UploadConflictError', // User uploading the same file again in Drive. 'UploadUserError', // Upload error on user's side in Drive. 'ValidationError', // Validation error on user's side in Drive. 'ChunkLoadError', // WebPack loading source code. /ResizeObserver loop/, // Chromium bug https://stackoverflow.com/questions/49384120/resizeobserver-loop-limit-exceeded // See: http://blog.errorception.com/2012/03/tale-of-unfindable-js-error.html 'originalCreateNotification', 'http://tt.epicplay.com', "Can't find variable: ZiteReader", 'jigsaw is not defined', 'ComboSearch is not defined', 'http://loading.retry.widdit.com/', // Facebook borked 'fb_xd_fragment', // ISP "optimizing" proxy - `Cache-Control: no-transform` seems to reduce this. (thanks @acdha) // See http://stackoverflow.com/questions/4113268/how-to-stop-javascript-injection-from-vodafone-proxy 'bmi_SafeAddOnload', 'EBCallBackMessageReceived', // Avast extension error '_avast_submit', 'AbortError', ]; }; function main({ uid, config, sessionTracking = false, sentryConfig = getDefaultSentryConfig(config), ignore = ({ host }) => isLocalhost(host), denyUrls = getDefaultDenyUrls(), ignoreErrors = getDefaultIgnoreErrors(), }: SentryOptions) { const { SENTRY_DSN, SENTRY_DESKTOP_DSN, APP_VERSION } = config; const isElectron = isElectronApp(); const sentryDSN = isElectron ? SENTRY_DESKTOP_DSN || SENTRY_DSN : SENTRY_DSN; const { host, release, environment } = sentryConfig; // No need to configure it if we don't load the DSN if (!sentryDSN || ignore(sentryConfig)) { return; } setUID(uid); // Assumes sentryDSN is: https://111b3eeaaec34cae8e812df705690a36@sentry/11 // To get https://[email protected]/api/core/v4/reports/sentry/11 const dsn = sentryDSN.replace('sentry', `${host}/api/core/v4/reports/sentry`); init({ dsn, release, environment, normalizeDepth: 5, transport: makeProtonFetchTransport, autoSessionTracking: sessionTracking, // do not log calls to console.log, console.error, etc. integrations: [ new SentryIntegrations.Breadcrumbs({ console: false, }), ], // Disable client reports. Client reports are used by sentry to retry events that failed to send on visibility change. // Unfortunately Sentry does not use the custom transport for those, and thus fails to add the headers the API requires. sendClientReports: false, beforeSend(event, hint) { const error = hint?.originalException as any; const stack = typeof error === 'string' ? error : error?.stack; // Filter out broken ferdi errors if (stack && stack.match(/ferdi|franz/i)) { return null; } // Not interested in uncaught API errors, or known errors if (error instanceof ApiError || error?.trace === false) { return null; } if (!context.enabled) { return null; } // Remove the hash from the request URL and navigation breadcrumbs to avoid // leaking the search parameters of encrypted searches if (event.request && event.request.url) { [event.request.url] = event.request.url.split('#'); } if (event.breadcrumbs) { event.breadcrumbs = event.breadcrumbs.map((breadcrumb) => { if (breadcrumb.category === 'navigation' && breadcrumb.data) { [breadcrumb.data.from] = breadcrumb.data.from.split('#'); [breadcrumb.data.to] = breadcrumb.data.to.split('#'); } return breadcrumb; }); } return event; }, // Some ignoreErrors and denyUrls are taken from this gist: https://gist.github.com/Chocksy/e9b2cdd4afc2aadc7989762c4b8b495a // This gist is suggested in the Sentry documentation: https://docs.sentry.io/clients/javascript/tips/#decluttering-sentry ignoreErrors, denyUrls, }); configureScope((scope) => { scope.setTag('appVersion', APP_VERSION); }); } export const traceError = (...args: Parameters<typeof captureException>) => { if (!isLocalhost(window.location.host)) { captureException(...args); } }; export const captureMessage = (...args: Parameters<typeof sentryCaptureMessage>) => { if (!isLocalhost(window.location.host)) { sentryCaptureMessage(...args); } }; export default main;
8,512
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/sessionStorage.ts
export const getItem = (key: string, defaultValue?: string) => { try { const value = window.sessionStorage.getItem(key); return value === null ? defaultValue : value; } catch (e: any) { return defaultValue; } }; export const setItem = (key: string, value: string) => { try { window.sessionStorage.setItem(key, value); } catch (e: any) { return undefined; } }; export const removeItem = (key: string) => { try { window.sessionStorage.removeItem(key); } catch (e: any) { return undefined; } }; export const hasStorage = (key = 'test') => { try { window.sessionStorage.setItem(key, key); window.sessionStorage.removeItem(key); return true; } catch (e: any) { return false; } };
8,513
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/setupCryptoWorker.ts
import { CryptoProxy } from '@proton/crypto'; import { CryptoWorkerPool, WorkerPoolInterface } from '@proton/crypto/lib/worker/workerPool'; import { hasModulesSupport, isIos11, isSafari11 } from './browser'; let promise: undefined | Promise<void>; const isUnsupportedWorker = () => { // In safari 11 there's an unknown problem. // In iOS there's a bug that prevents the worker from functioning properly. return isSafari11() || isIos11(); }; /** * Initialize worker pool and set it as CryptoProxy endpoint. * If workers are not supported by the current browser, the pmcrypto API is imported instead. */ const init = async (options?: Parameters<WorkerPoolInterface['init']>[0]) => { const isCompat = !hasModulesSupport(); // Compat browsers do not support the worker. if (isCompat || isUnsupportedWorker()) { // dynamic import needed to avoid loading openpgp into the main thread, unless we get here const { Api: CryptoApi } = await import( /* webpackChunkName: "crypto-worker-api" */ '@proton/crypto/lib/worker/api' ); CryptoApi.init(); CryptoProxy.setEndpoint(new CryptoApi(), (endpoint) => endpoint.clearKeyStore()); } else { await CryptoWorkerPool.init(options); CryptoProxy.setEndpoint(CryptoWorkerPool, (endpoint) => endpoint.destroy()); } }; /** * Start crypto worker and set it as `CryptoProxy` endpoint. * If the crypto worker was already loaded, this function is a no-op. * If the browser does not support workers, the pmcrypto API (including OpenPGP.js) is loaded directly in the main thread. * @returns init promise singleton */ export const loadCryptoWorker = (options?: Parameters<typeof init>[0]) => { if (!promise) { promise = init(options); } return promise; }; /** * Release crypto worker as `CryptoProxy` endpoint, then clear the key store and terminate the worker. */ export const destroyCryptoWorker = () => { promise = undefined; return CryptoProxy.releaseEndpoint(); };
8,514
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/storage.ts
export const getItem = (key: string, defaultValue?: string) => { try { const value = window.localStorage.getItem(key); return value === undefined ? defaultValue : value; } catch (e: any) { return defaultValue; } }; export const setItem = (key: string, value: string) => { try { window.localStorage.setItem(key, value); } catch (e: any) { return undefined; } }; export const removeItem = (key: string) => { try { window.localStorage.removeItem(key); } catch (e: any) { return undefined; } }; export const hasStorage = (key = 'test') => { try { window.localStorage.setItem(key, key); window.localStorage.removeItem(key); return true; } catch (e: any) { return false; } };
8,515
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/store.ts
export default (initialState: { [key: string]: any } = {}) => { let state = initialState; const set = (key: string, data: any) => { state[key] = data; }; const get = (key: string) => state[key]; const remove = (key: string) => delete state[key]; const reset = () => { state = {}; }; return { set, get, remove, reset, getState: () => state, }; };
8,516
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/string.ts
enum CURRENCIES { USD = '$', EUR = '€', CHF = 'CHF', } export const normalize = (value = '', removeDiacritics = false) => { let normalized = value.toLowerCase().trim(); if (removeDiacritics) { normalized = normalized.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); } return normalized; }; export const replaceLineBreak = (content = '') => content.replace(/(?:\r\n|\r|\n)/g, '<br />'); export const toCRLF = (str: string) => str.replace(/\n/g, '\r\n'); export const toPrice = (amount = 0, currency: keyof typeof CURRENCIES = 'EUR', divisor = 100) => { const symbol = CURRENCIES[currency] || currency; const value = Number(amount / divisor).toFixed(2); const prefix = +value < 0 ? '-' : ''; const absValue = Math.abs(+value); if (currency === 'USD') { return `${prefix}${symbol}${absValue}`; } return `${prefix}${absValue} ${symbol}`; }; export const addPlus = ([first = '', ...rest] = []) => { return [first, rest.length && `+${rest.length}`].filter(Boolean).join(', '); }; export const DEFAULT_TRUNCATE_OMISSION = '…'; /** * Given a maximum number of characters to capture from a string at the start and end of it, * truncate the string by adding omission if too long. If only a maximum number of characters * is passed, the string is truncated by adding omission in the middle of it if too long */ export const truncateMore = ({ string, charsToDisplay, charsToDisplayStart = 0, charsToDisplayEnd = 0, omission = '…', skewEnd = false, }: { string: string; charsToDisplay?: number; charsToDisplayStart?: number; charsToDisplayEnd?: number; omission?: string; skewEnd?: boolean; }): string => { if (string.length === 0) { return string; } if (charsToDisplay !== undefined) { // truncate symmetrically const visibleChars = charsToDisplay - omission.length; const charsToDisplayStart = skewEnd ? Math.floor(visibleChars / 2) : Math.ceil(visibleChars / 2); const charsToDisplayEnd = visibleChars - charsToDisplayStart; return truncateMore({ string, charsToDisplayStart, charsToDisplayEnd, omission }); } if (string.length <= charsToDisplayStart + charsToDisplayEnd + omission.length) { return string; } const strBegin = string.substring(0, charsToDisplayStart); const strEnd = string.substring(string.length - charsToDisplayEnd, string.length); return strBegin + omission + strEnd; }; export const truncatePossiblyQuotedString = (string: string, charsToDisplay: number) => { const match = string.match(/^"(.+)"$/); if (!match) { return truncateMore({ string, charsToDisplay }); } const [, quotedString] = match; return `"${truncateMore({ string: quotedString, charsToDisplay: charsToDisplay - 2 })}"`; }; export const getInitials = (fullName = '') => { const [first, ...rest] = fullName .replace(/\s{2,}/g, ' ') .split(' ') .filter((word = '') => !/^[.,/#!$@%^&*;:{}=\-_`~()]/g.test(word)); const last = rest[rest.length - 1]; const initials = [first, last] .filter(Boolean) .map((letter = '') => [...letter.toUpperCase()][0]) // We use the spread operator to support Unicode characters .join(''); if (!initials) { return '?'; } return initials; }; export const hasProtonDomain = (email = '') => { return /@(protonmail\.(com|ch)|proton\.(me|ch)|pm\.me|)$/i.test(email); }; const getMatchingCharacters = (string: string, substring: string) => { let i; for (i = 0; i < substring.length; ++i) { if (string[i] !== substring[i]) { return i; } } return i > 0 ? i : 0; }; export const findLongestMatchingIndex = (strings: string[] = [], substring = '') => { let max = 0; let i = -1; strings.forEach((string, idx) => { const numberOfMatches = getMatchingCharacters(string, substring); if (numberOfMatches > max) { max = numberOfMatches; i = idx; } }); return i; }; export const stripLeadingSlash = (str: string) => str.replace(/^\/+/g, ''); export const stripTrailingSlash = (str: string) => str.replace(/\/+$/g, ''); export const stripLeadingAndTrailingSlash = (str: string) => str.replace(/^\/+|\/+$/g, ''); export const removeDiacritics = (str: string) => { return str.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); }; /** * Replace LTR and RTL override unicode chars which can lead to security issues on filenames * 202D and 202E should be the only unicode chars concerned * https://jira.protontech.ch/browse/SEC-644 */ export const rtlSanitize = (str: string) => { return str.replace(/[\u202D\u202E]/g, '_'); }; export const removeHTMLComments = (str: string) => { return str.replace(/<!--[\s\S]*?-->/g, ''); };
8,517
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/subscription.ts
import { addWeeks, fromUnixTime, isBefore } from 'date-fns'; import { ProductParam } from '@proton/shared/lib/apps/product'; import { ADDON_NAMES, APPS, APP_NAMES, COUPON_CODES, CYCLE, FreeSubscription, IPS_INCLUDED_IN_PLAN, MEMBER_ADDON_PREFIX, PLANS, PLAN_SERVICES, PLAN_TYPES, isFreeSubscription, } from '../constants'; import { External, Plan, PlanIDs, PlansMap, Pricing, Subscription, SubscriptionModel } from '../interfaces'; import { hasBit } from './bitset'; const { PLAN, ADDON } = PLAN_TYPES; const { PLUS, VPNPLUS, VPNBASIC, PROFESSIONAL, VISIONARY, NEW_VISIONARY, MAIL, MAIL_PRO, DRIVE, DRIVE_PRO, PASS_PLUS, VPN, VPN_PASS_BUNDLE, ENTERPRISE, BUNDLE, BUNDLE_PRO, FAMILY, VPN_PRO, VPN_BUSINESS, } = PLANS; export const getPlan = (subscription: Subscription | undefined, service?: PLAN_SERVICES) => { const result = (subscription?.Plans || []).find( ({ Services, Type }) => Type === PLAN && (service === undefined ? true : hasBit(Services, service)) ); if (result) { return result as Plan & { Name: PLANS }; } return result; }; export const getAddons = (subscription: Subscription | undefined) => (subscription?.Plans || []).filter(({ Type }) => Type === ADDON); export const hasAddons = (subscription: Subscription | undefined) => (subscription?.Plans || []).some(({ Type }) => Type === ADDON); export const getPlanName = (subscription: Subscription | undefined, service: PLAN_SERVICES) => { const plan = getPlan(subscription, service); return plan?.Name; }; export const getPlanTitle = (subscription: Subscription | undefined) => { const plan = getPlan(subscription); return plan?.Title; }; export const hasSomePlan = (subscription: Subscription | FreeSubscription | undefined, planName: PLANS) => { if (isFreeSubscription(subscription)) { return false; } return (subscription?.Plans || []).some(({ Name }) => Name === planName); }; export const hasLifetime = (subscription: Subscription | undefined) => { return subscription?.CouponCode === COUPON_CODES.LIFETIME; }; export const hasMigrationDiscount = (subscription: Subscription) => { return subscription?.CouponCode?.startsWith('MIGRATION'); }; export const isManagedExternally = ( subscription: Subscription | FreeSubscription | Pick<Subscription, 'External'> | undefined | null ): boolean => { if (!subscription || isFreeSubscription(subscription)) { return false; } return subscription.External === External.Android || subscription.External === External.iOS; }; export const hasVisionary = (subscription: Subscription | undefined) => hasSomePlan(subscription, VISIONARY); export const hasNewVisionary = (subscription: Subscription | undefined) => hasSomePlan(subscription, NEW_VISIONARY); export const hasVPN = (subscription: Subscription | undefined) => hasSomePlan(subscription, VPN); export const hasVPNPassBundle = (subscription: Subscription | undefined) => hasSomePlan(subscription, VPN_PASS_BUNDLE); export const hasMail = (subscription: Subscription | undefined) => hasSomePlan(subscription, MAIL); export const hasMailPro = (subscription: Subscription | undefined) => hasSomePlan(subscription, MAIL_PRO); export const hasDrive = (subscription: Subscription | undefined) => hasSomePlan(subscription, DRIVE); export const hasDrivePro = (subscription: Subscription | undefined) => hasSomePlan(subscription, DRIVE_PRO); export const hasPassPlus = (subscription: Subscription | undefined) => hasSomePlan(subscription, PASS_PLUS); export const hasEnterprise = (subscription: Subscription | undefined) => hasSomePlan(subscription, ENTERPRISE); export const hasBundle = (subscription: Subscription | undefined) => hasSomePlan(subscription, BUNDLE); export const hasBundlePro = (subscription: Subscription | undefined) => hasSomePlan(subscription, BUNDLE_PRO); export const hasMailPlus = (subscription: Subscription | undefined) => hasSomePlan(subscription, PLUS); export const hasMailProfessional = (subscription: Subscription | undefined) => hasSomePlan(subscription, PROFESSIONAL); export const hasVpnBasic = (subscription: Subscription | undefined) => hasSomePlan(subscription, VPNBASIC); export const hasVpnPlus = (subscription: Subscription | undefined) => hasSomePlan(subscription, VPNPLUS); export const hasFamily = (subscription: Subscription | undefined) => hasSomePlan(subscription, FAMILY); export const hasVpnPro = (subscription: Subscription | FreeSubscription | undefined) => hasSomePlan(subscription, VPN_PRO); export const hasVpnBusiness = (subscription: Subscription | FreeSubscription | undefined) => hasSomePlan(subscription, VPN_BUSINESS); export const hasFree = (subscription: Subscription | undefined) => (subscription?.Plans || []).length === 0; export const getUpgradedPlan = (subscription: Subscription | undefined, app: ProductParam) => { if (hasFree(subscription)) { switch (app) { case APPS.PROTONPASS: return PLANS.PASS_PLUS; case APPS.PROTONDRIVE: return PLANS.DRIVE; case APPS.PROTONVPN_SETTINGS: return PLANS.VPN; default: case APPS.PROTONMAIL: return PLANS.MAIL; } } if (hasBundle(subscription) || hasBundlePro(subscription)) { return PLANS.BUNDLE_PRO; } return PLANS.BUNDLE; }; export const getIsB2BPlan = (planName: PLANS | ADDON_NAMES) => { return [MAIL_PRO, DRIVE_PRO, BUNDLE_PRO, ENTERPRISE, VPN_PRO, VPN_BUSINESS].includes(planName as any); }; export const getIsVpnB2BPlan = (planName: PLANS | ADDON_NAMES) => { return [VPN_PRO, VPN_BUSINESS].includes(planName as any); }; export const getIsLegacyPlan = (planName: PLANS | ADDON_NAMES) => { return [VPNBASIC, VPNPLUS, PLUS, PROFESSIONAL, VISIONARY].includes(planName as any); }; export const getHasB2BPlan = (subscription: Subscription | undefined) => { return !!subscription?.Plans?.some(({ Name }) => getIsB2BPlan(Name)); }; export const getHasVpnB2BPlan = (subscription: Subscription | FreeSubscription | undefined) => { return hasVpnPro(subscription) || hasVpnBusiness(subscription); }; export const getHasLegacyPlans = (subscription: Subscription | undefined) => { return !!subscription?.Plans?.some(({ Name }) => getIsLegacyPlan(Name)); }; export const getPrimaryPlan = (subscription: Subscription | undefined, app: APP_NAMES) => { if (!subscription) { return; } if (getHasLegacyPlans(subscription)) { const mailPlan = getPlan(subscription, PLAN_SERVICES.MAIL); const vpnPlan = getPlan(subscription, PLAN_SERVICES.VPN); if (app === APPS.PROTONVPN_SETTINGS) { return vpnPlan || mailPlan; } return mailPlan || vpnPlan; } return getPlan(subscription); }; export const getBaseAmount = ( name: PLANS | ADDON_NAMES, plansMap: PlansMap, subscription: Subscription | undefined, cycle = CYCLE.MONTHLY ) => { const base = plansMap[name]; if (!base) { return 0; } return (subscription?.Plans || []) .filter(({ Name }) => Name === name) .reduce((acc) => { const pricePerCycle = base.Pricing[cycle] || 0; return acc + pricePerCycle; }, 0); }; export const getPlanIDs = (subscription: Subscription | undefined | null): PlanIDs => { return (subscription?.Plans || []).reduce<PlanIDs>((acc, { Name, Quantity }) => { acc[Name] = (acc[Name] || 0) + Quantity; return acc; }, {}); }; export const isTrial = (subscription: Subscription | undefined) => { return subscription?.CouponCode === COUPON_CODES.REFERRAL; }; export const isTrialExpired = (subscription: Subscription | undefined) => { const now = new Date(); return now > fromUnixTime(subscription?.PeriodEnd || 0); }; export const willTrialExpire = (subscription: Subscription | undefined) => { const now = new Date(); return isBefore(fromUnixTime(subscription?.PeriodEnd || 0), addWeeks(now, 1)); }; export const hasBlackFridayDiscount = (subscription: Subscription | undefined) => { return [ COUPON_CODES.BLACK_FRIDAY_2022, COUPON_CODES.MAIL_BLACK_FRIDAY_2022, COUPON_CODES.VPN_BLACK_FRIDAY_2022, ].includes(subscription?.CouponCode as COUPON_CODES); }; export const hasVPNBlackFridayDiscount = (subscription: Subscription | undefined) => { return subscription?.CouponCode === COUPON_CODES.VPN_BLACK_FRIDAY_2022; }; export const hasMailBlackFridayDiscount = (subscription: Subscription | undefined) => { return subscription?.CouponCode === COUPON_CODES.MAIL_BLACK_FRIDAY_2022; }; export const allCycles = [CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.TWO_YEARS, CYCLE.FIFTEEN, CYCLE.THIRTY]; export const customCycles = [CYCLE.FIFTEEN, CYCLE.THIRTY]; export const regularCycles = allCycles.filter((cycle) => !customCycles.includes(cycle)); export const getValidCycle = (cycle: number): CYCLE | undefined => { return allCycles.includes(cycle) ? cycle : undefined; }; export const getIsCustomCycle = (subscription?: Subscription) => { return customCycles.includes(subscription?.Cycle as any); }; export function getNormalCycleFromCustomCycle(cycle: CYCLE): CYCLE; export function getNormalCycleFromCustomCycle(cycle: CYCLE | undefined): CYCLE | undefined { if (!cycle) { return undefined; } if (cycle === CYCLE.FIFTEEN) { return CYCLE.YEARLY; } if (cycle === CYCLE.THIRTY) { return CYCLE.TWO_YEARS; } return cycle; } export const hasYearly = (subscription?: Subscription) => { return subscription?.Cycle === CYCLE.YEARLY; }; export const hasMonthly = (subscription?: Subscription) => { return subscription?.Cycle === CYCLE.MONTHLY; }; export const hasTwoYears = (subscription?: Subscription) => { return subscription?.Cycle === CYCLE.TWO_YEARS; }; export const hasFifteen = (subscription?: Subscription) => { return subscription?.Cycle === CYCLE.FIFTEEN; }; export const hasThirty = (subscription?: Subscription) => { return subscription?.Cycle === CYCLE.THIRTY; }; interface PricingForCycles { [CYCLE.MONTHLY]: number; [CYCLE.YEARLY]: number; [CYCLE.TWO_YEARS]: number; [CYCLE.FIFTEEN]: number; [CYCLE.THIRTY]: number; } export interface AggregatedPricing { all: PricingForCycles; defaultMonthlyPrice: number; /** * That's pricing that counts only aggregate of cost for members. That's useful for rendering of * "per user per month" pricing. * Examples: * - If you have a B2C plan with 1 user, then this price will be the same as `all`. * - If you have Mail Plus plan with several users, then this price will be the same as `all`, because each * additional member counts to the price of members. * - If you have Bundle Pro with several users and with the default (minimum) number of custom domains, then * this price will be the same as `all`. * * Here things become different: * - If you have Bundle Pro with several users and with more than the default (minimum) number of custom domains, * then this price will be `all - extra custom domains price`. * - For VPN Business the behavior is more complex. It also has two addons: member and IPs/servers. By default it * has 2 members and 1 IP. The price for members should exclude price for the 1 default IP. */ members: PricingForCycles; membersNumber: number; plans: PricingForCycles; } function isMultiUserPersonalPlan(plan: Plan) { // even though Family and Visionary plans can have up to 6 users in the org, // for the price displaying purposes we count it as 1 member. return plan.Name === PLANS.FAMILY || plan.Name === PLANS.VISIONARY || plan.Name === PLANS.NEW_VISIONARY; } function getPlanMembers(plan: Plan, quantity: number): number { const hasMembers = plan.Type === PLAN_TYPES.PLAN || (plan.Type === PLAN_TYPES.ADDON && plan.Name.startsWith(MEMBER_ADDON_PREFIX)); let membersNumberInPlan = 0; if (isMultiUserPersonalPlan(plan)) { membersNumberInPlan = 1; } else if (hasMembers) { membersNumberInPlan = plan.MaxMembers || 1; } return membersNumberInPlan * quantity; } export const INCLUDED_IP_PRICING = { [CYCLE.MONTHLY]: 4999, [CYCLE.YEARLY]: 3999 * CYCLE.YEARLY, [CYCLE.TWO_YEARS]: 3599 * CYCLE.TWO_YEARS, }; function getIpPrice(cycle: CYCLE): number { if (cycle === CYCLE.MONTHLY) { return INCLUDED_IP_PRICING[CYCLE.MONTHLY]; } if (cycle === CYCLE.YEARLY) { return INCLUDED_IP_PRICING[CYCLE.YEARLY]; } if (cycle === CYCLE.TWO_YEARS) { return INCLUDED_IP_PRICING[CYCLE.TWO_YEARS]; } return 0; } export function getIpPricePerMonth(cycle: CYCLE): number { return getIpPrice(cycle) / cycle; } export function getPricePerMember(plan: Plan, cycle: CYCLE): number { const totalPrice = plan.Pricing[cycle] || 0; if (plan.Name === PLANS.VPN_BUSINESS) { // For VPN business, we exclude IP price from calculation. And we also divide by 2, // because it has 2 members by default too. const IP_PRICE = getIpPrice(cycle); return (totalPrice - IP_PRICE) / (plan.MaxMembers || 1); } if (isMultiUserPersonalPlan(plan)) { return totalPrice; } // Some plans have 0 MaxMembers. That's because they don't have access to mail. // In reality, they still get 1 member. return totalPrice / (plan.MaxMembers || 1); } export function getPricingPerMember(plan: Plan): Pricing { return allCycles.reduce((acc, cycle) => { acc[cycle] = getPricePerMember(plan, cycle); // If the plan doesn't have custom cycles, we need to remove it from the resulting Pricing object const isNonDefinedCycle = acc[cycle] === undefined || acc[cycle] === null || acc[cycle] === 0; if (customCycles.includes(cycle) && isNonDefinedCycle) { delete acc[cycle]; } return acc; }, {} as Pricing); } export const getPricingFromPlanIDs = (planIDs: PlanIDs, plansMap: PlansMap): AggregatedPricing => { const initial = { [CYCLE.MONTHLY]: 0, [CYCLE.YEARLY]: 0, [CYCLE.TWO_YEARS]: 0, [CYCLE.FIFTEEN]: 0, [CYCLE.THIRTY]: 0, }; return Object.entries(planIDs).reduce<AggregatedPricing>( (acc, [planName, quantity]) => { const plan = plansMap[planName as keyof PlansMap]; if (!plan) { return acc; } const members = getPlanMembers(plan, quantity); acc.membersNumber += members; const add = (target: PricingForCycles, cycle: CYCLE) => { const price = plan.Pricing[cycle]; if (price) { target[cycle] += quantity * price; } }; const addMembersPricing = (target: PricingForCycles, cycle: CYCLE) => { const price = getPricePerMember(plan, cycle); if (price) { target[cycle] += members * price; } }; allCycles.forEach((cycle) => { add(acc.all, cycle); }); if (members !== 0) { allCycles.forEach((cycle) => { addMembersPricing(acc.members, cycle); }); } if (plan.Type === PLAN_TYPES.PLAN) { allCycles.forEach((cycle) => { add(acc.plans, cycle); }); } const defaultMonthly = plan.DefaultPricing?.[CYCLE.MONTHLY] ?? 0; const monthly = plan.Pricing?.[CYCLE.MONTHLY] ?? 0; // Offers might affect Pricing both ways, increase and decrease. // So if the Pricing increases, then we don't want to use the lower DefaultPricing as basis // for discount calculations const price = Math.max(defaultMonthly, monthly); acc.defaultMonthlyPrice += quantity * price; return acc; }, { defaultMonthlyPrice: 0, all: { ...initial }, members: { ...initial, }, plans: { ...initial, }, membersNumber: 0, } ); }; export interface TotalPricing { discount: number; total: number; totalPerMonth: number; totalNoDiscountPerMonth: number; discountPercentage: number; perUserPerMonth: number; } export const getTotalFromPricing = (pricing: AggregatedPricing, cycle: CYCLE): TotalPricing => { const total = pricing.all[cycle]; const totalPerMonth = pricing.all[cycle] / cycle; const totalNoDiscount = pricing.defaultMonthlyPrice * cycle; const discount = cycle === CYCLE.MONTHLY ? 0 : totalNoDiscount - total; const perUserPerMonth = Math.floor(pricing.members[cycle] / cycle / pricing.membersNumber); return { discount, discountPercentage: Math.round((discount / totalNoDiscount) * 100), total, totalPerMonth, totalNoDiscountPerMonth: totalNoDiscount / cycle, perUserPerMonth, }; }; interface OfferResult { pricing: Pricing; cycles: CYCLE[]; valid: boolean; } export const getPlanOffer = (plan: Plan) => { const result = [CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.TWO_YEARS].reduce<OfferResult>( (acc, cycle) => { acc.pricing[cycle] = (plan.DefaultPricing?.[cycle] ?? 0) - (plan.Pricing?.[cycle] ?? 0); return acc; }, { valid: false, cycles: [], pricing: { [CYCLE.MONTHLY]: 0, [CYCLE.YEARLY]: 0, [CYCLE.TWO_YEARS]: 0, [CYCLE.FIFTEEN]: 0, [CYCLE.THIRTY]: 0, }, } ); const sortedResults = (Object.entries(result.pricing) as unknown as [CYCLE, number][]).sort((a, b) => b[1] - a[1]); result.cycles = sortedResults.map(([cycle]) => cycle); if (sortedResults[0][1] > 0) { result.valid = true; } return result; }; /** * Currently there is no convenient way to get the number of IPs for a VPN subscription. * There is no dedicated field for that in the API. * That's a hack that counts the number of IP addons. */ export const getVPNDedicatedIPs = (subscription: Subscription | undefined) => { const planName = getPlanName(subscription, PLAN_SERVICES.VPN); // If you have other VPN plans, they don't have dedicated IPs if (!planName) { return 0; } return (subscription as Subscription).Plans.reduce( (acc, { Name, Quantity }) => acc + (Name.startsWith('1ip') ? Quantity : 0), IPS_INCLUDED_IN_PLAN[planName] || 0 // 1 IP is included in the Business plan ); }; export const getHasCoupon = (subscription: SubscriptionModel | undefined, coupon: string) => { return [subscription?.CouponCode, subscription?.UpcomingSubscription?.CouponCode].includes(coupon); }; /** * Checks if subscription can be cancelled by a user. Cancellation means that the user will be downgraded at the end * of the current billing cycle. In contrast, "Downgrade subscription" button means that the user will be downgraded * immediately. Note that B2B subscriptions also have "Cancel subscription" button, but it behaves differently, so * we don't consider B2B subscriptions cancellable for the purpose of this function. */ export const hasCancellablePlan = (subscription: Subscription | undefined) => { return hasVPN(subscription) || hasPassPlus(subscription) || hasVPNPassBundle(subscription); };
8,518
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/time.ts
import { format as formatDate, fromUnixTime, getUnixTime, isSameDay } from 'date-fns'; import { serverTime } from '@proton/crypto'; export type DateFnsOptions = Parameters<typeof formatDate>[2]; export type Options = DateFnsOptions & { /** * Date format if `unixTime` argument is today. If false then force `format`. 'p' by default. */ sameDayFormat?: string | false; /** * Date format in general case. 'PP' by default. */ format?: string; }; /** * Convert UNIX timestamp into a readable time. The format of the readable time is: * ** Hours and minutes if the UNIX timestamp is from the same day, * ** Day, month and year otherwise */ export const readableTime = (unixTime: number, options: Options = {}) => { let { sameDayFormat, format, ...dateFnsOptions } = options; sameDayFormat = sameDayFormat ?? 'p'; format = format ?? 'PP'; const date = fromUnixTime(unixTime); if (sameDayFormat && isSameDay(date, Date.now())) { return formatDate(date, sameDayFormat, dateFnsOptions); } return formatDate(date, format, dateFnsOptions); }; export type OptionsWithIntl = { /** * Locale code string, or an array of such strings like 'en' or 'en-US'. */ localeCode?: string | string[]; /** * If true time will be shown in 12h format with AM/PM */ hour12?: boolean; /** * Intl format options. */ intlOptions?: Intl.DateTimeFormatOptions; /** * Intl options if readableTimeIntl `unixTime` argument is today. */ sameDayIntlOptions?: Intl.DateTimeFormatOptions | false; }; /** * Convert UNIX timestamp into a readable time with Intl.DateTimeFormat API. The format of the readable time is: * ** Hours and minutes if the UNIX timestamp is from the same day, * ** Day, month and year otherwise * @param unixTime {number} * @param {Object} options * @param {Object} [options.intlOptions={month: 'short', day: 'numeric', year: 'numeric'}] * @param {Object} [options.sameDayIntlOptions={month: 'short', day: 'numeric', year: 'numeric'}] */ export const readableTimeIntl = (unixTime: number, options: OptionsWithIntl = {}) => { let { sameDayIntlOptions, localeCode = 'en-US', hour12, intlOptions } = options; // h12: 12:59 AM | h23: 00:59 (h24 would have produced: 24:59) // We still want to let default Intl behavior if no hour12 params is pass, so we want to have undefined const hourCycle = (hour12 === true && 'h12') || (hour12 === false && 'h23') || undefined; const defaultIntlOptions: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', year: 'numeric' }; intlOptions = intlOptions ?? defaultIntlOptions; const defaultSameDayOptions: Intl.DateTimeFormatOptions = { hour: 'numeric', minute: 'numeric' }; sameDayIntlOptions = sameDayIntlOptions ?? defaultSameDayOptions; const date = new Date(unixTime * 1000); if (sameDayIntlOptions && isSameDay(date, Date.now())) { return Intl.DateTimeFormat(localeCode, { hourCycle, ...sameDayIntlOptions }).format(date); } return Intl.DateTimeFormat(localeCode, { hourCycle, ...intlOptions }).format(date); }; export const getCurrentUnixTimestamp = () => { return getUnixTime(serverTime()); };
8,519
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/twofa.ts
import { encode } from 'hi-base32'; export const generateSharedSecret = (length = 20) => { const randomBytes = crypto.getRandomValues(new Uint8Array(length)); return encode(randomBytes); }; interface GetUriArguments { identifier: string; sharedSecret: string; issuer?: string; digits?: number; algorithm?: string; period?: number; } export const getUri = ({ identifier, sharedSecret, issuer = 'ProtonMail', digits = 6, algorithm = 'SHA1', period = 30, }: GetUriArguments) => { return `otpauth://totp/${identifier}?secret=${sharedSecret}&issuer=${issuer}&algorithm=${algorithm}&digits=${digits}&period=${period}`; };
8,520
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/uid.ts
/** * Generate a string of four random hex characters */ export const randomHexString4 = () => { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); }; /** * Generates a contact UID of the form 'proton-web-uuid' */ export const generateProtonWebUID = () => { const s4 = () => randomHexString4(); return `proton-web-${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`; };
8,521
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/updateCollection.ts
import { EVENT_ACTIONS } from '../constants'; const { DELETE, CREATE, UPDATE } = EVENT_ACTIONS; function getKeyToSortBy<T>(sortByKey: boolean | keyof T, todos: Partial<T>[]) { if (sortByKey === true) { const itemFromTodos = todos?.[0]; if (!itemFromTodos) { return undefined; } return ['Order', 'Priority'].find((sortProperty) => sortProperty in itemFromTodos) as keyof T; } if (sortByKey === false) { return undefined; } return sortByKey; } const defaultMerge = <T>(oldModel: T, newModel: Partial<T>): T => { return { ...oldModel, ...newModel, }; }; export type EventItemModelPartial<EventItemModel> = Partial<EventItemModel>; export type CreateEventItemUpdate<EventItemModel, EventItemKey extends string> = { ID: string; Action: EVENT_ACTIONS.CREATE; } & { [key in EventItemKey]: EventItemModel }; export type UpdateEventItemUpdate<EventItemModel, EventItemKey extends string> = { ID: string; Action: EVENT_ACTIONS.UPDATE; } & { [key in EventItemKey]: EventItemModelPartial<EventItemModel> }; export type DeleteEventItemUpdate = { ID: string; Action: EVENT_ACTIONS.DELETE; }; export type EventItemUpdate<EventItemModel, EventItemKey extends string> = | CreateEventItemUpdate<EventItemModel, EventItemKey> | UpdateEventItemUpdate<EventItemModel, EventItemKey> | DeleteEventItemUpdate; interface Model { ID: string; } /** * Update a model collection with incoming events. */ const updateCollection = <EventItemModel extends Model, EventItemKey extends string>({ model = [], events = [], item, itemKey, merge = defaultMerge, sortByKey: maybeSortByKey = true, }: { model: readonly EventItemModel[]; events: readonly EventItemUpdate<EventItemModel, EventItemKey>[]; item?: ( event: CreateEventItemUpdate<EventItemModel, EventItemKey> | UpdateEventItemUpdate<EventItemModel, EventItemKey> ) => EventItemModelPartial<EventItemModel> | undefined; merge?: (a: EventItemModel, B: EventItemModelPartial<EventItemModel>) => EventItemModel; itemKey: EventItemKey; sortByKey?: boolean | keyof EventItemModel; }): EventItemModel[] => { const copy = [...model]; const todo = events.reduce<{ [UPDATE]: EventItemModelPartial<EventItemModel>[]; [CREATE]: EventItemModelPartial<EventItemModel>[]; [DELETE]: { [key: string]: boolean }; }>( (acc, task) => { const { Action, ID } = task; if (Action === DELETE) { acc[DELETE][ID] = true; return acc; } if (Action === UPDATE || Action === CREATE) { const value = item?.(task) ?? task[itemKey]; if (value) { acc[Action].push(value); } } return acc; }, { [UPDATE]: [], [CREATE]: [], [DELETE]: {} } ); const todos = [...todo[CREATE], ...todo[UPDATE]]; const copiedMap = copy.reduce<{ [key: string]: number }>((acc, element, index) => { acc[element.ID] = index; return acc; }, Object.create(null)); // NOTE: We cannot trust Action so "create" and "update" events need to be handled in this way by going through the original model. const { collection } = todos.reduce<{ collection: EventItemModel[]; map: { [key: string]: number } }>( (acc, element) => { const id = element.ID; if (id === undefined) { return acc; } // Update. const index = acc.map[id]; if (index !== undefined) { acc.collection[index] = merge(acc.collection[index], element); return acc; } // Create. Assume it is never partial. const length = acc.collection.push(element as EventItemModel); // Set index in case there is an UPDATE on this CREATEd item afterwards. acc.map[id] = length - 1; // index return acc; }, { collection: copy, map: copiedMap, } ); const filteredArray = collection.filter(({ ID }) => !todo[DELETE][ID]); const sortByKey = getKeyToSortBy(maybeSortByKey, todos); return sortByKey ? filteredArray.sort((itemA, itemB) => Number(itemA[sortByKey]) - Number(itemB[sortByKey])) : filteredArray; }; export default updateCollection;
8,522
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/updateCounter.js
const updateCounter = (model, newModel = []) => { return newModel; }; export default updateCounter;
8,523
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/updateObject.ts
const updateObject = <T>(model: T, newModel: Partial<T>) => ({ ...model, ...newModel, }); export default updateObject;
8,524
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/upsell.ts
import { APPS, APP_NAMES, APP_UPSELL_REF_PATH, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; /** * Add an upsell ref param to a URL */ export const addUpsellPath = (link: string, upsellPath?: string) => { if (!upsellPath) { return link; } const hasParams = link.includes('?'); return hasParams ? `${link}&ref=${upsellPath}` : `${link}?ref=${upsellPath}`; }; /** * Generate upsell ref from app component and feature * * @param app => Current app from which we open a link * @param feature => feature identifier to include in the path * @param component => Optional, ref component (e.g. banner, modal, button) */ export const getUpsellRef = ({ app, feature, component, isSettings = false, }: { app: APP_UPSELL_REF_PATH; feature: string; component?: UPSELL_COMPONENT; isSettings?: boolean; }) => { const upsellComponent = component || ''; const upsellInSettings = isSettings ? '_settings' : ''; return `${app}${upsellComponent}${feature}${upsellInSettings}`; }; /** * Generate upsell ref from the current app, the "feature" identifier, the "component" and the "from app" * * @param app => Current app from which we open a link * @param feature => feature identifier to include in the path * @param component => Optional, ref component (e.g. banner, modal, button) * @param fromApp => Optional, "parent app" of the current app (e.g. in mail settings, app=account and fromApp=mail) * * Return a ref string like "upsell_mail-banner-auto-reply_settings" */ export const getUpsellRefFromApp = ({ app, fromApp, component, feature, }: { app: APP_NAMES; feature: string; component?: UPSELL_COMPONENT; fromApp?: APP_NAMES; }) => { if (app === APPS.PROTONMAIL) { return getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, feature, component }); } else if (app === APPS.PROTONCALENDAR) { return getUpsellRef({ app: APP_UPSELL_REF_PATH.CALENDAR_UPSELL_REF_PATH, feature, component }); } else if (app === APPS.PROTONDRIVE) { return getUpsellRef({ app: APP_UPSELL_REF_PATH.DRIVE_UPSELL_REF_PATH, feature, component }); } else if (app === APPS.PROTONACCOUNT && fromApp) { if (fromApp === APPS.PROTONMAIL) { return getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, feature, component, isSettings: true, }); } else if (fromApp === APPS.PROTONCALENDAR) { return getUpsellRef({ app: APP_UPSELL_REF_PATH.CALENDAR_UPSELL_REF_PATH, feature, component, isSettings: true, }); } else if (fromApp === APPS.PROTONDRIVE) { return getUpsellRef({ app: APP_UPSELL_REF_PATH.DRIVE_UPSELL_REF_PATH, feature, component, isSettings: true, }); } else if (fromApp === APPS.PROTONPASS) { return getUpsellRef({ app: APP_UPSELL_REF_PATH.PASS_UPSELL_REF_PATH, feature, component, isSettings: true, }); } else if (fromApp === APPS.PROTONVPN_SETTINGS) { return getUpsellRef({ app: APP_UPSELL_REF_PATH.VPN_UPSELL_REF_PATH, feature, component, isSettings: true }); } } return undefined; };
8,525
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/url.ts
import { stripLeadingSlash, stripTrailingSlash } from '@proton/shared/lib/helpers/string'; import { APPS, APPS_CONFIGURATION, APP_NAMES, DOH_DOMAINS, LINK_TYPES } from '../constants'; import window from '../window'; const PREFIX_TO_TYPE: { [prefix: string]: LINK_TYPES | undefined } = { 'tel:': LINK_TYPES.PHONE, 'mailto:': LINK_TYPES.EMAIL, 'http://': LINK_TYPES.WEB, 'https://': LINK_TYPES.WEB, }; const EXTENSION_PROTOCOLS = ['chrome-extension:', 'moz-extension:']; const TYPE_TO_PREFIX = { [LINK_TYPES.PHONE]: { regex: /^tel:/, defaultPrefix: 'tel:' }, [LINK_TYPES.EMAIL]: { regex: /^mailto:/, defaultPrefix: 'mailto:' }, [LINK_TYPES.WEB]: { regex: /^http(|s):\/\//, defaultPrefix: 'https://' }, }; // Create one big regexp of all the regexes in TYPE_TO_PREFIX. // It can be used for finding a particular type from a link. const ALL_REGEXP_SOURCES = (Object.keys(TYPE_TO_PREFIX) as LINK_TYPES[]) .map((key) => `(${TYPE_TO_PREFIX[key].regex.source})`) .join('|'); const ALL_REGEXP = new RegExp(ALL_REGEXP_SOURCES); /** * Extract host * @param url * @returns host */ export const getHost = (url = '') => { const { host = '' } = new URL(url); return host; }; /** * Extract hostname * @param url * @returns hostname */ export const getHostname = (url = '') => { const { hostname = '' } = new URL(url); return hostname; }; /** * Converts search parameters from hash to a URLSearchParams compatible string */ const getSearchFromHash = (search: string) => { let searchHash = search; if (searchHash) { searchHash = searchHash[0] === '#' ? `?${search.slice(1)}` : searchHash; } return searchHash; }; export const stringifySearchParams = ( params: { [key: string]: string | string[] | undefined }, prefix?: string | undefined ) => { const urlSearchParams = new URLSearchParams(); Object.entries(params) .filter(([, value]) => value !== undefined && value !== '') .forEach(([key, value]) => { /* * typescript is not able to determine that stringifiedValue * can't be undefined because of the previous filter condition * therefore, typecast to string */ const stringifiedValue = Array.isArray(value) ? value.join(',') : (value as string); urlSearchParams.set(key, stringifiedValue); }); const urlSearch = urlSearchParams.toString(); return urlSearch !== '' && prefix !== undefined ? prefix + urlSearch : urlSearch; }; /** * Return a param (native) map based on the search string */ export const getSearchParams = (search: string): { [key: string]: string } => { const params = new URLSearchParams(getSearchFromHash(search)); const result: { [key: string]: string } = {}; params.forEach((value, key) => { result[key] = value; }); return result; }; /** * Return a new pathname with the query string updated from * the search input and updated with the newParams */ export const changeSearchParams = ( pathname: string, search: string, newParams: { [key: string]: string | undefined } = {} ) => { const params = new URLSearchParams(getSearchFromHash(search)); Object.keys(newParams).forEach((key) => { if (newParams[key] === undefined) { params.delete(key); } else { params.set(key, newParams[key] as string); } }); // Remove potential mailto query from the params, otherwise search will be concatenated to the mailto query if (params.get('mailto')) { params.delete('mailto'); } const queryString = params.toString(); const urlFragment = (queryString === '' ? '' : '#') + queryString; return pathname + urlFragment; }; /** * Convert from a link prefix to link type. */ const prefixToType = (prefix = 'http://') => { return PREFIX_TO_TYPE[prefix]; }; /** * Get a link prefix from a url. */ const getLinkPrefix = (input = ''): string | undefined => { const matches = ALL_REGEXP.exec(input) || []; return matches[0]; }; /** * Get a link type from a link. */ export const linkToType = (link = '') => { const prefix = getLinkPrefix(link); return prefixToType(prefix); }; /** * Strip the link prefix from a url. * Leave the prefix if it's http to let the user be able to set http or https. */ export const stripLinkPrefix = (input = '') => { const prefix = getLinkPrefix(input); if (!prefix || prefix.indexOf('http') !== -1) { return input; } return input.replace(prefix, ''); }; /** * Try to add link prefix if missing */ export const addLinkPrefix = (input = '', type: LINK_TYPES) => { const prefix = getLinkPrefix(input); if (prefix) { return input; } const { defaultPrefix } = TYPE_TO_PREFIX[type] || {}; if (defaultPrefix) { return `${defaultPrefix}${input}`; } return input; }; // Note: This function makes some heavy assumptions on the hostname. Only intended to work on proton-domains. export const getSecondLevelDomain = (hostname: string) => { return hostname.slice(hostname.indexOf('.') + 1); }; export const getRelativeApiHostname = (hostname: string) => { const idx = hostname.indexOf('.'); const first = hostname.slice(0, idx); const second = hostname.slice(idx + 1); return `${first}-api.${second}`; }; export const getIsDohDomain = (origin: string) => { return DOH_DOMAINS.some((dohDomain) => origin.endsWith(dohDomain)); }; const doesHostnameLookLikeIP = (hostname: string) => { // Quick helper function to tells us if hostname string seems to be IP address or DNS name. // Relies on a fact, that no TLD ever will probably end with a digit. So if last char is // a digit, it's probably an IP. // IPv6 addresses can end with a letter, so there's additional colon check also. // Probably no need ever to use slow & complicated IP regexes here, but feel free to change // whenever we have such util functions available. // Note: only works on hostnames (no port), not origins (can include port and protocol). return /\d$/.test(hostname) || hostname.includes(':'); }; export const getApiSubdomainUrl = (pathname: string) => { const url = new URL('', window.location.origin); const usePathPrefix = url.hostname === 'localhost' || getIsDohDomain(url.origin) || doesHostnameLookLikeIP(url.hostname); if (usePathPrefix) { url.pathname = `/api${pathname}`; return url; } url.hostname = getRelativeApiHostname(url.hostname); url.pathname = pathname; return url; }; export const getAppUrlFromApiUrl = (apiUrl: string, appName: APP_NAMES) => { const { subdomain } = APPS_CONFIGURATION[appName]; const url = new URL(apiUrl); const { hostname } = url; const index = hostname.indexOf('.'); const tail = hostname.slice(index + 1); url.pathname = ''; url.hostname = `${subdomain}.${tail}`; return url; }; export const getAppUrlRelativeToOrigin = (origin: string, appName: APP_NAMES) => { const { subdomain } = APPS_CONFIGURATION[appName]; const url = new URL(origin); const segments = url.host.split('.'); segments[0] = subdomain; url.hostname = segments.join('.'); return url; }; let cache = ''; export const getStaticURL = (path: string) => { if ( window.location.hostname === 'localhost' || getIsDohDomain(window.location.origin) || EXTENSION_PROTOCOLS.includes(window.location.protocol) ) { return `https://proton.me${path}`; } // We create a relative URL to support the TOR domain cache = cache || getSecondLevelDomain(window.location.hostname); // The VPN domain has a different static site and the proton.me urls are not supported there const hostname = cache === 'protonvpn.com' || cache === 'protonmail.com' ? 'proton.me' : cache; return `https://${hostname}${path}`; }; export const getBlogURL = (path: string) => { return getStaticURL(`/blog${path}`); }; export const getKnowledgeBaseUrl = (path: string) => { return getStaticURL(`/support${path}`); }; export const getDomainsSupportURL = () => { return getStaticURL('/support/mail/custom-email-domain'); }; export const getBridgeURL = () => { return getStaticURL('/mail/bridge'); }; export const getEasySwitchURL = () => { return getStaticURL('/easyswitch'); }; export const getImportExportAppUrl = () => { return getStaticURL('/support/export-emails-import-export-app'); }; export const getShopURL = () => { return `https://shop.proton.me`; }; export const getDownloadUrl = (path: string) => { return `https://proton.me/download${path}`; }; export const getSupportContactURL = (params: { [key: string]: string | string[] | undefined }) => { return getStaticURL(`/support/contact${stringifySearchParams(params, '?')}`); }; export const getAppStaticUrl = (app: APP_NAMES) => { if (app === 'proton-mail') { return getStaticURL('/mail'); } if (app === 'proton-drive') { return getStaticURL('/drive'); } if (app === 'proton-calendar') { return getStaticURL('/calendar'); } if (app === 'proton-pass') { return getStaticURL('/pass'); } if (app === 'proton-vpn-settings') { return getStaticURL('/vpn'); } return getStaticURL(''); }; export const getPrivacyPolicyURL = (app?: APP_NAMES) => { if (app === APPS.PROTONVPN_SETTINGS) { return 'https://protonvpn.com/privacy-policy'; } return getStaticURL('/legal/privacy'); }; export const getTermsURL = (locale?: string) => { const link = locale && locale !== 'en' ? `/${locale}/legal/terms` : '/legal/terms'; return getStaticURL(link); }; export const getBlackFriday2023URL = (app?: APP_NAMES) => { if (app === APPS.PROTONVPN_SETTINGS) { return 'https://protonvpn.com/support/black-friday-2023'; } return getKnowledgeBaseUrl('/black-friday-2023'); }; export const getAbuseURL = () => { return getStaticURL('/support/abuse'); }; export const isValidHttpUrl = (string: string) => { let url; try { url = new URL(string); } catch (_) { return false; } return url.protocol === 'http:' || url.protocol === 'https:'; }; export const isAppFromURL = (url: string | undefined, app: APP_NAMES) => { if (url) { const { host } = new URL(url); const segments = host.split('.'); return segments[0] === APPS_CONFIGURATION[app].subdomain; } return false; }; export const formatURLForAjaxRequest = () => { const url = new URL(window.location.href); if (url.search.includes('?')) { url.search = `${url.search}&load=ajax`; } else { url.search = '?load=ajax'; } url.hash = ''; return url; }; export const getPathFromLocation = (location: { pathname: string; hash: string; search: string }) => { return [location.pathname, location.search, location.hash].join(''); }; export const joinPaths = (...paths: string[]) => { return paths.reduce((acc, path) => { return `${stripTrailingSlash(acc)}/${stripLeadingSlash(path)}`; }, ''); };
8,526
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/userSettings.ts
import { SETTINGS_PROTON_SENTINEL_STATE, UserSettings } from '../interfaces'; export const isProtonSentinelEligible = (userSettings: UserSettings) => { return ( !!userSettings.HighSecurity.Eligible || userSettings.HighSecurity.Value === SETTINGS_PROTON_SENTINEL_STATE.ENABLED ); };
8,527
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/validators.ts
import isValidDomain from 'is-valid-domain'; /* eslint-disable no-useless-escape */ export const REGEX_URL = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/; export const REGEX_HEX_COLOR = /^#([a-f0-9]{3,4}|[a-f0-9]{4}(?:[a-f0-9]{2}){1,2})\b$/i; export const REGEX_NUMBER = /^\d+$/; export const REGEX_PUNYCODE = /^(http|https):\/\/xn--/; export const REGEX_USERNAME = /^[A-Za-z0-9]+(?:[_.-][A-Za-z0-9]+)*$/; export const REGEX_USERNAME_START = /^[A-Za-z0-9]/; export const REGEX_USERNAME_END = /[A-Za-z0-9]$/; export const isEmpty = (value = '') => !value.length; export const maxLength = (value = '', limit = 0) => value.length <= limit; export const minLength = (value = '', limit = 0) => value.length >= limit; export const isURL = (value = '') => { if (/\s/.test(value)) { // A URL should contain no spaces // (doing this check separately as URL_REGEX is not checking it) return false; } return REGEX_URL.test(value); }; export const isDomain = isValidDomain; export const isHexColor = (value = '') => REGEX_HEX_COLOR.test(value); export const isNumber = (value = '') => REGEX_NUMBER.test(value); export const isBase64Image = (value = '') => value.startsWith('data:image') && value.includes(';base64'); export const isPunycode = (value = '') => REGEX_PUNYCODE.test(value);
8,528
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/i18n/dateFnLocale.ts
import { Locale } from 'date-fns'; import { SETTINGS_DATE_FORMAT, SETTINGS_TIME_FORMAT, SETTINGS_WEEK_START } from '../interfaces'; import { enGBLocale, enUSLocale, faIRLocale } from './dateFnLocales'; // Support for changing the date format is not great. Hide it for now. export const IS_DATE_FORMAT_ENABLED = false; export const getDateFnLocaleWithLongFormat = (a: Locale, b: Locale): Locale => { /* * By default we use the same date-time locale as the user has selected in the app in order * to get the correct translations for days, months, year, etc. However, we override * the long date and time format to get 12 or 24 hour time and the correct date format depending * on what is selected in the browser for the "system settings" option. */ if (!b.formatLong?.time || !a.formatLong) { return a; } const [languageA] = a.code?.split('-') || ['a']; const [languageB] = b.code?.split('-') || ['b']; // When the languages are the same, we can just straight up use the other locale. if (languageB === languageA) { return b; } return { ...a, formatLong: { ...a.formatLong, time: b.formatLong.time, }, }; }; export interface Options { TimeFormat: SETTINGS_TIME_FORMAT; DateFormat: SETTINGS_DATE_FORMAT; WeekStart: SETTINGS_WEEK_START; } export const getIsLocaleAMPM = (locale: Locale) => locale.formatLong?.time().includes('a'); export const getDateFnLocaleWithDateFormat = (locale: Locale, dateFormat: SETTINGS_DATE_FORMAT): Locale => { const date = ( dateFormat === SETTINGS_DATE_FORMAT.DDMMYYYY ? enGBLocale : dateFormat === SETTINGS_DATE_FORMAT.MMDDYYYY ? enUSLocale : faIRLocale ).formatLong?.date; return { ...locale, formatLong: { ...locale.formatLong, // @ts-ignore date, }, }; }; export const getDateFnLocaleWithTimeFormat = (dateLocale: Locale, displayAMPM = false): Locale => { const isAMPMLocale = getIsLocaleAMPM(dateLocale); if ((displayAMPM && isAMPMLocale) || (!displayAMPM && !isAMPMLocale)) { return dateLocale; } const time = (displayAMPM ? enUSLocale : enGBLocale).formatLong?.time; return { ...dateLocale, formatLong: { ...dateLocale.formatLong, // @ts-ignore time, }, }; }; export const getDateFnLocaleWithSettings = ( locale: Locale, { TimeFormat = SETTINGS_TIME_FORMAT.LOCALE_DEFAULT, DateFormat = SETTINGS_DATE_FORMAT.LOCALE_DEFAULT, WeekStart = SETTINGS_WEEK_START.LOCALE_DEFAULT, }: Partial<Options> = {} ) => { let copy: Locale = { ...locale, }; if (TimeFormat !== SETTINGS_TIME_FORMAT.LOCALE_DEFAULT) { const displayAMPM = TimeFormat === SETTINGS_TIME_FORMAT.H12; copy = getDateFnLocaleWithTimeFormat(locale, displayAMPM); } if (IS_DATE_FORMAT_ENABLED && DateFormat !== SETTINGS_DATE_FORMAT.LOCALE_DEFAULT) { copy = getDateFnLocaleWithDateFormat(copy, DateFormat); } if (WeekStart !== SETTINGS_WEEK_START.LOCALE_DEFAULT && WeekStart >= 1 && WeekStart <= 7) { copy.options = { ...copy.options, weekStartsOn: (WeekStart % 7) as any, }; } return copy; };
8,529
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/i18n/dateFnLocales.ts
import { DateFnsLocaleMap } from '../interfaces/Locale'; const dateFnLocales = import.meta.webpackContext!('date-fns/locale', { recursive: true, regExp: /^\.\/[a-z]{2}(-([A-Z]{2}))?\/index\.js$/, mode: 'lazy', chunkName: 'date-fns/[request]', }); export default dateFnLocales.keys().reduce((acc: DateFnsLocaleMap, key: string) => { const end = key.lastIndexOf('/'); const normalizedKey = key.slice(2, end).replace('-', '_'); acc[normalizedKey] = () => dateFnLocales(key); return acc; }, {}); export { default as enUSLocale } from 'date-fns/locale/en-US'; export { default as enGBLocale } from 'date-fns/locale/en-GB'; export { default as faIRLocale } from 'date-fns/locale/fa-IR';
8,530
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/i18n/helper.ts
import { DEFAULT_LOCALE } from '../constants'; export const getNormalizedLocale = (locale = '') => { return locale.toLowerCase().replace(/-/g, '_'); }; // Attempts to convert the original locale (en_US) to BCP 47 (en-US) as supported by the lang attribute export const getLangAttribute = (locale: string) => { return locale.replace(/_/g, '-').replace('es-LA', 'es'); }; /** * Takes the first portion, e.g. nl_NL => nl, kab_KAB => kab */ export const getLanguageCode = (locale = '') => { return getNormalizedLocale(locale).split('_')[0]; }; /** * Takes the second portion, e.g. nl_NL => nl, fr_CA => ca * ** Only for the locale user setting you are guaranteed to get an ISO_3166-1_alpha-2 country code. You may get undefined for other locale instances ** */ export const getNaiveCountryCode = (locale = '') => { return getNormalizedLocale(locale).split('_')[1]; }; /** * Transforms a locale string into one that can be passed to Javascript Intl methods. * Basically transforms zh_ZH => zh-ZH, es-es => es-es (Intl cares about the dash, but not about capitalization) */ export const getIntlLocale = (locale = '') => { return getNormalizedLocale(locale).replace(/_/g, '-'); }; export const getBrowserLanguageTags = (): string[] => { const tags = window.navigator?.languages; return [...tags] || []; }; /** * Gets the first specified locale from the browser, if any. * * If the first locale does not have a region and the second is a regional variant of the first, take it instead. */ export const getBrowserLocale = () => { const first = window.navigator?.languages?.[0]; const second = window.navigator?.languages?.[1]; if (!/[_-]/.test(first) && /[_-]/.test(second) && getLanguageCode(first) === getLanguageCode(second)) { return second; } return first; }; /** * Give a higher score to locales with higher chances to be a proper fallback languages * when there is no exact match. */ const getLanguagePriority = (locale: string) => { const parts = locale.toLowerCase().split(/[_-]/); // Prefer language (en) over language + region (en_US) if (parts.length === 1) { return 2; } // Prefer region matching language (fr_FR, it_IT, de_DE) over other regions (fr_CA, it_CH, de_AU) return parts[0] === parts[1] ? 1 : 0; }; /** * Get the closest matching locale from an object of locales. */ export const getClosestLocaleMatch = (locale = '', locales = {}) => { const localeKeys = [DEFAULT_LOCALE, ...Object.keys(locales)].sort((first, second) => { if (first === second) { return 0; } const firstPriority = getLanguagePriority(first); const secondPriority = getLanguagePriority(second); if (firstPriority > secondPriority) { return -1; } if (firstPriority < secondPriority) { return 1; } return first > second ? 1 : -1; }); const normalizedLocaleKeys = localeKeys.map(getNormalizedLocale); const normalizedLocale = getNormalizedLocale(locale); // First by language and country code. const fullMatchIndex = normalizedLocaleKeys.findIndex((key) => key === normalizedLocale); if (fullMatchIndex >= 0) { return localeKeys[fullMatchIndex]; } // Language code. const language = getLanguageCode(normalizedLocale); const languageMatchIndex = normalizedLocaleKeys.findIndex((key) => { return getLanguageCode(key) === language; }); if (languageMatchIndex >= 0) { return localeKeys[languageMatchIndex]; } }; export const getClosestLocaleCode = (locale: string | undefined, locales: { [key: string]: any }) => { if (!locale) { return DEFAULT_LOCALE; } return getClosestLocaleMatch(locale, locales) || DEFAULT_LOCALE; };
8,531
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/i18n/index.ts
import { enUSLocale } from './dateFnLocales'; /** * The locales are exported as mutable exports: * 1) To avoid using a react context for components deep in the tree * 2) It's more similar to how ttag works */ export let dateLocale = enUSLocale; export let defaultDateLocale = enUSLocale; export let browserDateLocale = enUSLocale; export let dateLocaleCode = 'en_US'; export let browserLocaleCode = 'en_US'; export let localeCode = 'en_US'; export let languageCode = 'en'; export const setLocales = ({ localeCode: newLocaleCode = localeCode, languageCode: newLanguageCode = languageCode, }) => { localeCode = newLocaleCode; languageCode = newLanguageCode; }; export const setDateLocales = ({ defaultDateLocale: newDefaultDateLocale = defaultDateLocale, browserDateLocale: newBrowserDateLocale = browserDateLocale, browserLocaleCode: newBrowserLocaleCode = browserLocaleCode, dateLocale: newDateLocale = dateLocale, dateLocaleCode: newDateLocaleCode = dateLocaleCode, }) => { defaultDateLocale = newDefaultDateLocale; browserDateLocale = newBrowserDateLocale; browserLocaleCode = newBrowserLocaleCode; dateLocale = newDateLocale; dateLocaleCode = newDateLocaleCode; };
8,532
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/i18n/loadLocale.ts
import { addLocale as ttagAddLocale, useLocale as ttagUseLocale } from 'ttag'; import { DEFAULT_LOCALE } from '../constants'; import { TtagLocaleMap } from '../interfaces/Locale'; import { Options, getDateFnLocaleWithLongFormat, getDateFnLocaleWithSettings } from './dateFnLocale'; import dateFnLocales from './dateFnLocales'; import { getClosestLocaleMatch, getLangAttribute, getLanguageCode } from './helper'; import { setDateLocales, setLocales } from './index'; export const loadLocale = async (localeCode: string, locales: TtagLocaleMap) => { const languageCode = getLanguageCode(localeCode); if (localeCode !== DEFAULT_LOCALE) { const getLocaleData = locales[localeCode]; if (!getLocaleData) { throw new Error('No locale data for requested localeCode'); } const data = await getLocaleData(); ttagAddLocale(localeCode, data); } ttagUseLocale(localeCode); setLocales({ localeCode, languageCode, }); if (typeof document !== 'undefined') { document.documentElement.lang = getLangAttribute(localeCode); } }; export const loadDateLocale = async (localeCode: string, browserLocaleCode?: string, options?: Options) => { const closestLocaleCode = getClosestLocaleMatch(localeCode, dateFnLocales) || DEFAULT_LOCALE; const closestBrowserLocaleCode = getClosestLocaleMatch(browserLocaleCode, dateFnLocales) || DEFAULT_LOCALE; const [dateFnLocale, browserDateFnLocale] = await Promise.all([ dateFnLocales[closestLocaleCode](), dateFnLocales[closestBrowserLocaleCode](), ]); const mergedDateLocale = getDateFnLocaleWithLongFormat(dateFnLocale, browserDateFnLocale); const updatedDateFnLocale = getDateFnLocaleWithSettings(mergedDateLocale, options); setDateLocales({ defaultDateLocale: dateFnLocale, browserDateLocale: browserDateFnLocale, browserLocaleCode: closestBrowserLocaleCode, dateLocale: updatedDateFnLocale, dateLocaleCode: closestLocaleCode, }); return updatedDateFnLocale; };
8,533
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/i18n/locales.ts
import { LocaleData } from 'ttag'; import { TtagLocaleMap } from '../interfaces/Locale'; export let locales: TtagLocaleMap = {}; type LocaleRequireContext = { keys: () => string[]; (id: string): Promise<LocaleData> }; export const getLocalesFromRequireContext = (locales: LocaleRequireContext) => { return locales.keys().reduce<TtagLocaleMap>((acc, key) => { acc[key.slice(2, key.length - 5)] = () => locales(key); return acc; }, {}); }; export const setTtagLocales = (newLocales: TtagLocaleMap) => { locales = newLocales; };
8,534
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/i18n/relocalize.ts
import { addLocale as ttagAddLocale, useLocale as ttagUseLocale } from 'ttag'; import { DEFAULT_LOCALE } from '../constants'; import { Options } from './dateFnLocale'; import { getBrowserLocale, getClosestLocaleCode } from './helper'; import { browserDateLocale, browserLocaleCode, dateLocale, dateLocaleCode, defaultDateLocale, localeCode, setDateLocales, } from './index'; import { loadDateLocale } from './loadLocale'; import { locales } from './locales'; export const relocalizeText = async ({ getLocalizedText, newLocaleCode, relocalizeDateFormat, userSettings, }: { getLocalizedText: () => string; newLocaleCode?: string; relocalizeDateFormat?: boolean; userSettings?: Options; }) => { const currentLocaleCode = localeCode; const [ currentDefaultDateLocale, currentBrowserDateLocale, currentBrowserLocaleCode, currentDateLocale, currentDateLocaleCode, ] = [defaultDateLocale, browserDateLocale, browserLocaleCode, dateLocale, dateLocaleCode]; if (!newLocaleCode || newLocaleCode === currentLocaleCode) { return getLocalizedText(); } try { const newSafeLocaleCode = getClosestLocaleCode(newLocaleCode, locales); const useDefaultLocale = newSafeLocaleCode === DEFAULT_LOCALE; const [newTtagLocale] = await Promise.all([ useDefaultLocale ? undefined : locales[newSafeLocaleCode]?.(), relocalizeDateFormat ? loadDateLocale(newSafeLocaleCode, getBrowserLocale(), userSettings) : undefined, ]); if (!useDefaultLocale && !newTtagLocale) { throw new Error('No locale data for requested localeCode'); } if (newTtagLocale) { ttagAddLocale(newSafeLocaleCode, newTtagLocale); } ttagUseLocale(newSafeLocaleCode); return getLocalizedText(); } catch (e) { return getLocalizedText(); } finally { ttagUseLocale(currentLocaleCode); setDateLocales({ defaultDateLocale: currentDefaultDateLocale, browserDateLocale: currentBrowserDateLocale, browserLocaleCode: currentBrowserLocaleCode, dateLocale: currentDateLocale, dateLocaleCode: currentDateLocaleCode, }); } };
8,535
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Address.ts
import { ADDRESS_FLAGS, ADDRESS_RECEIVE, ADDRESS_SEND, ADDRESS_STATUS, ADDRESS_TYPE, EVENT_ACTIONS, } from '../constants'; import { AddressKey } from './Key'; import { ActiveSignedKeyList, SignedKeyList } from './SignedKeyList'; export enum AddressConfirmationState { CONFIRMATION_NOT_CONFIRMED = 0, CONFIRMATION_CONFIRMED, CONFIRMATION_INVALID, } export interface Address { CatchAll: boolean; DisplayName: string; DomainID: string; Email: string; HasKeys: number; ID: string; Keys: AddressKey[]; SignedKeyList: ActiveSignedKeyList | null; Order: number; Priority: number; Receive: ADDRESS_RECEIVE; Send: ADDRESS_SEND; Signature: string; Status: ADDRESS_STATUS; Type: ADDRESS_TYPE; Flags?: ADDRESS_FLAGS; ProtonMX: boolean; ConfirmationState: AddressConfirmationState; } export type DomainAddress = Omit<Address, 'SignedKeyList' | 'Keys'>; export interface AddressKeyPayload { AddressID: string; PrivateKey: string; SignedKeyList: SignedKeyList; } export interface AddressKeyPayloadV2 { AddressID: string; Token: string; Signature: string; PrivateKey: string; SignedKeyList: SignedKeyList; } export interface Recipient { Name: string; Address: string; ContactID?: string; Group?: string; BimiSelector?: string | null; DisplaySenderImage?: number; IsProton?: number; IsSimpleLogin?: number; } export interface AddressEvent { ID: string; Action: EVENT_ACTIONS; Address?: Address; }
8,536
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/AddressForwarding.ts
import { SIEVE_VERSION, SieveBranch } from '@proton/sieve/src/interface'; // bit 0 = unencrypted/encrypted, bit 1: internal/external export enum ForwardingType { InternalUnencrypted = 0, InternalEncrypted = 1, ExternalUnencrypted = 2, ExternalEncrypted = 3, } export enum ForwardingState { Pending = 0, Active = 1, Outdated = 2, Paused = 3, Rejected = 4, } export interface AddressForwarding { ID: string; CreateTime: number; State: ForwardingState; Type: ForwardingType; Filter: { Tree: SieveBranch[]; Version: SIEVE_VERSION; Sieve: string; } | null; } interface ForwardingKey { PrivateKey: string; ActivationToken: string; } export interface IncomingAddressForwarding extends AddressForwarding { ForwardeeAddressID: string; ForwarderEmail: string; ForwardingKeys?: ForwardingKey[]; } export interface OutgoingAddressForwarding extends AddressForwarding { ForwarderAddressID: string; ForwardeeEmail: string; }
8,537
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Api.ts
export type Api = <T = any>(arg: object) => Promise<T>; export interface ApiResponse { Code: number; }
8,538
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/ApiEnvironmentConfig.ts
export interface ApiEnvironmentConfig { 'importer.google.client_id': string; 'importer.outlook.client_id': string; }
8,539
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/AutoResponder.ts
import { AutoReplyDuration } from '../constants'; export interface AutoResponder { IsEnabled: boolean; Message: string; Repeat: AutoReplyDuration; DaysSelected: number[]; Zone: string; Subject: string; }
8,540
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Checklist.ts
export interface ChecklistApiResponse { Code: number; Items: ChecklistKey[]; CreatedAt: number; ExpiresAt: number; UserWasRewarded: boolean; Visible: boolean; Display: CHECKLIST_DISPLAY_TYPE; } export type ChecklistId = 'get-started' | 'paying-user'; export enum ChecklistKey { SendMessage = 'SendMessage', RecoveryMethod = 'RecoveryMethod', DriveUpload = 'DriveUpload', DriveShare = 'DriveShare', //New checklist items Import = 'Import', ProtectInbox = 'ProtectInbox', AccountLogin = 'AccountLogin', MobileApp = 'MobileApp', } export type ChecklistKeyType = keyof typeof ChecklistKey; export enum CHECKLIST_DISPLAY_TYPE { FULL = 'Full', REDUCED = 'Reduced', HIDDEN = 'Hidden', }
8,541
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Domain.ts
export interface DKIMKey { ID: string; Selector: string; PublicKey: string; Algorithm: number; DNSState: number; CreateTime: number; } export interface DKIMConfig { Hostname: string; CNAME: string; Key: DKIMKey | null; } export enum DOMAIN_STATE { DOMAIN_STATE_DEFAULT = 0, // Domain's State before verify or after deactivation DOMAIN_STATE_VERIFIED = 1, // active once verified DOMAIN_STATE_WARN = 2, // detected backward DNS change after ACTIVE } export enum VERIFY_STATE { VERIFY_STATE_DEFAULT = 0, // 0 is default, no good VERIFY_STATE_EXIST = 1, // 1 is has code but doesn't match DB's, no good VERIFY_STATE_GOOD = 2, // 2 is has code and matches DB's, good! } export enum MX_STATE { MX_STATE_DEFAULT = 0, // 0 is default, no good MX_STATE_NO_US = 1, // 1 is set but does not have us MX_STATE_INC_US = 2, // 2 is includes our MX but priority no good MX_STATE_GOOD = 3, // 3 is includes our MX and we are highest and pri is legit, good! } export enum SPF_STATE { SPF_STATE_DEFAULT = 0, // 0 is default, no spf record SPF_STATE_ONE = 1, // 1 is has spf record but not us SPF_STATE_MULT = 2, // 2 is has multiple spf records, no good SPF_STATE_GOOD = 3, // 3 is has spf record and includes us, good! } export enum DKIM_STATE { DKIM_STATE_DEFAULT = 0, DKIM_STATE_ERROR = 3, DKIM_STATE_GOOD = 4, DKIM_STATE_WARNING = 6, } export enum DMARC_STATE { DMARC_STATE_DEFAULT = 0, // 0 is default, no dmarc record DMARC_STATE_ONE = 1, // 1 is found entries but format wrong DMARC_STATE_MULT = 2, // 2 is multiple dmarc records, no good DMARC_STATE_GOOD = 3, // 3 is good! } export interface Domain { ID: string; DomainName: string; VerifyCode: string; DkimPublicKey: string; State: DOMAIN_STATE; CheckTime: number; LastActiveTime: number; WarnTime: number; VerifyState: VERIFY_STATE; // 0 is default, 1 is has code but wrong, 2 is good MxState: MX_STATE; // 0 is default, 1 is set but no us, 2 has us but priority is wrong, 3 is good SpfState: SPF_STATE; // 0 is default, 1 and 2 means detected a record but wrong, 3 is good DKIM: { State: DKIM_STATE; // 0 is default, 1 and 2 means detected record but wrong, 3 means key is wrong, 4 is good, 5 is turned off by user through DNS Config: DKIMConfig[]; }; DmarcState: DMARC_STATE; // 0 is default, 1 and 2 means detected record but wrong, 3 is good }
8,542
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Drawer.ts
export interface DrawerFeatureFlag { CalendarInMail: boolean; CalendarInDrive: boolean; ContactsInMail: boolean; ContactsInCalendar: boolean; ContactsInDrive: boolean; }
8,543
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/EncryptionPreferences.ts
import { PublicKeyReference } from '@proton/crypto'; import { CONTACT_MIME_TYPES, CONTACT_PGP_SCHEMES, KEY_FLAG, MIME_TYPES, PGP_SCHEMES, RECIPIENT_TYPES, } from '../constants'; import { Address } from './Address'; import { KeyTransparencyVerificationResult } from './KeyTransparency'; import { MailSettings } from './MailSettings'; export interface PublicKeyWithPref { publicKey: PublicKeyReference; pref?: number; } export interface SelfSend { address: Address; publicKey?: PublicKeyReference; canSend?: boolean; } export type MimeTypeVcard = MIME_TYPES.PLAINTEXT; export interface ProcessedApiKey { armoredKey: string; flags: KEY_FLAG; publicKey?: PublicKeyReference; } export interface ApiKeysConfig { publicKeys: ProcessedApiKey[]; Code?: number; RecipientType?: RECIPIENT_TYPES; isCatchAll?: boolean; /** * Internal addresses with e2ee disabled are marked as having EXTERNAL recipient type. * This flag allows distinguishing them from actual external users, for which E2EE should * never be disabled, even for mail (since e.g. they might have WKD set up, or uploaded keys associated with them). */ isInternalWithDisabledE2EEForMail?: boolean; MIMEType?: MIME_TYPES; Warnings?: string[]; Errors?: string[]; ktVerificationResult?: KeyTransparencyVerificationResult; } export interface PinnedKeysConfig { pinnedKeys: PublicKeyReference[]; encryptToPinned?: boolean; encryptToUntrusted?: boolean; sign?: boolean; scheme?: PGP_SCHEMES; mimeType?: MimeTypeVcard; error?: Error; isContact: boolean; isContactSignatureVerified?: boolean; contactSignatureTimestamp?: Date; } export interface PublicKeyConfigs { emailAddress: string; apiKeysConfig: ApiKeysConfig; pinnedKeysConfig: PinnedKeysConfig; mailSettings: MailSettings; } export interface ContactPublicKeyModel { emailAddress: string; publicKeys: { apiKeys: PublicKeyReference[]; pinnedKeys: PublicKeyReference[]; verifyingPinnedKeys: PublicKeyReference[]; // Subset of pinned keys not marked as compromised }; encrypt?: boolean; sign?: boolean; mimeType: CONTACT_MIME_TYPES; scheme: CONTACT_PGP_SCHEMES; isInternalWithDisabledE2EEForMail: boolean; // Both `encrypt` and `isInternalWithDisabledE2EEForMail` might be true at this stage trustedFingerprints: Set<string>; obsoleteFingerprints: Set<string>; // Keys that are not allowed to encrypt, because they are marked as obsolete. encryptionCapableFingerprints: Set<string>; // Keys that are capable of encryption (regardless of whether they are allowed to encrypt). compromisedFingerprints: Set<string>; // Keys that are not allowed to encrypt nor sign, because they are marked as compromised isPGPExternal: boolean; isPGPInternal: boolean; isPGPExternalWithWKDKeys: boolean; isPGPExternalWithoutWKDKeys: boolean; pgpAddressDisabled: boolean; isContact: boolean; isContactSignatureVerified?: boolean; contactSignatureTimestamp?: Date; emailAddressWarnings?: string[]; emailAddressErrors?: string[]; ktVerificationResult?: KeyTransparencyVerificationResult; } export interface PublicKeyModel { emailAddress: string; publicKeys: { apiKeys: PublicKeyReference[]; pinnedKeys: PublicKeyReference[]; verifyingPinnedKeys: PublicKeyReference[]; }; encrypt: boolean; sign: boolean; mimeType: CONTACT_MIME_TYPES; scheme: PGP_SCHEMES; isInternalWithDisabledE2EEForMail: boolean; // Both `encrypt` and `isInternalWithDisabledE2EEForMail` might be true at this stage trustedFingerprints: Set<string>; obsoleteFingerprints: Set<string>; encryptionCapableFingerprints: Set<string>; compromisedFingerprints: Set<string>; isPGPExternal: boolean; isPGPInternal: boolean; isPGPExternalWithWKDKeys: boolean; isPGPExternalWithoutWKDKeys: boolean; pgpAddressDisabled: boolean; isContact: boolean; isContactSignatureVerified?: boolean; contactSignatureTimestamp?: Date; emailAddressWarnings?: string[]; emailAddressErrors?: string[]; ktVerificationResult?: KeyTransparencyVerificationResult; }
8,544
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Environment.ts
export type Environment = 'alpha' | 'beta'; export type EnvironmentExtended = Environment | 'default';
8,545
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Folder.ts
export interface Folder { ID: string; Name: string; Color: string; Path: string; Expanded: number; Type: number; Order: number; ParentID?: number | string; Notify: number; } export type FolderWithSubFolders = Folder & { subfolders?: Folder[] };
8,546
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Hotkeys.ts
// The following enum was initially taken from // https://github.com/ashubham/w3c-keys/blob/master/dist/index.d.ts export enum KeyboardKey { Backspace = 'Backspace', Tab = 'Tab', Enter = 'Enter', Shift = 'Shift', Control = 'Control', Alt = 'Alt', CapsLock = 'CapsLock', Escape = 'Escape', Space = ' ', Spacebar = ' ', PageUp = 'PageUp', PageDown = 'PageDown', End = 'End', Home = 'Home', ArrowLeft = 'ArrowLeft', ArrowUp = 'ArrowUp', ArrowRight = 'ArrowRight', ArrowDown = 'ArrowDown', Left = 'Left', Up = 'Up', Right = 'Right', Down = 'Down', Insert = 'Insert', Delete = 'Delete', Zero = '0', ClosedParen = ')', One = '1', ExclamationMark = '!', Two = '2', AtSign = '@', Three = '3', PoundSign = '\u00A3', Hash = '#', Four = '4', DollarSign = '$', Five = '5', PercentSign = '%', Six = '6', Caret = '^', Hat = '^', Seven = '7', Ampersand = '&', Eight = '8', Star = '*', Asterisk = '*', Nine = '9', OpenParen = '(', a = 'a', b = 'b', c = 'c', d = 'd', e = 'e', f = 'f', g = 'g', h = 'h', i = 'i', j = 'j', k = 'k', l = 'l', m = 'm', n = 'n', o = 'o', p = 'p', q = 'q', r = 'r', s = 's', t = 't', u = 'u', v = 'v', w = 'w', x = 'x', y = 'y', z = 'z', A = 'A', B = 'B', C = 'C', D = 'D', E = 'E', F = 'F', G = 'G', H = 'H', I = 'I', J = 'J', K = 'K', L = 'L', M = 'M', N = 'N', O = 'O', P = 'P', Q = 'Q', R = 'R', S = 'S', T = 'T', U = 'U', V = 'V', W = 'W', X = 'X', Y = 'Y', Z = 'Z', Meta = 'Meta', LeftWindowKey = 'Meta', RightWindowKey = 'Meta', Numpad0 = '0', Numpad1 = '1', Numpad2 = '2', Numpad3 = '3', Numpad4 = '4', Numpad5 = '5', Numpad6 = '6', Numpad7 = '7', Numpad8 = '8', Numpad9 = '9', Multiply = '*', Add = '+', Subtract = '-', DecimalPoint = '.', MSDecimalPoint = 'Decimal', Divide = '/', F1 = 'F1', F2 = 'F2', F3 = 'F3', F4 = 'F4', F5 = 'F5', F6 = 'F6', F7 = 'F7', F8 = 'F8', F9 = 'F9', F10 = 'F10', F11 = 'F11', F12 = 'F12', NumLock = 'NumLock', ScrollLock = 'ScrollLock', SemiColon = ';', Equals = '=', Comma = ',', Dash = '-', Period = '.', UnderScore = '_', PlusSign = '+', Slash = '/', ForwardSlash = '/', Tilde = '~', GraveAccent = '`', OpenBracket = '[', ClosedBracket = ']', Quote = "'", QuestionMark = '?', } export type KeyboardKeyType = keyof typeof KeyboardKey | KeyboardKey;
8,547
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/IncomingDefault.ts
import { INCOMING_DEFAULTS_LOCATION } from '../constants'; export interface IncomingDefault { ID: string; Email?: string; Domain?: string; Location: INCOMING_DEFAULTS_LOCATION; Type: number; Time: number; } export type IncomingDefaultStatus = 'not-loaded' | 'pending' | 'loaded' | 'rejected';
8,548
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Key.ts
import { PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import { RequireSome } from './utils'; export interface KeyWithRecoverySecret extends Key { RecoverySecret: string; RecoverySecretSignature: string; } export interface Key { ID: string; Primary: 1 | 0; Active: 1 | 0; Flags?: number; // Only available for address keys Fingerprint: string; Fingerprints: string[]; PublicKey: string; // armored key Version: number; Activation?: string; PrivateKey: string; // armored key Token?: string; Signature?: string; // Only available for address keys RecoverySecret?: string | null; // Only available for user keys RecoverySecretSignature?: string | null; // Only available for user keys AddressForwardingID?: string | null; // Only available for address keys } export type AddressKey = RequireSome<Key, 'Flags' | 'Signature' | 'AddressForwardingID'>; export type UserKey = RequireSome<Key, 'RecoverySecret' | 'RecoverySecretSignature'>; export interface KeyPair { privateKey: PrivateKeyReference; publicKey: PublicKeyReference; } export interface KeysPair { privateKeys: PrivateKeyReference[]; publicKeys: PublicKeyReference[]; } export interface DecryptedKey extends KeyPair { ID: string; } export interface DecryptedAddressKey extends KeyPair { ID: string; Flags: number; Primary: 1 | 0; } export interface InactiveKey { Key: Key; publicKey?: PublicKeyReference; fingerprint?: string; } export interface ActiveKey extends DecryptedKey { fingerprint: string; flags: number; primary: 1 | 0; sha256Fingerprints: string[]; }
8,549
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/KeySalt.ts
export interface KeySalt { ID: string; KeySalt: string; }
8,550
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/KeyTransparency.ts
import { PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import { Epoch, SelfAuditResult } from '@proton/key-transparency/lib'; import { Address } from './Address'; import { ProcessedApiKey } from './EncryptionPreferences'; import { DecryptedAddressKey, DecryptedKey, KeyPair } from './Key'; import { FetchedSignedKeyList, SignedKeyList } from './SignedKeyList'; import { User } from './User'; export enum IGNORE_KT { NORMAL, EXTERNAL, CATCHALL, } export interface ProcessedAddressKey extends ProcessedApiKey { flags: number; publicKey: PublicKeyReference; primary: 1 | 0; } export interface KTLocalStorageAPI { getBlobs: () => Promise<string[]>; removeItem: (key: string) => Promise<void | undefined>; getItem: (key: string) => Promise<string | null | undefined>; setItem: (key: string, value: string) => Promise<void | undefined>; } export interface SelfAuditState { userKeys: KeyPair[]; epoch: Epoch; addresses: { address: Address; addressKeys: DecryptedAddressKey[]; }[]; } export interface KeyTransparencyState { selfAuditResult?: SelfAuditResult; } export type KeyTransparencyVerify = ( address: Address, signedKeyList: SignedKeyList, publicKeys: PublicKeyReference[] ) => Promise<void>; export type PreAuthKTVerify = (userKeys: DecryptedKey[]) => KeyTransparencyVerify; export type KeyTransparencyCommit = (userKeys: DecryptedKey[]) => Promise<void>; export interface PreAuthKTVerifier { preAuthKTVerify: PreAuthKTVerify; preAuthKTCommit: (userID: string) => Promise<void>; } export enum ApiAddressKeySource { PROTON = 0, WKD = 1, UNKNOWN, } export interface ApiAddressKey { PublicKey: string; Flags: number; Source: number; } export interface ProcessedApiAddressKey { armoredPublicKey: string; flags: number; publicKeyRef: PublicKeyReference; source: ApiAddressKeySource; } export type VerifyOutboundPublicKeys = ( email: string, /** * Optimisations for apps where users with external domains do not have valid keys (e.g. Mail) */ skipVerificationOfExternalDomains: boolean, address: { keyList: ProcessedApiAddressKey[]; signedKeyList: FetchedSignedKeyList | null; }, catchAll?: { keyList: ProcessedApiAddressKey[]; signedKeyList: FetchedSignedKeyList | null; } ) => Promise<{ addressKTResult?: KeyTransparencyVerificationResult; catchAllKTResult?: KeyTransparencyVerificationResult; }>; export type SaveSKLToLS = ( email: string, data: string, revision: number, expectedMinEpochID: number, addressID?: string, isCatchall?: boolean ) => Promise<void>; export type KeyMigrationKTVerifier = ( email: string, signedKeyList: Partial<FetchedSignedKeyList> | null | undefined ) => Promise<void>; export enum KeyTransparencyActivation { DISABLED, LOG_ONLY, SHOW_UI, } export type GetLatestEpoch = (forceRefresh?: boolean) => Epoch; export enum KT_VERIFICATION_STATUS { VERIFIED_KEYS, UNVERIFIED_KEYS, VERIFICATION_FAILED, } export interface KeyTransparencyVerificationResult { status: KT_VERIFICATION_STATUS; keysChangedRecently?: boolean; } export type UploadMissingSKL = (address: Address, epoch: Epoch, saveSKLToLS: SaveSKLToLS) => Promise<void>; export type ResetSelfAudit = (user: User, keyPassword: string, addressesBeforeReset: Address[]) => Promise<void>; export interface ResignSKLWithPrimaryKeyArguments { address: Address; newPrimaryKey: PrivateKeyReference; formerPrimaryKey: PublicKeyReference; userKeys: DecryptedKey[]; } export type ResignSKLWithPrimaryKey = (args: ResignSKLWithPrimaryKeyArguments) => Promise<void>;
8,551
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Label.ts
export interface Label { ID: string; Name: string; Color: string; ContextTime?: number; Type: number; Order: number; Path: string; Display?: number; } export interface LabelCount { LabelID?: string; Total?: number; Unread?: number; }
8,552
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Locale.ts
import { Locale } from 'date-fns'; import { LocaleData } from 'ttag'; import { SimpleMap } from './utils'; export type TtagLocaleMap = SimpleMap<() => Promise<LocaleData>>; export interface DateFnsLocaleMap { [key: string]: () => Promise<Locale>; }
8,553
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/MailSettings.ts
import { BLOCK_SENDER_CONFIRMATION } from '../mail/constants'; import { ALMOST_ALL_MAIL, ATTACH_PUBLIC_KEY, AUTO_DELETE_SPAM_AND_TRASH_DAYS, AUTO_SAVE_CONTACTS, COMPOSER_MODE, CONFIRM_LINK, DELAY_IN_SECONDS, DIRECTION, DRAFT_MIME_TYPES, FOLDER_COLOR, HIDE_SENDER_IMAGES, INHERIT_PARENT_FOLDER_COLOR, KEY_TRANSPARENCY_SETTING, MESSAGE_BUTTONS, PACKAGE_TYPE, PM_SIGNATURE, PM_SIGNATURE_REFERRAL, PROMPT_PIN, SHORTCUTS, SHOW_IMAGES, SIGN, SPAM_ACTION, STICKY_LABELS, UNREAD_FAVICON, VIEW_LAYOUT, VIEW_MODE, } from '../mail/mailSettings'; export interface AutoResponder { StartTime: number; EndTime: number; Repeat: number; DaysSelected: number[]; Subject: string; Message: string; IsEnabled: boolean; Zone: string; } export interface MailSettings { DisplayName: string; Signature: string; Theme: string; AutoResponder: AutoResponder; AutoSaveContacts: AUTO_SAVE_CONTACTS; ComposerMode: COMPOSER_MODE; MessageButtons: MESSAGE_BUTTONS; ShowMoved: number; ViewMode: VIEW_MODE; ViewLayout: VIEW_LAYOUT; SwipeLeft: number; SwipeRight: number; HideEmbeddedImages: SHOW_IMAGES; HideRemoteImages: SHOW_IMAGES; Shortcuts: SHORTCUTS; // used by v4 PMSignature: PM_SIGNATURE; PMSignatureReferralLink: PM_SIGNATURE_REFERRAL; ImageProxy: number; RightToLeft: DIRECTION; AttachPublicKey: ATTACH_PUBLIC_KEY; Sign: SIGN; PGPScheme: PACKAGE_TYPE; PromptPin: PROMPT_PIN; NumMessagePerPage: number; DraftMIMEType: DRAFT_MIME_TYPES; StickyLabels: STICKY_LABELS; ConfirmLink: CONFIRM_LINK; DelaySendSeconds: DELAY_IN_SECONDS; EnableFolderColor: FOLDER_COLOR; InheritParentFolderColor: INHERIT_PARENT_FOLDER_COLOR; /** * FontFace value is a FONT_FACES.${FONT}.id value or null. */ FontFace: string | null; FontSize: number | null; SpamAction: SPAM_ACTION | null; BlockSenderConfirmation: BLOCK_SENDER_CONFIRMATION | null; HideSenderImages: HIDE_SENDER_IMAGES; AutoDeleteSpamAndTrashDays: AUTO_DELETE_SPAM_AND_TRASH_DAYS | null; UnreadFavicon: UNREAD_FAVICON; RecipientLimit: number; AlmostAllMail: ALMOST_ALL_MAIL; ReceiveMIMEType: string; ShowMIMEType: string; KT: KEY_TRANSPARENCY_SETTING; }
8,554
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Member.ts
import { MEMBER_PRIVATE, MEMBER_ROLE, MEMBER_TYPE } from '../constants'; import { Key } from './Key'; export interface PartialMemberAddress { ID: string; Email: string; } export enum FAMILY_PLAN_INVITE_STATE { STATUS_DISABLED = 0, STATUS_ENABLED = 1, STATUS_INVITED = 2, } export interface Member { ID: string; Role: MEMBER_ROLE; Private: MEMBER_PRIVATE; Type: MEMBER_TYPE; ToMigrate: 0 | 1; MaxSpace: number; MaxVPN: number; Name: string; UsedSpace: number; Self: number; Subscriber: number; Keys: Key[]; PublicKey: string; BrokenSKL: 0 | 1; Addresses?: PartialMemberAddress[]; '2faStatus': number; State?: FAMILY_PLAN_INVITE_STATE; //This is only available for the family invitations TwoFactorRequiredTime: number; SSO: 1 | 0; }
8,555
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Modal.ts
export interface ModalWithProps<T = void> { isOpen: boolean; props?: T; }
8,556
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Model.ts
import { Api } from './Api'; export interface Model<T> { key: string; get: (api: Api) => T; update: (oldModel: T, newModel: Partial<T>) => T; }
8,557
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Organization.ts
import { ORGANIZATION_TWOFA_SETTING, PLANS } from '@proton/shared/lib/constants'; export interface Organization { Name: string; DisplayName: string; // DEPRECATED PlanName: PLANS; VPNPlanName: string; TwoFactorRequired: ORGANIZATION_TWOFA_SETTING; // If 0, 2FA not required, if 1, 2FA required for admins only, if 2, 2FA required for all TwoFactorGracePeriod: number; // If non-null, number of seconds until 2FA setup enforced Theme: string; ToMigrate: 0 | 1; BrokenSKL: 0 | 1; Email: string; MaxDomains: number; MaxAddresses: number; MaxCalendars: number; MaxSpace: number; MaxMembers: number; MaxVPN: number; Features: number; // bits: 1 = catch-all addresses Flags: number; // bits: 1 = loyalty, 2 = covid, 4 = smtp_submission, 8 = no_cycle_scheduled, 64 = dissident, 128 = proton UsedDomains: number; UsedCalendars: number; RequiresKey: number; // greater than 0 if the organization requires a key to be setup RequiresDomain: number; // greater than 0 of the organization requires custom domain UsedAddresses: number; UsedSpace: number; AssignedSpace: number; UsedMembers: number; UsedVPN: number; InvitationsRemaining: number; HasKeys: number; CreateTime: number; LoyaltyCounter: number; LoyaltyIncrementTime: number; BonusDomains: number; BonusAddresses: number; BonusSpace: number; BonusMembers: number; BonusVPN: number; Permissions: number; }
8,558
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/OrganizationKey.ts
import { PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; export interface OrganizationKey { PrivateKey?: string; PublicKey: string; } export type CachedOrganizationKey = | { Key: OrganizationKey; privateKey?: undefined; publicKey?: undefined; error?: Error; } | { Key: OrganizationKey; privateKey: PrivateKeyReference; publicKey: PublicKeyReference; error?: undefined; };
8,559
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/PendingInvitation.ts
export interface PendingInvitation { ID: string; InviterEmail: string; MaxSpace: number; OrganizationName: string; Validation: AcceptInvitationValidation; } export interface AcceptInvitationValidation { Valid: boolean; IsLifetimeAccount: boolean; IsOnForbiddenPlan: boolean; HasOrgWithMembers: boolean; HasCustomDomains: boolean; ExceedsMaxSpace: boolean; ExceedsAddresses: boolean; ExceedsMaxAcceptedInvitations: boolean; IsExternalUser: boolean; }
8,560
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Referrals.ts
/** * State of referred user * - `0` => `invited` : The user has been invited (email invite only) * - `1` => `signedup` : User signed up with the link * - `2` => `trial` : User accepted the free trial * - `3` => `completed` : User paid a plus subscription * - `4` => `rewarded` : After some processing reward is given to referrer */ export enum ReferralState { INVITED = 0, SIGNED_UP = 1, TRIAL = 2, COMPLETED = 3, REWARDED = 4, } export interface Referral { /** Unique id of referred registration/invitation */ ReferralID: string; /** * Encrypted id of the Referrer user id */ UserId: string; /** * Encrypted id of the Referred User id : * - `null` if it's an email invitations where the referred user has not yet registered */ ReferredUserID: string | null; /** Referral creation time (can be registration time or invitation time for email invitations) */ CreateTime: number; /** not null only for email invitations */ Email: string | null; /** referred user registration time */ SignupTime: number | null; /** when the referred user started its free trial */ TrialTime: number | null; /** when the referral was validated but the referred was already at the maximum allowed reward (or not yet given) */ CompleteTime: number | null; /** when we gave the reward to the referrer */ RewardTime: number | null; /** The amount of reward amount given to the referrer */ RewardMonths: number | null; State: ReferralState; InvoiceID: number | null; /** The number of months user subscribed. If monthly will be 1. If yearly will be 12 */ ReferredUserSubscriptionCycle: number | null; } export interface ReferralStatus { /** Number of free monthes of mail plus */ RewardMonths: number; /** Max number of free monthes user can have */ RewardMonthsLimit: number; /** Number of emails user can send */ EmailsAvailable: number; }
8,561
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/SignedKeyList.ts
// Interface for SignedKeyList generated by the FE before uploading export interface SignedKeyList { Data: string; Signature: string; } // Metadata of a public key included in the SKL's Data property export interface SignedKeyListItem { Primary: 0 | 1; Flags: number; Fingerprint: string; SHA256Fingerprints: string[]; } interface SKLEpochs { Data: string | null; Signature: string | null; MinEpochID: number | null; MaxEpochID: number | null; ObsolescenceToken?: string; ExpectedMinEpochID?: number; Revision?: number; } export interface ActiveSignedKeyList extends SignedKeyList, SKLEpochs { Data: string; Signature: string; } export interface ObsolescentSignedKeyList extends SKLEpochs { ObsolescenceToken: string; } export interface ActiveSignedKeyListWithRevision extends ActiveSignedKeyList { Revision: number; } export interface ObsolescentSignedKeyListWithRevision extends ObsolescentSignedKeyList { Revision: number; } // SKL served by the server. Note that Data and Signature // might be missing or be null for obsolescent SKLs export type FetchedSignedKeyList = ActiveSignedKeyListWithRevision | ObsolescentSignedKeyListWithRevision;
8,562
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/Subscription.ts
import { ADDON_NAMES, CYCLE, PLANS, PLAN_TYPES } from '../constants'; export type Currency = 'EUR' | 'CHF' | 'USD'; export type Cycle = CYCLE.MONTHLY | CYCLE.YEARLY | CYCLE.TWO_YEARS | CYCLE.THIRTY | CYCLE.FIFTEEN; export interface CycleMapping<T> { [CYCLE.MONTHLY]?: T; [CYCLE.YEARLY]?: T; [CYCLE.TWO_YEARS]?: T; // Not always included for all plans [CYCLE.THIRTY]?: T; [CYCLE.FIFTEEN]?: T; } export type Pricing = CycleMapping<number>; export type MaxKeys = 'MaxDomains' | 'MaxAddresses' | 'MaxSpace' | 'MaxMembers' | 'MaxVPN' | 'MaxTier' | 'MaxIPs'; export type Quantity = number; export interface Offer { Name: string; StartTime: number; EndTime: number; Pricing: Partial<Pricing>; } export interface Plan { ID: string; Type: PLAN_TYPES; Cycle: Cycle; Name: PLANS | ADDON_NAMES; Title: string; Currency: Currency; Amount: number; MaxDomains: number; MaxAddresses: number; MaxSpace: number; MaxCalendars: number; MaxMembers: number; MaxVPN: number; MaxTier: number; Services: number; Features: number; Quantity: Quantity; Pricing: Pricing; DefaultPricing?: Pricing; State: number; Offers: Offer[]; } export const getPlanMaxIPs = (plan: Plan) => { if (plan.Name === PLANS.VPN_BUSINESS || plan.Name === ADDON_NAMES.IP_VPN_BUSINESS) { return 1; } return 0; }; export enum Renew { Disabled = 0, Enabled = 1, } export enum External { Default = 0, iOS = 1, Android = 2, Chargebee = 3, } export interface Subscription { ID: string; InvoiceID: string; Cycle: Cycle; PeriodStart: number; PeriodEnd: number; CreateTime: number; CouponCode: null | string; Currency: Currency; Amount: number; RenewAmount: number; Renew: Renew; Discount: number; Plans: Plan[]; External: External; } export interface SubscriptionModel extends Subscription { isManagedByMozilla: boolean; UpcomingSubscription?: Subscription | null; } export type PlanIDs = Partial<{ [planName in PLANS | ADDON_NAMES]: Quantity; }>; export type PlansMap = Partial<{ [planName in PLANS | ADDON_NAMES]: Plan; }>; export interface Additions { [ADDON_NAMES.ADDRESS]?: number; [ADDON_NAMES.DOMAIN]?: number; [ADDON_NAMES.DOMAIN_ENTERPRISE]?: number; [ADDON_NAMES.DOMAIN_BUNDLE_PRO]?: number; [ADDON_NAMES.MEMBER]?: number; [ADDON_NAMES.SPACE]?: number; [ADDON_NAMES.VPN]?: number; [ADDON_NAMES.MEMBER_MAIL_PRO]?: number; [ADDON_NAMES.MEMBER_DRIVE_PRO]?: number; [ADDON_NAMES.MEMBER_BUNDLE_PRO]?: number; [ADDON_NAMES.MEMBER_ENTERPRISE]?: number; } export interface SubscriptionCheckResponse { Amount: number; AmountDue: number; Proration?: number; CouponDiscount?: number; Coupon: null | { Code: string; Description: string; }; UnusedCredit?: number; Credit?: number; Currency: Currency; Cycle: Cycle; Gift?: number; Additions: null | Additions; PeriodEnd: number; } export enum Audience { B2C = 0, B2B = 1, FAMILY = 2, }
8,563
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/User.ts
import { USER_ROLES } from '../constants'; import { Key } from './Key'; import { Currency } from './Subscription'; export enum MNEMONIC_STATUS { DISABLED = 0, ENABLED = 1, OUTDATED = 2, SET = 3, PROMPT = 4, } export enum UserType { PROTON = 1, MANAGED = 2, EXTERNAL = 3, } export enum SessionRecoveryState { NONE = 0, GRACE_PERIOD = 1, CANCELLED = 2, INSECURE = 3, EXPIRED = 4, } export enum SessionRecoveryReason { NONE = 0, CANCELLED = 1, AUTHENTICATION = 2, } export interface User { ID: string; Name: string; UsedSpace: number; Currency: Currency; Credit: number; MaxSpace: number; MaxUpload: number; Role: USER_ROLES; Private: number; Type: UserType; Subscribed: number; Services: number; Delinquent: number; Email: string; DisplayName: string; OrganizationPrivateKey?: string; Keys: Key[]; DriveEarlyAccess: number; ToMigrate: 0 | 1; MnemonicStatus: MNEMONIC_STATUS; Idle: 0 | 1; CreateTime: number; Flags: { protected: boolean; 'drive-early-access': boolean; 'onboard-checklist-storage-granted': boolean; 'has-temporary-password': boolean; 'test-account': boolean; 'no-login': boolean; 'recovery-attempt': boolean; sso: boolean; }; AccountRecovery: { State: SessionRecoveryState; StartTime: number; EndTime: number; Reason: SessionRecoveryReason | null; UID: string; } | null; } export interface UserModel extends User { isAdmin: boolean; isMember: boolean; isFree: boolean; isPaid: boolean; isPrivate: boolean; isSubUser: boolean; isDelinquent: boolean; hasNonDelinquentScope: boolean; hasPaidMail: boolean; hasPaidVpn: boolean; hasPaidDrive: boolean; canPay: boolean; }
8,564
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/UserSettings.ts
import type { ThemeSetting } from '@proton/shared/lib/themes/themes'; import { DENSITY } from '../constants'; import { RegisteredKey } from '../webauthn/interface'; import { ChecklistId } from './Checklist'; export enum SETTINGS_STATUS { UNVERIFIED = 0, VERIFIED = 1, INVALID = 2, } export enum SETTINGS_PASSWORD_MODE { ONE_PASSWORD_MODE = 1, TWO_PASSWORD_MODE = 2, } export enum SETTINGS_LOG_AUTH_STATE { DISABLE = 0, BASIC = 1, ADVANCED = 2, } export enum SETTINGS_PROTON_SENTINEL_STATE { DISABLED = 0, ENABLED = 1, } export enum SETTINGS_WEEK_START { LOCALE_DEFAULT = 0, MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 4, FRIDAY = 5, SATURDAY = 6, SUNDAY = 7, } export enum SETTINGS_DATE_FORMAT { LOCALE_DEFAULT = 0, DDMMYYYY = 1, MMDDYYYY = 2, YYYYMMDD = 3, } export enum SETTINGS_TIME_FORMAT { LOCALE_DEFAULT = 0, H24 = 1, H12 = 2, } export enum SETTINGS_2FA_ENABLED { OTP = 1, FIDO2 = 2, } export const enum DRAWER_VISIBILITY { SHOW = 0, HIDE = 1, } export interface Flags { Welcomed: number; } export interface UserSettings { '2FA': { Enabled: number; // 0 for disabled, 1 for OTP, 2 for FIDO2, 3 for both Allowed: number; // 0 for disabled, 1 for OTP, 2 for FIDO2, 3 for both ExpirationTime: number | null; // If set, after this time force add 2FA RegisteredKeys: RegisteredKey[]; }; AppWelcome: { Account?: string[]; Calendar?: string[]; Contacts?: string[]; Mail?: string[]; Drive?: string[]; }; Checklists?: ChecklistId[]; CrashReports: 1 | 0; DateFormat: SETTINGS_DATE_FORMAT; DeviceRecovery: 0 | 1; Density: DENSITY; EarlyAccess: number; Email: { Value: string; Status: SETTINGS_STATUS; Notify: number; Reset: number; }; Flags: Flags; HideSidePanel: DRAWER_VISIBILITY; InvoiceText: string; Locale: string; LogAuth: SETTINGS_LOG_AUTH_STATE; News: number; Phone: { Value: string; Status: SETTINGS_STATUS; Notify: number; Reset: number; }; Password: { Mode: SETTINGS_PASSWORD_MODE; ExpirationTime: number; // If set, after this time force password change }; HighSecurity: { /** * 1 => user can enable High Security, 0 => can't enable */ Eligible: 1 | 0; /** * 1 => user has High Security enabled, 0 => disabled */ Value: SETTINGS_PROTON_SENTINEL_STATE; }; Referral?: { /** * 0 - Not elligible to * 1 - Elligible to "refer a friend" */ Eligible: boolean; /** * The referral link * will always be a string containing the link. */ Link: string; }; SessionAccountRecovery: 1 | 0; Telemetry: 1 | 0; Theme: ThemeSetting | null; ThemeType: number; TimeFormat: SETTINGS_TIME_FORMAT; WeekStart: SETTINGS_WEEK_START; WelcomeFlag: number; Welcome: number; }
8,565
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/VPN.ts
export interface MyLocationResponse { IP: string; Lat: number; Long: number; Country: string; ISP: string; } export interface VPNServersCount { Capacity: number; Countries: number; Servers: number; } export interface VPNServersCountData { free: { countries: number; servers: number; }; paid: { countries: number; servers: number; }; } export interface VPNServersCounts { free: VPNServersCount; paid: VPNServersCount; } export interface VPNLogicalsCount { Counts: { 2: number; 0: number }; } export interface VPNCountryCount { MaxTier: 0 | 1 | 2; Count: number; } export interface VPNCountriesCount { Counts: VPNCountryCount[]; }
8,566
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/VPNServer.ts
export interface ServerLocation { Lat: number; Long: number; } interface Server { Domain: string; EntryIP: string; ExitIP: string; ID: string; Status: number; } export interface VPNServer { City: string | null; Country: string; Domain: string; EntryCountry: string; ExitCountry: string; Features: number; ID: string; Load: number; Location: ServerLocation; Name: string; Score: number; Servers: Server[]; Status: number; Tier: number; }
8,567
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/VerificationPreferences.ts
import { PublicKeyReference } from '@proton/crypto'; import { KeyTransparencyVerificationResult } from './KeyTransparency'; export interface VerificationPreferences { isOwnAddress: boolean; verifyingKeys: PublicKeyReference[]; apiKeys: PublicKeyReference[]; pinnedKeys: PublicKeyReference[]; compromisedKeysFingerprints?: Set<string>; pinnedKeysFingerprints?: Set<string>; ktVerificationResult?: KeyTransparencyVerificationResult; pinnedKeysVerified?: boolean; apiKeysErrors?: string[]; }
8,568
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/config.ts
import { APP_NAMES, CLIENT_TYPES } from '../constants'; export interface ProtonConfig { CLIENT_TYPE: CLIENT_TYPES; CLIENT_SECRET: string; APP_VERSION: string; APP_NAME: APP_NAMES; API_URL: string; LOCALES: { [key: string]: string }; DATE_VERSION: string; COMMIT: string; BRANCH: string; SENTRY_DSN: string; SENTRY_DESKTOP_DSN?: string; VERSION_PATH: string; }
8,569
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/index.ts
import type { enums } from '@proton/crypto'; export * from './Address'; export * from './AddressForwarding'; export * from './Api'; export * from './ApiEnvironmentConfig'; export * from './Checklist'; export * from './Domain'; export * from './EncryptionPreferences'; export * from './Environment'; export * from './Hotkeys'; export * from './IncomingDefault'; export * from './Key'; export * from './KeySalt'; export * from './KeyTransparency'; export * from './Label'; export * from './MailSettings'; export * from './Member'; export * from './Organization'; export * from './OrganizationKey'; export * from './PendingInvitation'; export * from './Referrals'; export * from './SignedKeyList'; export * from './Subscription'; export * from './User'; export * from './UserSettings'; export * from './VPN'; export * from './config'; export * from './utils'; export interface EncryptionConfig { type?: 'ecc' | 'rsa'; curve?: enums.curve; rsaBits?: number; } export type HumanVerificationMethodType = | 'captcha' | 'payment' | 'sms' | 'email' | 'invite' | 'coupon' | 'ownership-email' | 'ownership-sms';
8,570
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/message.ts
export enum CREATE_DRAFT_MESSAGE_ACTION { REPLY = 0, REPLY_ALL = 1, FORWARD = 2, } export enum SEND_MESSAGE_DIRECT_ACTION { REPLY = 0, REPLY_ALL = 1, FORWARD = 2, AUTO_RESPONSE = 3, READ_RECEIPT = 4, }
8,571
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/utils.ts
export type SimpleMap<T> = { [key: string]: T | undefined }; export type MaybeArray<T> = T[] | T; export type LoadingMap = SimpleMap<boolean>; export type RequireOnly<T, Keys extends keyof T> = Partial<T> & Required<Pick<T, Keys>>; export type RequireSome<T, Keys extends keyof T> = T & Required<Pick<T, Keys>>; export type Unwrap<T> = T extends Promise<infer U> ? U : T extends (...args: any) => Promise<infer U> ? U : T extends (...args: any) => infer U ? U : T; export type Nullable<T> = T | null; /** * Allow interface to have "specific" optinal entries. * Works the following : Optional<MyInterface, 'keya' | 'keyb'> */ export type Optional<T extends object, K extends keyof T = keyof T> = Omit<T, K> & Partial<Pick<T, K>>; /** * Like TypeScript's `Partial<T>` utility type, but recurses into arrays and objects. * * ```typescript * // For example, with the following type * type Example = { a: { b: number[], c: string }}; * type PartialExample = { a?: { b: number[], c: string }}; * type DeepPartialExample = { a?: { b?: (number | undefined)[], c?: string }}; * ``` */ export type DeepPartial<T> = T extends (infer E)[] ? DeepPartial<E>[] : T extends object ? { [K in keyof T]?: DeepPartial<T[K]>; } : T | undefined;
8,572
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Alarm.ts
export interface CalendarAlarm { ID: string; CalendarID: string; Occurrence: number; Trigger: string; Action: number; EventID: string; MemberID: string; }
8,573
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Api.ts
import { PaginationParams } from '../../api/interface'; import { CALENDAR_DISPLAY, CALENDAR_TYPE } from '../../calendar/constants'; import { ApiResponse } from '../Api'; import { Nullable, RequireSome } from '../utils'; import { CalendarNotificationSettings } from './Calendar'; import { CalendarKey, CalendarPassphrase } from './CalendarKey'; import { CalendarMember, CalendarMemberInvitation } from './CalendarMember'; import { Attendee, CalendarEvent, CalendarEventData } from './Event'; import { ACCESS_LEVEL } from './Link'; export type CalendarCreateData = { Name: string; Description: string; Color: string; Display: CALENDAR_DISPLAY; URL?: string; }; export enum DELETION_REASON { NORMAL = 0, CHANGE_CALENDAR = 1, } export interface CalendarCreateArguments extends CalendarCreateData { IsImport?: 0 | 1; AddressID: string; } export interface CalendarSetupData { AddressID: string; Signature: string; PrivateKey: string; Passphrase: { DataPacket: string; KeyPacket: string; }; } export interface CalendarSetupResponse extends ApiResponse { Key: CalendarKey; Passphrase: CalendarPassphrase; } export interface CreateOrResetCalendarPayload { AddressID: string; Signature: string; PrivateKey: string; Passphrase: { DataPacket: string; KeyPacket: string; }; } export interface CalendarKeysResetData { [calendarID: string]: CalendarSetupData; } export interface CreateCalendarMemberData { Email: string; PassphraseKeyPacket: string; Permissions: number; } export interface UpdateCalendarMemberData { Permissions: number; PassphraseKeyPacket: string; Name: string; Description: string; Color: string; Display: CALENDAR_DISPLAY; } export interface UpdateCalendarInviteData { Permissions: number; } export enum CalendarEventsQueryType { PartDayInsideWindow = 0, PartDayBeforeWindow = 1, FullDayInsideWindow = 2, FullDayBeforeWindow = 3, } export interface CalendarEventsQuery extends PaginationParams { Start: number; End: number; Timezone: string; Type: CalendarEventsQueryType; MetaDataOnly?: 0 | 1; // default is 0 } export interface CalendarEventsIDsQuery { Limit?: number; AfterID?: string; } export interface CalendarExportEventsQuery extends PaginationParams { BeginID?: string; } export interface GetEventByUIDArguments extends Partial<PaginationParams> { UID: string; RecurrenceID?: number; CalendarType?: CALENDAR_TYPE; } export interface CalendarCreateOrUpdateEventBlobData { CalendarKeyPacket?: string; CalendarEventContent?: Omit<CalendarEventData, 'Author'>[]; SharedKeyPacket?: string; SharedEventContent?: Omit<CalendarEventData, 'Author'>[]; Notifications: Nullable<CalendarNotificationSettings[]>; AttendeesEventContent?: Omit<CalendarEventData, 'Author'>[]; Attendees?: Omit<Attendee, 'UpdateTime' | 'ID'>[]; } export type CalendarCreateEventBlobData = RequireSome< CalendarCreateOrUpdateEventBlobData, 'SharedEventContent' | 'SharedKeyPacket' >; interface CalendarCreateOrUpdateEventMetaData { Permissions: number; IsOrganizer?: 0 | 1; RemovedAttendeeAddresses?: string[]; AddedProtonAttendees?: { Email: string; AddressKeyPacket: string; }[]; } export interface CreateOrUpdateCalendarEventData extends CalendarCreateOrUpdateEventBlobData, CalendarCreateOrUpdateEventMetaData {} export interface CreateSinglePersonalEventData { Notifications: Nullable<CalendarNotificationSettings[]>; } export interface CreateLinkedCalendarEventData extends RequireSome<Partial<CreateOrUpdateCalendarEventData>, 'SharedKeyPacket'> { UID: string; SharedEventID: string; SourceCalendarID?: string; } export interface QueryCalendarAlarms { Start: number; End: number; PageSize: number; } export interface CreateCalendarEventSyncData { Overwrite?: 0 | 1; Event: CreateOrUpdateCalendarEventData; } export interface DeleteCalendarEventSyncData { ID: string; DeletionReason?: DELETION_REASON; } export interface UpdateCalendarEventSyncData { ID: string; Event?: Omit<CreateOrUpdateCalendarEventData, 'SharedKeyPacket' | 'CalendarKeyPacket'>; } export interface CreateLinkedCalendarEventsSyncData { Overwrite?: 0 | 1; Event: CreateLinkedCalendarEventData; } export interface SyncMultipleEventsData { MemberID: string; IsImport?: 0 | 1; Events: ( | CreateCalendarEventSyncData | CreateLinkedCalendarEventsSyncData | DeleteCalendarEventSyncData | UpdateCalendarEventSyncData )[]; } export interface CreatePublicLinks { AccessLevel: ACCESS_LEVEL; CacheKeySalt: string; CacheKeyHash: string; EncryptedPassphrase: Nullable<string>; EncryptedPurpose: Nullable<string>; EncryptedCacheKey: string; PassphraseID: Nullable<string>; } export interface SyncMultipleApiResponses { Index: number; Response: { Code: number; Event?: CalendarEvent; Error?: string; }; } export interface SyncMultipleApiResponse extends ApiResponse { Responses: SyncMultipleApiResponses[]; } export interface UpdateEventPartApiResponse extends ApiResponse { Event: CalendarEvent; } interface GetCanonicalAddressesSingleApiResponse extends ApiResponse { CanonicalEmail: string; } export interface GetCanonicalAddressesApiResponses { Email: string; Response: GetCanonicalAddressesSingleApiResponse; } export interface GetCanonicalAddressesApiResponse extends ApiResponse { Responses: GetCanonicalAddressesApiResponses[]; } export interface GetAllMembersApiResponse { Members: CalendarMember[]; } export interface GetCalendarInvitationsResponse { Invitations: CalendarMemberInvitation[]; }
8,574
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Attendee.ts
import { ATTENDEE_STATUS_API } from '../../calendar/constants'; import { VcalAttendeeProperty, VcalAttendeePropertyParameters } from './VcalModel'; export interface AttendeeClearPartResult { status: ATTENDEE_STATUS_API; token: string; } interface AttendeeParameters extends VcalAttendeePropertyParameters { 'x-pm-token': string; } export interface AttendeePart extends VcalAttendeeProperty { parameters: AttendeeParameters; }
8,575
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Calendar.ts
import { CALENDAR_DISPLAY, CALENDAR_TYPE, NOTIFICATION_TYPE_API, SETTINGS_VIEW } from '../../calendar/constants'; import { Nullable } from '../utils'; import { CalendarKey } from './CalendarKey'; import { CalendarMember, CalendarOwner } from './CalendarMember'; import { NotificationModel } from './Notification'; import { Passphrase } from './Passphrase'; export interface Calendar { ID: string; Type: CALENDAR_TYPE; } export interface CalendarWithOwnMembers extends Calendar { Owner: CalendarOwner; Members: CalendarMember[]; } export interface VisualCalendar extends CalendarWithOwnMembers { Name: string; Description: string; Color: string; Display: CALENDAR_DISPLAY; Email: string; Flags: number; Permissions: number; Priority: number; } export interface CalendarUserSettings { DefaultCalendarID: Nullable<string>; WeekLength: number; DisplayWeekNumber: number; AutoDetectPrimaryTimezone: number; PrimaryTimezone: string; DisplaySecondaryTimezone: number; SecondaryTimezone: Nullable<string>; ViewPreference: SETTINGS_VIEW; InviteLocale: Nullable<string>; AutoImportInvite: number; } export interface CalendarNotificationSettings { Type: NOTIFICATION_TYPE_API; Trigger: string; } export interface CalendarSettings { ID: string; CalendarID: string; DefaultEventDuration: number; DefaultPartDayNotifications: CalendarNotificationSettings[]; DefaultFullDayNotifications: CalendarNotificationSettings[]; } export interface CalendarBootstrap { Keys: CalendarKey[]; Passphrase: Passphrase; Members: CalendarMember[]; CalendarSettings: CalendarSettings; } export interface CalendarAddressOptions { value: string; text: string; } export interface CalendarSelectOption { id: string; name: string; color: string; } export interface CalendarViewModelFull { calendarID: string; name: string; members: CalendarMember[]; display: boolean; description: string; color: string; addressID: string; addressOptions: CalendarAddressOptions[]; duration: number; defaultPartDayNotification: NotificationModel; defaultFullDayNotification: NotificationModel; partDayNotifications: NotificationModel[]; fullDayNotifications: NotificationModel[]; url?: string; type: CALENDAR_TYPE; } export interface CalendarErrors { name?: string; description?: string; } export interface HolidaysDirectoryCalendar { CalendarID: string; Country: string; CountryCode: string; Hidden: boolean; Language: string; LanguageCode: string; Passphrase: string; SessionKey: { Key: string; Algorithm: string; }; Timezones: string[]; }
8,576
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/CalendarKey.ts
import { PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import { CALENDAR_FLAGS } from '@proton/shared/lib/calendar/constants'; import { ApiResponse } from '@proton/shared/lib/interfaces'; export enum CalendarKeyFlags { INACTIVE = 0, ACTIVE = 1, PRIMARY = 2, } export interface CalendarKey { ID: string; CalendarID: string; PrivateKey: string; PassphraseID: string; Flags: CalendarKeyFlags; } interface CalendarMemberPassphrase { MemberID: string; Passphrase: string; Signature: string; } export interface CalendarPassphrase { ID: string; CalendarID: string; Flags: CALENDAR_FLAGS; MemberPassphrases: CalendarMemberPassphrase[]; } export interface DecryptedCalendarKey { Key: CalendarKey; privateKey: PrivateKeyReference; publicKey: PublicKeyReference; } export interface ReenableKeyResponse extends ApiResponse { Key: CalendarKey; }
8,577
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/CalendarMember.ts
import { CALENDAR_DISPLAY } from '../../calendar/constants'; export enum MEMBER_INVITATION_STATUS { PENDING = 0, ACCEPTED = 1, REJECTED = 2, } export interface CalendarOwner { Email: string; } export interface CalendarMember { ID: string; CalendarID: string; AddressID: string; Flags: number; Name: string; Description: string; Email: string; Permissions: number; Color: string; Display: CALENDAR_DISPLAY; Priority: number; } export interface CalendarMemberInvitation { Calendar: { Color: string; Name: string; SenderEmail: string; }; CalendarID: string; CalendarInvitationID: string; CreateTime: number; Email: string; ExpirationTime: number; Passphrase: string; PassphraseID: string; Permissions: number; Status: MEMBER_INVITATION_STATUS; Signature: string; }
8,578
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Date.ts
export interface DateTime { year: number; month: number; day: number; hours: number; minutes: number; seconds: number; milliseconds?: number; }
8,579
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/DateTime.ts
export interface DateTimeValue { year: number; month: number; day: number; hours: number; minutes: number; seconds: number; }
8,580
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Decrypt.ts
import { SessionKey } from '@proton/crypto'; import { EVENT_VERIFICATION_STATUS } from '../../calendar/constants'; import { Address } from '../Address'; import { VcalAttendeeProperty, VcalVeventComponent } from './VcalModel'; export interface SelfAddressData { isOrganizer: boolean; isAttendee: boolean; selfAttendee?: VcalAttendeeProperty; selfAddress?: Address; selfAttendeeIndex?: number; } export interface CalendarEventEncryptionData { encryptingAddressID?: string; sharedSessionKey?: SessionKey; calendarSessionKey?: SessionKey; } export type DecryptedVeventResult = { veventComponent: VcalVeventComponent; hasDefaultNotifications: boolean; verificationStatus: EVENT_VERIFICATION_STATUS; selfAddressData: SelfAddressData; encryptionData: CalendarEventEncryptionData; };
8,581
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Event.ts
import { CalendarNotificationSettings } from '@proton/shared/lib/interfaces/calendar/Calendar'; import { ATTENDEE_STATUS_API, CALENDAR_CARD_TYPE, DAILY_TYPE, END_TYPE, EVENT_VERIFICATION_STATUS, FREQUENCY, ICAL_ATTENDEE_ROLE, ICAL_ATTENDEE_RSVP, ICAL_ATTENDEE_STATUS, ICAL_EVENT_STATUS, MONTHLY_TYPE, SHARED_SIGNED_FIELDS, WEEKLY_TYPE, YEARLY_TYPE, } from '../../calendar/constants'; import { API_CODES } from '../../constants'; import { pick } from '../../helpers/object'; import { Address } from '../Address'; import { Nullable } from '../utils'; import { NotificationModel } from './Notification'; import { VcalRrulePropertyValue, VcalVeventComponent } from './VcalModel'; export interface CalendarEventData { Type: CALENDAR_CARD_TYPE; Data: string; Signature: string | null; Author: string; } export interface CalendarPersonalEventData extends CalendarEventData { MemberID: string; } export interface Attendee { ID: string; Token: string; Status: ATTENDEE_STATUS_API; UpdateTime: Nullable<number>; } export interface CalendarEventBlobData { CalendarKeyPacket: Nullable<string>; CalendarEvents: CalendarEventData[]; SharedKeyPacket: Nullable<string>; AddressKeyPacket: Nullable<string>; AddressID: Nullable<string>; SharedEvents: CalendarEventData[]; Notifications?: Nullable<CalendarNotificationSettings[]>; AttendeesEvents: CalendarEventData[]; Attendees: Attendee[]; } export type CalendarEventBlobDataWithNotifications = Required<CalendarEventBlobData>; export interface CalendarEventSharedData { ID: string; SharedEventID: string; CalendarID: string; CreateTime: number; ModifyTime: number; Permissions: number; IsOrganizer: 1 | 0; IsProtonProtonInvite: 1 | 0; Author: string; } export interface CalendarEventMetadata { StartTime: number; StartTimezone: string; EndTime: number; EndTimezone: string; FullDay: number; RRule: Nullable<string>; UID: string; RecurrenceID: Nullable<number>; Exdates: number[]; } export interface CalendarEvent extends CalendarEventSharedData, CalendarEventBlobData, CalendarEventMetadata {} export interface CalendarEventWithoutBlob extends CalendarEventSharedData, CalendarEventMetadata {} export interface SyncMultipleApiSuccessResponses { Index: number; Response: { Code: API_CODES.SINGLE_SUCCESS; Event: CalendarEvent; }; } export interface FrequencyModel { type: FREQUENCY; frequency: FREQUENCY; interval?: number; daily: { type: DAILY_TYPE; }; weekly: { type: WEEKLY_TYPE; days: number[]; }; monthly: { type: MONTHLY_TYPE; }; yearly: { type: YEARLY_TYPE; }; ends: { type: END_TYPE; count?: number; until?: Date; }; vcalRruleValue?: VcalRrulePropertyValue; } export interface DateTimeModel { date: Date; time: Date; tzid: string; } export interface OrganizerModel { email: string; cn: string; } export interface AttendeeModel { email: string; cn: string; rsvp: ICAL_ATTENDEE_RSVP; role: ICAL_ATTENDEE_ROLE; partstat: ICAL_ATTENDEE_STATUS; token?: string; } export interface CalendarViewModel { id: string; color: string; permissions: number; isSubscribed: boolean; isOwned: boolean; isWritable: boolean; isUnknown: boolean; } export interface CalendarsModel { text: string; value: string; color: string; permissions: number; isSubscribed: boolean; isOwned: boolean; isWritable: boolean; isUnknown: boolean; } export interface EventModelView { uid?: string; frequencyModel: FrequencyModel; title: string; location: string; description: string; sequence?: number; start: DateTimeModel; end: DateTimeModel; attendees: AttendeeModel[]; organizer?: OrganizerModel; isOrganizer: boolean; // this property only takes into account the event ICS content. It does not care if the event is in a shared or subscribed calendar isAttendee: boolean; // this property only takes into account the event ICS content. It does not care if the event is in a shared or subscribed calendar isProtonProtonInvite: boolean; hasDefaultNotifications: boolean; selfAttendeeIndex?: number; selfAddress?: Address; status: ICAL_EVENT_STATUS; verificationStatus: EVENT_VERIFICATION_STATUS; rest?: any; } export interface EventModel extends EventModelView { // these types will be used in the future, for now only event is used type: 'event' | 'alarm' | 'task'; calendar: CalendarViewModel; calendars: CalendarsModel[]; member: { memberID: string; addressID: string; }; isAllDay: boolean; defaultPartDayNotification: NotificationModel; defaultFullDayNotification: NotificationModel; fullDayNotifications: NotificationModel[]; partDayNotifications: NotificationModel[]; initialDate: Date; initialTzid: string; defaultEventDuration: number; hasTouchedRrule: boolean; hasPartDayDefaultNotifications: boolean; hasFullDayDefaultNotifications: boolean; } export interface EventModelErrors { title?: string; end?: string; interval?: string; until?: string; count?: string; notifications?: { fields: number[]; text: string; }; participantError?: boolean; } export interface EventModelReadView extends EventModelView { notifications?: NotificationModel[]; isAllDay: boolean; } const sharedPick = (x: VcalVeventComponent) => pick(x, [...SHARED_SIGNED_FIELDS, 'component']); export type SharedVcalVeventComponent = ReturnType<typeof sharedPick>;
8,582
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/EventManager.ts
import { EVENT_ACTIONS } from '../../constants'; import { Calendar, CalendarAlarm, CalendarEventWithoutBlob, CalendarMember, CalendarSubscription, CalendarUrl, CalendarWithOwnMembers, } from './index'; export interface CalendarAlarmEventManagerDelete { ID: string; Action: EVENT_ACTIONS.DELETE; } export interface CalendarAlarmEventManagerUpdate { ID: string; Action: EVENT_ACTIONS.UPDATE; Alarm: CalendarAlarm; } export interface CalendarAlarmEventManagerCreate { ID: string; Action: EVENT_ACTIONS.CREATE; Alarm: CalendarAlarm; } export type CalendarAlarmEventManager = | CalendarAlarmEventManagerDelete | CalendarAlarmEventManagerUpdate | CalendarAlarmEventManagerCreate; export interface CalendarUrlEventManagerDelete { ID: string; Action: EVENT_ACTIONS.DELETE; } export interface CalendarUrlEventManagerUpdate { ID: string; Action: EVENT_ACTIONS.UPDATE; CalendarUrl: CalendarUrl; } export interface CalendarUrlEventManagerCreate { ID: string; Action: EVENT_ACTIONS.CREATE; CalendarUrl: CalendarUrl; } export type CalendarUrlEventManager = | CalendarUrlEventManagerDelete | CalendarUrlEventManagerUpdate | CalendarUrlEventManagerCreate; export interface CalendarSubscriptionEventManagerDelete { ID: string; Action: EVENT_ACTIONS.DELETE; } export interface CalendarSubscriptionEventManagerUpdate { ID: string; Action: EVENT_ACTIONS.UPDATE; CalendarSubscription: CalendarSubscription; } export interface CalendarSubscriptionEventManagerCreate { ID: string; Action: EVENT_ACTIONS.CREATE; CalendarSubscription: CalendarSubscription; } export type CalendarSubscriptionEventManager = | CalendarSubscriptionEventManagerDelete | CalendarSubscriptionEventManagerUpdate | CalendarSubscriptionEventManagerCreate; export interface CalendarMemberEventManagerDelete { ID: string; Action: EVENT_ACTIONS.DELETE; } export interface CalendarMemberEventManagerUpdate { ID: string; Action: EVENT_ACTIONS.UPDATE; Member: CalendarMember; } export interface CalendarMemberEventManagerCreate { ID: string; Action: EVENT_ACTIONS.CREATE; Member: CalendarMember; } export type CalendarMemberEventManager = | CalendarMemberEventManagerDelete | CalendarMemberEventManagerUpdate | CalendarMemberEventManagerCreate; export interface CalendarEventManagerDelete { ID: string; Action: EVENT_ACTIONS.DELETE; } export interface CalendarEventManagerUpdate { ID: string; Action: EVENT_ACTIONS.UPDATE; Calendar: Calendar; } export interface CalendarEventManagerCreate { ID: string; Action: EVENT_ACTIONS.CREATE; Calendar: CalendarWithOwnMembers; } export interface CalendarEventsEventManagerDelete { ID: string; Action: EVENT_ACTIONS.DELETE; } export interface CalendarEventsEventManagerUpdate { ID: string; Action: EVENT_ACTIONS.UPDATE; Event: CalendarEventWithoutBlob; } export interface CalendarEventsEventManagerCreate { ID: string; Action: EVENT_ACTIONS.CREATE; Event: CalendarEventWithoutBlob; } export type CalendarEventsEventManager = | CalendarEventsEventManagerDelete | CalendarEventsEventManagerUpdate | CalendarEventsEventManagerCreate; export type CalendarEventManager = CalendarEventManagerCreate | CalendarEventManagerUpdate | CalendarEventManagerDelete;
8,583
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Export.ts
import { WeekStartsOn } from '../../date-fns-utc/interface'; import { VisualCalendar } from './Calendar'; export enum EXPORT_STEPS { EXPORTING, FINISHED, } export enum EXPORT_ERRORS { NETWORK_ERROR, } export enum EXPORT_EVENT_ERROR_TYPES { DECRYPTION_ERROR, PASSWORD_RESET, } export type ExportError = [string, EXPORT_EVENT_ERROR_TYPES]; export interface ExportCalendarModel { step: EXPORT_STEPS; totalFetched: number; totalProcessed: number; totalToProcess: number; calendar: VisualCalendar; exportErrors: ExportError[]; error?: EXPORT_ERRORS; weekStartsOn: WeekStartsOn; }
8,584
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Import.ts
import { ICAL_METHOD } from '../../calendar/constants'; import { ImportEventError } from '../../calendar/icsSurgery/ImportEventError'; import { ImportFatalError } from '../../calendar/import/ImportFatalError'; import { ImportFileError } from '../../calendar/import/ImportFileError'; import { CalendarCreateEventBlobData } from './Api'; import { VisualCalendar } from './Calendar'; import { SyncMultipleApiSuccessResponses } from './Event'; import { VcalVeventComponent } from './VcalModel'; export enum IMPORT_STEPS { ATTACHING, ATTACHED, WARNING_IMPORT_INVITATION, WARNING_PARTIAL_IMPORT, IMPORTING, FINISHED, } export interface ImportCalendarModel { step: IMPORT_STEPS; fileAttached?: File; method?: ICAL_METHOD; eventsParsed: VcalVeventComponent[]; totalEncrypted: number; totalImported: number; visibleErrors: ImportEventError[]; hiddenErrors: ImportEventError[]; failure?: ImportFatalError | ImportFileError | Error; calendar: VisualCalendar; loading: boolean; } export interface EncryptedEvent { component: VcalVeventComponent; data: CalendarCreateEventBlobData; } export interface ImportedEvent extends EncryptedEvent { response: SyncMultipleApiSuccessResponses; }
8,585
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Invite.ts
import { Nullable } from '@proton/shared/lib/interfaces'; import { ICAL_ATTENDEE_ROLE, ICAL_ATTENDEE_STATUS } from '../../calendar/constants'; import { DecryptedKey } from '../Key'; import { CalendarSettings, VisualCalendar } from './Calendar'; import { DecryptedCalendarKey } from './CalendarKey'; import { CalendarEvent } from './Event'; import { VcalAttendeeProperty, VcalOrganizerProperty, VcalVeventComponent } from './VcalModel'; export interface PartstatActions { accept: () => Promise<void>; acceptTentatively: () => Promise<void>; decline: () => Promise<void>; retryCreateEvent: ({ partstat, isProtonInvite, }: { partstat: ICAL_ATTENDEE_STATUS; isProtonInvite: boolean; }) => Promise<void>; retryUpdateEvent: ({ partstat, timestamp, isProtonInvite, calendarEvent, }: { partstat: ICAL_ATTENDEE_STATUS; timestamp: number; isProtonInvite: boolean; calendarEvent?: CalendarEvent; }) => Promise<void>; } export interface CalendarWidgetData { calendar: VisualCalendar; isCalendarDisabled: boolean; calendarNeedsUserAction: boolean; memberID?: string; addressID?: string; addressKeys?: DecryptedKey[]; calendarKeys?: DecryptedCalendarKey[]; calendarSettings?: CalendarSettings; } export interface PmInviteData { isProtonReply?: boolean; sharedEventID?: string; sharedSessionKey?: string; } export interface Participant { vcalComponent: VcalAttendeeProperty | VcalOrganizerProperty; name: string; emailAddress: string; displayName: string; displayEmail: string; partstat?: ICAL_ATTENDEE_STATUS; role?: ICAL_ATTENDEE_ROLE; addressID?: string; attendeeIndex?: number; token?: string; updateTime?: Nullable<number>; attendeeID?: string; } export interface SavedImportData { savedEvent: CalendarEvent; savedVevent: VcalVeventComponent; } export interface SavedInviteData extends SavedImportData { savedVcalAttendee: VcalAttendeeProperty; }
8,586
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Link.ts
import { Nullable } from '../utils'; import { Calendar } from './Calendar'; export enum ACCESS_LEVEL { LIMITED = 0, FULL = 1, } export interface CalendarUrl { CalendarUrlID: string; CalendarID: string; PassphraseID?: string; AccessLevel: ACCESS_LEVEL; EncryptedPurpose: Nullable<string>; EncryptedCacheKey: string; EncryptedPassphrase: Nullable<string>; CreateTime: number; } export interface CalendarUrlResponse { CalendarUrl: CalendarUrl; Code: number; } export interface CalendarUrlsResponse { CalendarUrls: CalendarUrl[]; Code: number; } export interface CalendarMap { [key: string]: Calendar; } export interface CalendarLink extends Omit<CalendarUrl, 'PassphraseID'> { purpose: Nullable<string>; link: string; } export interface CopyLinkParams { calendarID: string; urlID: string; accessLevel: ACCESS_LEVEL; encryptedPassphrase: Nullable<string>; encryptedCacheKey: string; }
8,587
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Notification.ts
import { NOTIFICATION_TYPE_API, NOTIFICATION_UNITS, NOTIFICATION_WHEN } from '../../calendar/constants'; export interface NotificationModel { id: string; unit: NOTIFICATION_UNITS; type: NOTIFICATION_TYPE_API; when: NOTIFICATION_WHEN; value?: number; at?: Date; isAllDay: boolean; }
8,588
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/PartResult.ts
export interface EncryptPartResult { dataPacket: Uint8Array; signature: string; } export interface SignPartResult { data: string; signature: string; }
8,589
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Passphrase.ts
export interface MemberPassphrase { MemberID: string; Passphrase: string; Signature: string; } export interface Invitation { CalendarID: string; PassphraseID: string; InvitationID: string; Status: number; CreateTime: number; ExpirationTime: number; Permissions: number; Email: string; } export interface Passphrase { ID: string; Flags: number; MemberPassphrases: MemberPassphrase[]; Invitations: Invitation[]; }
8,590
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/Subscription.ts
import { VisualCalendar } from './Calendar'; export enum CALENDAR_SUBSCRIPTION_STATUS { OK = 0, ERROR = 1, INVALID_ICS = 2, CALENDAR_SOFT_DELETED = 3, CALENDAR_NOT_FOUND = 4, USER_NOT_EXIST = 5, ICS_SIZE_EXCEED_LIMIT = 6, SYNCHRONIZING = 7, CALENDAR_MISSING_PRIMARY_KEY = 8, HTTP_REQUEST_FAILED_GENERIC = 20, HTTP_REQUEST_FAILED_BAD_REQUEST = 21, HTTP_REQUEST_FAILED_UNAUTHORIZED = 22, HTTP_REQUEST_FAILED_FORBIDDEN = 23, HTTP_REQUEST_FAILED_NOT_FOUND = 24, HTTP_REQUEST_FAILED_INTERNAL_SERVER_ERROR = 25, HTTP_REQUEST_FAILED_TIMEOUT = 26, INTERNAL_CALENDAR_URL_NOT_FOUND = 27, INTERNAL_CALENDAR_UNDECRYPTABLE = 28, INVALID_URL = 30, } export interface CalendarSubscription { CalendarID: string; CreateTime: number; LastUpdateTime: number; Status: CALENDAR_SUBSCRIPTION_STATUS; URL: string; } export interface SubscribedCalendar extends VisualCalendar { SubscriptionParameters: CalendarSubscription; } export interface CalendarSubscriptionResponse { CalendarSubscription: CalendarSubscription; Code: number; }
8,591
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/VcalModel.ts
import { ICAL_ATTENDEE_ROLE, ICAL_ATTENDEE_RSVP, ICAL_ATTENDEE_STATUS, ICAL_EVENT_STATUS, } from '../../calendar/constants'; export enum VcalDays { SU, MO, TU, WE, TH, FR, SA, } export type VcalDaysKeys = keyof typeof VcalDays; export interface VcalDateValue { year: number; month: number; day: number; } export interface VcalDateTimeValue { year: number; month: number; day: number; hours: number; minutes: number; seconds: number; isUTC: boolean; } export type VcalDateOrDateTimeValue = VcalDateValue | VcalDateTimeValue; export interface VcalDateTimeProperty { parameters?: { type?: 'date-time'; tzid?: string; }; value: VcalDateTimeValue; } export interface VcalDateProperty { parameters: { type: 'date'; }; value: VcalDateValue; } export interface VcalFloatingDateTimeProperty { parameters?: { type?: 'date-time'; }; value: VcalDateTimeValue; } export interface IcalJSDateOrDateTimeProperty { parameters?: { type?: 'date' | 'date-time'; tzid?: string; }; value: VcalDateValue | VcalDateTimeValue; } export type VcalDateOrDateTimeProperty = VcalDateProperty | VcalDateTimeProperty; export type VcalRruleFreqValue = 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'YEARLY' | undefined | string; export interface VcalRrulePropertyValue { freq: VcalRruleFreqValue; count?: number; interval?: number; until?: VcalDateOrDateTimeValue; bysetpos?: number | number[]; byday?: string | string[]; bymonthday?: number | number[]; bymonth?: number | number[]; bysecond?: number | number[]; byminute?: number | number[]; byhour?: number | number[]; byyearday?: number | number[]; byweekno?: number | number[]; wkst?: VcalDaysKeys; } export interface VcalRruleProperty { value: VcalRrulePropertyValue; } export interface VcalDurationValue { weeks: number; days: number; hours: number; minutes: number; seconds: number; isNegative: boolean; } export interface VcalTriggerRelativeProperty { value: VcalDurationValue; parameters?: { type?: 'duration'; related?: string; }; } export type VcalTriggerProperty = VcalTriggerRelativeProperty | VcalDateTimeProperty; export interface VcalUidProperty { value: string; } export interface VcalStringProperty { value: string; } export interface VcalNumberProperty { value: number; } export interface VcalBooleanProperty { value: 'true' | 'false'; parameters: { type: 'boolean' }; } export interface VcalStringArrayProperty { value: string[]; } export interface VcalNumberArrayProperty { value: number[]; } interface VcalDurationProperty { value: VcalDurationValue; } interface VcalURIProperty { value: string; params: { type: 'uri' }; } interface VcalBinaryProperty { value: string; params: { type: 'binary'; encoding: 'base64'; }; } type VcalImageProperty = VcalURIProperty | VcalBinaryProperty; export interface VcalValarmComponent<T = VcalTriggerProperty> { component: 'valarm'; action: VcalStringProperty; trigger: T; duration?: VcalDurationProperty; repeat?: VcalStringProperty; description?: VcalStringProperty; summary?: VcalStringProperty; attendee?: VcalAttendeeProperty[]; attach?: VcalStringProperty; } export type VcalValarmRelativeComponent = VcalValarmComponent<VcalTriggerRelativeProperty>; export type VcalValarmAbsoluteComponent = VcalValarmComponent<VcalDateTimeProperty>; export interface VcalStringWithParamsProperty { value: string; params?: { [key: string]: string }; } export interface VcalOrganizerPropertyParameters { cn?: string; dir?: string; language?: string; 'sent-by'?: string; email?: string; } export interface VcalOrganizerProperty { value: string; parameters?: VcalOrganizerPropertyParameters; } export interface VcalStatusProperty { value: ICAL_EVENT_STATUS | string; } export interface VcalDescriptionPropertyParameters { language?: string; altrep?: string; } export interface VcalDescriptionProperty { value: string; parameters?: VcalDescriptionPropertyParameters; } export interface VcalAttendeePropertyParameters extends VcalOrganizerPropertyParameters { cn?: string; cutype?: string; member?: string; role?: ICAL_ATTENDEE_ROLE | string; partstat?: ICAL_ATTENDEE_STATUS | string; rsvp?: ICAL_ATTENDEE_RSVP | string; 'delegated-from'?: string; 'delegated-to'?: string; 'x-pm-token'?: string; } export interface VcalAttendeeProperty { value: string; parameters?: VcalAttendeePropertyParameters; } export interface VcalAttendeePropertyWithCn extends VcalAttendeeProperty { parameters: VcalAttendeePropertyParameters & Required<Pick<VcalAttendeePropertyParameters, 'cn'>>; } export interface VcalAttendeePropertyWithPartstat extends VcalAttendeeProperty { parameters: VcalAttendeePropertyParameters & Required<Pick<VcalAttendeePropertyParameters, 'partstat'>>; } export interface VcalAttendeePropertyWithRole extends VcalAttendeeProperty { parameters: VcalAttendeePropertyParameters & Required<Pick<VcalAttendeePropertyParameters, 'role'>>; } export interface VcalAttendeePropertyWithToken extends VcalAttendeeProperty { parameters: VcalAttendeePropertyParameters & Required<Pick<VcalAttendeePropertyParameters, 'x-pm-token'>>; } export type VcalPmAttendee = VcalAttendeePropertyWithCn & VcalAttendeePropertyWithToken; export interface VcalCategoryProperty { value: string[]; } export interface VcalVeventComponent { component: 'vevent'; components?: VcalValarmComponent[]; // Not complete. Can be other components. uid: VcalUidProperty; dtstamp: VcalDateTimeProperty; dtstart: VcalDateOrDateTimeProperty; dtend?: VcalDateOrDateTimeProperty; rrule?: VcalRruleProperty; 'recurrence-id'?: VcalDateOrDateTimeProperty; exdate?: VcalDateOrDateTimeProperty[]; organizer?: VcalOrganizerProperty; attendee?: VcalAttendeeProperty[]; description?: VcalDescriptionProperty; summary?: VcalStringProperty; duration?: VcalDurationProperty; location?: VcalDescriptionProperty; geo?: VcalNumberArrayProperty; class?: VcalStringProperty; priority?: VcalNumberProperty; sequence?: VcalNumberProperty; status?: VcalStatusProperty; created?: VcalDateTimeProperty; 'last-modified'?: VcalDateTimeProperty; transp?: VcalStringProperty; url?: VcalStringProperty; attach?: VcalStringWithParamsProperty[]; categories?: VcalCategoryProperty[]; comment?: VcalStringWithParamsProperty[]; contact?: VcalStringWithParamsProperty[]; 'request-status'?: VcalStringArrayProperty[]; 'related-to'?: VcalStringWithParamsProperty[]; resources?: VcalStringWithParamsProperty[]; rdate?: VcalDateTimeProperty[]; 'x-pm-proton-reply'?: VcalBooleanProperty; 'x-pm-session-key'?: VcalStringProperty; 'x-pm-shared-event-id'?: VcalStringProperty; 'x-yahoo-yid'?: VcalStringProperty; 'x-yahoo-user-status'?: VcalStringProperty; } export type VcalComponentKeys = keyof VcalVeventComponent; export interface VcalPmVeventComponent extends Omit<VcalVeventComponent, 'attendee'> { attendee?: VcalAttendeePropertyWithToken[]; } export interface VcalVtodoComponent { component: 'vtodo'; components?: VcalValarmComponent[]; // Not complete. Can be other components. uid: VcalUidProperty; } export interface VcalVjournalComponent { component: 'vjournal'; components?: VcalValarmComponent[]; // Not complete. Can be other components. uid: VcalUidProperty; } export interface VcalFreeBusyStartEndValue { start: VcalDateTimeValue; end: VcalDateTimeValue; } export interface VcalFreeBusyStartDurationValue { start: VcalDateTimeValue; duration: VcalDurationValue; } type VcalFreeBusyValue = VcalFreeBusyStartEndValue | VcalFreeBusyStartDurationValue; export interface VcalFreeBusyProperty { value: VcalFreeBusyValue[]; } export interface VcalVfreebusyComponent { component: 'vfreebusy'; components?: VcalValarmComponent[]; // Not complete. Can be other components. uid: VcalUidProperty; dtstamp: VcalDateTimeProperty; dtstart?: VcalDateOrDateTimeProperty; dtend?: VcalDateOrDateTimeProperty; organizer?: VcalOrganizerProperty; attendee?: VcalAttendeeProperty[]; freebusy?: VcalFreeBusyProperty[]; url?: VcalStringProperty; comment?: VcalStringProperty[]; } export interface VcalVtimezoneComponent { component: 'vtimezone'; tzid: VcalStringProperty; } export interface VcalXOrIanaComponent { component: string; } export type VcalCalendarComponent = | VcalVeventComponent | VcalVtodoComponent | VcalVjournalComponent | VcalVfreebusyComponent | VcalVtimezoneComponent | VcalXOrIanaComponent | VcalVcalendar; export interface VcalErrorComponent { error: Error; icalComponent: any; } export interface VcalVcalendar { component: string; components?: ( | VcalVeventComponent | VcalVtodoComponent | VcalVjournalComponent | VcalVfreebusyComponent | VcalVtimezoneComponent | VcalXOrIanaComponent )[]; prodid: VcalStringProperty; version: VcalStringProperty; calscale?: VcalStringProperty; method?: VcalStringProperty; 'x-wr-timezone'?: VcalStringProperty; 'x-wr-calname'?: VcalStringProperty; // RFC 7986 name?: VcalStringProperty; description?: VcalStringProperty; uid?: VcalStringProperty; url?: VcalStringProperty; 'last-modified'?: VcalDateTimeProperty; categories?: VcalStringWithParamsProperty[]; 'refresh-interval'?: VcalDurationProperty; source?: VcalURIProperty; color?: VcalStringProperty; image?: VcalImageProperty; conference?: VcalURIProperty; } export interface VcalVeventComponentWithMaybeErrors extends Omit<VcalVeventComponent, 'components'> { components?: (VcalErrorComponent | VcalValarmComponent)[]; } export interface VcalVtodoComponentWithMaybeErrors extends Omit<VcalVtodoComponent, 'components'> { components?: (VcalErrorComponent | VcalValarmComponent)[]; } export interface VcalVjournalComponentWithMaybeErrors extends Omit<VcalVjournalComponent, 'components'> { components?: (VcalErrorComponent | VcalValarmComponent)[]; } export interface VcalVfreebusyComponentWithMaybeErrors extends Omit<VcalVfreebusyComponent, 'components'> { components?: (VcalErrorComponent | VcalValarmComponent)[]; } export type VcalCalendarComponentWithMaybeErrors = | VcalVeventComponentWithMaybeErrors | VcalVtodoComponentWithMaybeErrors | VcalVjournalComponentWithMaybeErrors | VcalVfreebusyComponentWithMaybeErrors | VcalVtimezoneComponent | VcalXOrIanaComponent; export interface VcalVcalendarWithMaybeErrors extends Omit<VcalVcalendar, 'components'> { components?: (VcalCalendarComponentWithMaybeErrors | VcalErrorComponent)[]; }
8,592
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/calendar/index.ts
export * from './Alarm'; export * from './Attendee'; export * from './Calendar'; export * from './CalendarKey'; export * from './Date'; export * from './DateTime'; export * from './Decrypt'; export * from './Event'; export * from './Export'; export * from './Import'; export * from './Invite'; export * from './CalendarMember'; export * from './Notification'; export * from './PartResult'; export * from './Passphrase'; export * from './Link'; export * from './Subscription'; export * from './VcalModel'; export * from './Api';
8,593
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/contacts/Contact.ts
import { PublicKeyReference } from '@proton/crypto'; import { CONTACT_CARD_TYPE } from '../../constants'; export interface ContactEmail { ID: string; Email: string; Name: string; Type: string[]; Defaults: number; Order: number; ContactID: string; LabelIDs: string[]; LastUsedTime: number; } export interface ContactCard { Type: CONTACT_CARD_TYPE; Data: string; Signature: string | null; } export interface ContactMetadata { ID: string; Name: string; UID: string; Size: number; CreateTime: number; ModifyTime: number; ContactEmails: ContactEmail[]; LabelIDs: string[]; } export interface Contact extends ContactMetadata { Cards: ContactCard[]; } export interface ContactFormatted extends Contact { emails: string[]; } export interface ContactWithBePinnedPublicKey { contactID?: string; emailAddress: string; name?: string; isInternal: boolean; bePinnedPublicKey: PublicKeyReference; } export interface ContactGroup { ID: string; Name: string; Color: string; Path: string; Display: number; Exclusive: number; Notify: number; Order: number; Type: number; } export type ContactValue = string | (string | string[])[]; export type ContactEmailModel = Pick<ContactEmail, 'Email' | 'ContactID' | 'LabelIDs' | 'Name'> & { uid: string; changes: { [groupID: string]: boolean }; }; export interface ContactMergeModel { orderedContacts: ContactFormatted[][]; isChecked: { [ID: string]: boolean; }; beDeleted: { [ID: string]: boolean; }; }
8,594
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/contacts/ContactApi.ts
import { ContactMetadata } from './Contact'; export interface AddContactsApiResponse { Index: number; Response: { Code: number; Contact?: ContactMetadata; Error?: string; }; } export interface AddContactsApiResponses { Code: number; Responses: AddContactsApiResponse[]; } export interface UpdateContactApiResponse { Code: number; Contact?: ContactMetadata; }
8,595
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/contacts/FormattedContact.ts
import { Contact } from './Contact'; export interface FormattedContact extends Contact { emails: string[]; }
8,596
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/contacts/GroupsWithCount.ts
import { ContactGroup } from './Contact'; export interface GroupsWithCount extends ContactGroup { count: number; }
8,597
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/contacts/Import.ts
import { ImportContactError } from '../../contacts/errors/ImportContactError'; import { ImportFatalError } from '../../contacts/errors/ImportFatalError'; import { ImportFileError } from '../../contacts/errors/ImportFileError'; import { ContactCard, ContactGroup, ContactValue } from './Contact'; import { VCardContact, VCardKey } from './VCard'; export enum IMPORT_STEPS { ATTACHING, ATTACHED, IMPORT_CSV, WARNING, IMPORTING, SUMMARY, IMPORT_GROUPS, } export enum IMPORT_GROUPS_ACTION { MERGE, CREATE, IGNORE, } export enum EXTENSION { CSV = 'csv', VCF = 'vcf', } export type ACCEPTED_EXTENSIONS = EXTENSION.CSV | EXTENSION.VCF; export interface ParsedCsvContacts { headers: string[]; contacts: string[][]; } export interface ImportCategories { name: string; totalContacts: number; contactIDs: string[]; contactEmailIDs: string[]; action: IMPORT_GROUPS_ACTION; targetGroup: ContactGroup; targetName: string; error?: string; } export interface ImportContactsModel { step: IMPORT_STEPS; fileAttached?: File; extension?: ACCEPTED_EXTENSIONS; preVcardsContacts?: PreVcardsContact[]; parsedVcardContacts: VCardContact[]; importedContacts: ImportedContact[]; totalEncrypted: number; totalImported: number; errors: ImportContactError[]; failure?: ImportFatalError | ImportFileError | Error; loading: boolean; contactGroups?: ContactGroup[]; categories: ImportCategories[]; } export interface SimpleEncryptedContact { contact: { Cards: ContactCard[]; error?: Error }; contactId: string; } export interface EncryptedContact extends SimpleEncryptedContact { contactEmails: { email: string; group?: string }[]; categories: { name: string; group?: string }[]; } export interface ImportedContact { contactID: string; contactEmailIDs: string[]; categories: { name: string; contactEmailIDs?: string[] }[]; } export interface Combine { [key: string]: (preVcards: PreVcardsProperty) => any; } export interface Display { [key: string]: (preVcards: PreVcardsProperty) => string; } export interface PreVcardProperty { header: string; checked: boolean; pref?: number; field: string; type?: VCardKey; value: ContactValue; combineInto?: string; combineIndex?: number; custom?: boolean; } export type PreVcardsProperty = PreVcardProperty[]; export type PreVcardsContact = PreVcardsProperty[];
8,598
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces
petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/contacts/MergeModel.ts
import { FormattedContact } from './FormattedContact'; export interface MergeModel { orderedContacts: FormattedContact[][]; isChecked: { [ID: string]: boolean; }; beDeleted: { [ID: string]: boolean; }; }
8,599