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/mail
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/send/helpers.ts
import mimemessage from '@protontech/mimemessage'; import { encodeUtf8 } from '@proton/crypto/lib/utils'; import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants'; import { AttachmentDirect } from '../../interfaces/mail/crypto'; /** * Remove '; name=' and '; filename=' values */ export const extractContentValue = (value = '') => { const semicolonIndex = value.indexOf(';'); if (semicolonIndex === -1) { return value; } return value.substr(0, semicolonIndex); }; const buildAttachment = (attachmentData: { attachment: AttachmentDirect; data: string }) => { const { attachment, data } = attachmentData; const attachmentName = JSON.stringify(attachment.Filename); const headers = attachment.Headers || {}; const contentTypeValue = extractContentValue(headers['content-type']) || attachment.MIMEType || 'application/octet-stream'; const contentDispositionValue = extractContentValue(headers['content-disposition']) || ATTACHMENT_DISPOSITION.ATTACHMENT; const entity = mimemessage.factory({ contentType: `${contentTypeValue}; filename=${attachmentName}; name=${attachmentName}`, contentTransferEncoding: 'base64', // the mimemessage library requires a particular transformation of the string `data` into a binary string // to produce the right body when data contains non Latin1 characters body: encodeUtf8(data), }); entity.header( 'content-disposition', `${contentDispositionValue}; filename=${attachmentName}; name=${attachmentName}` ); if (headers['content-id']) { entity.header('content-id', headers['content-id']); } return entity; }; /** * Quoted printable for compatibility with old clients * Mimemessagefactory doesn't handle the empty string well. */ const buildPlaintextEntity = (plaintext?: string) => { const entity = mimemessage.factory({ body: plaintext, contentTransferEncoding: 'quoted-printable', }); if (!plaintext) { // the mimemessage library is buggy in this case and converts an empty string into 'null' entity.internalBody = ''; } return entity; }; export const constructMime = ( plaintext: string, attachmentData: { attachment: AttachmentDirect; data: string } ): string => { const bodyEntity = buildPlaintextEntity(plaintext); const attachmentEntities = buildAttachment(attachmentData); const body = [bodyEntity].concat(attachmentEntities); const msgentity = mimemessage.factory({ contentType: 'multipart/mixed', body, }); // this trailing line space is important: if it's not there Outlook adds it and breaks pgp/mime signatures. return `${msgentity.toString()}\r\n`; };
8,700
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/send/sendEncrypt.ts
/** * Currently this is basically a copy of sendEncrypt from the mail repo. TO BE IMPROVED */ import { CryptoProxy, PrivateKeyReference, PublicKeyReference, SessionKey } from '@proton/crypto'; import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import isTruthy from '@proton/utils/isTruthy'; import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays'; import { AES256, MIME_TYPES } from '../../constants'; import { hasBit } from '../../helpers/bitset'; import { uint8ArrayToBase64String } from '../../helpers/encoding'; import { Attachment, Message } from '../../interfaces/mail/Message'; import { PackageDirect } from '../../interfaces/mail/crypto'; import { RequireOnly, SimpleMap } from '../../interfaces/utils'; import { getSessionKey } from './attachments'; interface AttachmentKeys { Attachment: Attachment; SessionKey: SessionKey; } const { SEND_CLEAR, SEND_CLEAR_MIME } = PACKAGE_TYPE; const packToBase64 = ({ data, algorithm: Algorithm = AES256 }: SessionKey) => { return { Key: uint8ArrayToBase64String(data), Algorithm }; }; const encryptKeyPacket = async ({ sessionKeys = [], publicKeys = [], passwords = [], }: { sessionKeys?: SessionKey[]; publicKeys?: PublicKeyReference[]; passwords?: string[]; }) => Promise.all( sessionKeys.map(async (sessionKey) => { const encryptedSessionKey = await CryptoProxy.encryptSessionKey({ data: sessionKey.data, algorithm: sessionKey.algorithm, encryptionKeys: publicKeys, passwords, format: 'binary', }); return uint8ArrayToBase64String(encryptedSessionKey); }) ); /** * Encrypt the attachment session keys and add them to the package */ const encryptAttachmentKeys = async ({ pack, attachmentKeys, }: { pack: PackageDirect; attachmentKeys: AttachmentKeys[]; }) => { // multipart/mixed bodies already include the attachments so we don't add them here if (pack.MIMEType === MIME_TYPES.MIME) { return; } const promises = Object.values(pack.Addresses || {}).map(async (address) => { if (!address?.PublicKey) { return; } const keys = await encryptKeyPacket({ sessionKeys: attachmentKeys.map(({ SessionKey }) => SessionKey), publicKeys: [address.PublicKey], }); address.AttachmentKeyPackets = keys; }); if (hasBit(pack.Type, PACKAGE_TYPE.SEND_CLEAR)) { const AttachmentKeys: { Key: string; Algorithm: string }[] = []; attachmentKeys.forEach(({ SessionKey }) => { AttachmentKeys.push(packToBase64(SessionKey)); }); pack.AttachmentKeys = AttachmentKeys; } return Promise.all(promises); }; /** * Generate random session key in the format openpgp creates them */ const generateSessionKeyHelper = async (): Promise<SessionKey> => ({ algorithm: AES256, data: await CryptoProxy.generateSessionKeyForAlgorithm(AES256), }); /** * Encrypts the draft body. This is done separately from the other bodies so we can make sure that the send body * (the encrypted body in the message object) is the same as the other emails so we can use 1 blob for them in the api * (i.e. deduplication) */ const encryptDraftBodyPackage = async ({ body, publicKeys, privateKeys, publicKeysList = [], }: { body?: string; privateKeys: PrivateKeyReference[]; publicKeys: PublicKeyReference[]; publicKeysList?: (PublicKeyReference | undefined)[]; }) => { const cleanPublicKeys = [...publicKeys, ...publicKeysList].filter(isTruthy); // pass all public keys to make sure the generated session key is compatible with them all const sessionKey = await CryptoProxy.generateSessionKey({ recipientKeys: cleanPublicKeys }); // we encrypt using `sessionKey` directly instead of `encryptionKeys` so that returned message only includes // symmetrically encrypted data const { message: encryptedData } = await CryptoProxy.encryptMessage({ textData: body || '', stripTrailingSpaces: true, sessionKey, signingKeys: privateKeys, format: 'binary', }); // Encrypt to each public key separetely to get separate serialized session keys. const encryptedSessionKeys = await Promise.all( cleanPublicKeys.map((publicKey) => CryptoProxy.encryptSessionKey({ ...sessionKey, encryptionKeys: publicKey, format: 'binary', }) ) ); // combine message const value = mergeUint8Arrays([...encryptedSessionKeys.slice(0, publicKeys.length), encryptedData]); // _.flowRight(mergeUint8Arrays, _.flatten, _.values)(packets); const armoredBody = await CryptoProxy.getArmoredMessage({ binaryMessage: value }); return { keys: encryptedSessionKeys.slice(publicKeys.length), encrypted: encryptedData, sessionKey, armoredBody }; }; /** * Encrypt the body in the given package. Should only be used if the package body differs from message body * (i.e. the draft body) */ const encryptBodyPackage = async ({ body, privateKeys, publicKeysList, }: { body?: string; privateKeys: PrivateKeyReference[]; publicKeysList: (PublicKeyReference | undefined)[]; }) => { const cleanPublicKeys = publicKeysList.filter(isTruthy); const sessionKey = cleanPublicKeys.length ? await CryptoProxy.generateSessionKey({ recipientKeys: cleanPublicKeys }) : await generateSessionKeyHelper(); // we encrypt using `sessionKey` directly instead of `encryptionKeys` so that returned message only includes // symmetrically encrypted data const { message: encryptedData } = await CryptoProxy.encryptMessage({ textData: body || '', stripTrailingSpaces: true, sessionKey, signingKeys: privateKeys, format: 'binary', }); // encrypt to each public key separetely to get separate serialized session keys const encryptedSessionKeys = await Promise.all( cleanPublicKeys.map((publicKey) => CryptoProxy.encryptSessionKey({ ...sessionKey, encryptionKeys: publicKey, format: 'binary', }) ) ); return { keys: encryptedSessionKeys, encrypted: encryptedData, sessionKey }; }; /** * Temporary helper to encrypt the draft body. Get rid of this mutating function with refactor */ const encryptDraftBody = async ({ publicKeys, privateKeys, message, }: { privateKeys: PrivateKeyReference[]; publicKeys: PublicKeyReference[]; message: RequireOnly<Message, 'Body' | 'MIMEType'>; }) => { const { armoredBody } = await encryptDraftBodyPackage({ body: message.Body, publicKeys, privateKeys }); message.Body = armoredBody; }; /** * Encrypts the body of the package and then overwrites the body in the package and adds the encrypted session keys * to the subpackages. If we send clear message the unencrypted session key is added to the (top-level) package too. */ const encryptBody = async ({ pack, privateKeys, publicKeys, message, }: { pack: PackageDirect; privateKeys: PrivateKeyReference[]; publicKeys: PublicKeyReference[]; message: RequireOnly<Message, 'Body' | 'MIMEType'>; }): Promise<void> => { const addressKeys = Object.keys(pack.Addresses || {}).filter(isTruthy); const addresses = Object.values(pack.Addresses || {}).filter(isTruthy); const publicKeysList = addresses.map(({ PublicKey }) => PublicKey); const { keys, encrypted, sessionKey } = message.MIMEType === pack.MIMEType ? await encryptDraftBodyPackage({ body: pack.Body, publicKeys, privateKeys, publicKeysList, }) : await encryptBodyPackage({ body: pack.Body, privateKeys, publicKeysList, }); let counter = 0; publicKeysList.forEach((publicKey, index) => { if (!publicKey) { return; } const key = keys[counter++]; const address = pack.Addresses?.[addressKeys[index]]; if (!address) { return; } address.BodyKeyPacket = uint8ArrayToBase64String(key); }); if ((pack.Type || 0) & (SEND_CLEAR | SEND_CLEAR_MIME)) { // eslint-disable-next-line require-atomic-updates pack.BodyKey = packToBase64(sessionKey); } // eslint-disable-next-line require-atomic-updates pack.Body = uint8ArrayToBase64String(encrypted); }; const encryptPackage = async ({ pack, publicKeys, privateKeys, attachmentKeys, message, }: { pack: PackageDirect; publicKeys: PublicKeyReference[]; privateKeys: PrivateKeyReference[]; attachmentKeys: AttachmentKeys[]; message: RequireOnly<Message, 'Body' | 'MIMEType'>; }): Promise<void> => { await Promise.all([ encryptBody({ pack, publicKeys, privateKeys, message }), encryptAttachmentKeys({ pack, attachmentKeys }), ]); Object.values(pack.Addresses || {}).forEach((address: any) => delete address.PublicKey); }; const getAttachmentKeys = async ( attachments: Attachment[], privateKeys: PrivateKeyReference[] ): Promise<AttachmentKeys[]> => Promise.all( attachments.map(async (attachment) => ({ Attachment: attachment, SessionKey: await getSessionKey(attachment, privateKeys), })) ); /** * Encrypts the packages and removes all temporary values that should not be send to the API */ export const encryptPackages = async ({ packages, attachments, privateKeys, publicKeys, message, }: { packages: SimpleMap<PackageDirect>; attachments: Attachment[]; privateKeys: PrivateKeyReference[]; publicKeys: PublicKeyReference[]; message: RequireOnly<Message, 'Body' | 'MIMEType'>; }): Promise<SimpleMap<PackageDirect>> => { const attachmentKeys = await getAttachmentKeys(attachments, privateKeys); const packageList = Object.values(packages) as PackageDirect[]; await Promise.all([ ...packageList.map((pack) => encryptPackage({ pack, privateKeys, publicKeys, attachmentKeys, message })), encryptDraftBody({ publicKeys, privateKeys, message }), ]); return packages; };
8,701
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/send/sendPreferences.ts
import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import { MIME_TYPES, PGP_SCHEMES } from '../../constants'; import { Message } from '../../interfaces/mail/Message'; import { EncryptionPreferences } from '../encryptionPreferences'; import { isEO } from '../messages'; const { SEND_PM, SEND_EO, SEND_CLEAR, SEND_PGP_INLINE, SEND_PGP_MIME } = PACKAGE_TYPE; /** * Logic for determining the PGP scheme to be used when sending to an email address. * The API expects a package type. */ export const getPGPScheme = ( { encrypt, sign, scheme, isInternal }: Pick<EncryptionPreferences, 'encrypt' | 'sign' | 'scheme' | 'isInternal'>, message?: Partial<Message> ): PACKAGE_TYPE => { if (isInternal) { return SEND_PM; } if (!encrypt && isEO(message)) { return SEND_EO; } if (sign) { return scheme === PGP_SCHEMES.PGP_INLINE ? SEND_PGP_INLINE : SEND_PGP_MIME; } return SEND_CLEAR; }; export const getPGPSchemeAndMimeType = ( { encrypt, sign, scheme, isInternal, mimeType: prefMimeType, }: Pick<EncryptionPreferences, 'encrypt' | 'sign' | 'scheme' | 'mimeType' | 'isInternal'>, message?: Partial<Message> ): { pgpScheme: PACKAGE_TYPE; mimeType: MIME_TYPES } => { const messageMimeType = message?.MIMEType as MIME_TYPES; const pgpScheme = getPGPScheme({ encrypt, sign, scheme, isInternal }, message); if (sign && [SEND_PGP_INLINE, SEND_PGP_MIME].includes(pgpScheme)) { const enforcedMimeType = pgpScheme === SEND_PGP_INLINE ? MIME_TYPES.PLAINTEXT : MIME_TYPES.MIME; return { pgpScheme, mimeType: enforcedMimeType }; } // If sending EO, respect the MIME type of the composer, since it will be what the API returns when retrieving the message. // If plain text is selected in the composer and the message is not signed, send in plain text if (pgpScheme === SEND_EO || messageMimeType === MIME_TYPES.PLAINTEXT) { return { pgpScheme, mimeType: messageMimeType || prefMimeType }; } return { pgpScheme, mimeType: prefMimeType || messageMimeType }; };
8,702
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/send/sendSubPackages.ts
import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; /** * Currently this is basically a copy of sendSubPackages from the mail repo. TO BE IMPROVED */ import { MIME_TYPES } from '../../constants'; import { Attachment } from '../../interfaces/mail/Message'; import { PackageDirect, SendPreferences } from '../../interfaces/mail/crypto'; import { SimpleMap } from '../../interfaces/utils'; const { PLAINTEXT, DEFAULT, MIME } = MIME_TYPES; const { SEND_PM, SEND_CLEAR, SEND_PGP_INLINE, SEND_PGP_MIME, SEND_CLEAR_MIME } = PACKAGE_TYPE; /** * Package for a Proton Mail user. */ const sendPM = async ({ publicKeys }: Pick<SendPreferences, 'publicKeys'>, attachments: Attachment[] = []) => ({ Type: SEND_PM, PublicKey: (publicKeys?.length && publicKeys[0]) || undefined, Signature: +attachments.every(({ Signature }) => Signature), }); /** * Package for a PGP/MIME user. */ const sendPGPMime = async ({ encrypt, sign, publicKeys }: Pick<SendPreferences, 'encrypt' | 'sign' | 'publicKeys'>) => { if (encrypt) { return { Type: SEND_PGP_MIME, PublicKey: (publicKeys?.length && publicKeys[0]) || undefined, }; } // PGP/MIME signature only return { Type: SEND_CLEAR_MIME, Signature: +sign, }; }; /** * Package for a PGP/Inline user. */ const sendPGPInline = async ( { encrypt, sign, publicKeys }: Pick<SendPreferences, 'encrypt' | 'sign' | 'publicKeys'>, attachments: Attachment[] = [] ) => { if (encrypt) { return { Type: SEND_PGP_INLINE, PublicKey: (publicKeys?.length && publicKeys[0]) || undefined, Signature: +attachments.every(({ Signature }) => Signature), }; } // PGP/Inline signature only return { Type: SEND_CLEAR, Signature: +sign, }; }; /** * Package for an unencrypted user */ const sendClear = async () => ({ Type: SEND_CLEAR, Signature: 0 }); /** * Attach the subpackages for encryptMessage to the given top level packages. The packages need to be encrypted before * they can be send to the api. See encryptPackages for that. */ export const attachSubPackages = async ({ packages, attachments = [], emails, sendPreferencesMap, }: { packages: SimpleMap<PackageDirect>; attachments: Attachment[]; emails: string[]; sendPreferencesMap: SimpleMap<SendPreferences>; }): Promise<SimpleMap<PackageDirect>> => { const bindPackageSet = async (promise: Promise<PackageDirect>, email: string, type: MIME_TYPES) => { const pack = await promise; const packageToUpdate = packages[type] as PackageDirect; if (!packageToUpdate.Addresses) { packageToUpdate.Addresses = {}; } if (!packageToUpdate.Type) { packageToUpdate.Type = 0; } packageToUpdate.Addresses[email] = pack; packageToUpdate.Type |= pack.Type || 0; }; const promises = emails.map((email: string) => { const sendPrefs = sendPreferencesMap[email]; if (!sendPrefs) { throw new Error('Missing send preferences'); } const { encrypt, sign, pgpScheme, mimeType, publicKeys } = sendPrefs; const packageType = mimeType === 'text/html' ? DEFAULT : PLAINTEXT; switch (pgpScheme) { case SEND_PM: return bindPackageSet(sendPM({ publicKeys }, attachments), email, packageType); case SEND_PGP_MIME: if (!sign && !encrypt) { return bindPackageSet(sendClear(), email, DEFAULT); } return bindPackageSet(sendPGPMime({ encrypt, sign, publicKeys }), email, MIME); case SEND_PGP_INLINE: return bindPackageSet(sendPGPInline({ encrypt, sign, publicKeys }, attachments), email, PLAINTEXT); case SEND_CLEAR: // Sent encrypted for outside (EO) not supported here return bindPackageSet(sendClear(), email, packageType); default: throw new Error('Invalid PGP scheme'); } }); await Promise.all(promises); return packages; };
8,703
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/send/sendTopPackages.ts
/** * Currently this is basically a copy of sendSubPackages from the mail repo. TO BE IMPROVED */ import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import isTruthy from '@proton/utils/isTruthy'; import { MIME_TYPES } from '../../constants'; import { Message } from '../../interfaces/mail/Message'; import { AttachmentDirect, PackageDirect, PackageStatus, SendPreferences } from '../../interfaces/mail/crypto'; import { RequireOnly, SimpleMap } from '../../interfaces/utils'; import { constructMime } from './helpers'; const { PLAINTEXT, DEFAULT, MIME } = MIME_TYPES; /** * Generates the mime top-level packages, which include all attachments in the body. * Build the multipart/alternate MIME entity containing both the HTML and plain text entities. */ const generateMimePackage = ( message: RequireOnly<Message, 'Body'>, attachmentData: { attachment: AttachmentDirect; data: string } ): PackageDirect => ({ Addresses: {}, MIMEType: MIME, Body: constructMime(message.Body, attachmentData), }); const generatePlainTextPackage = (message: RequireOnly<Message, 'Body'>): PackageDirect => ({ Addresses: {}, MIMEType: PLAINTEXT, Body: message.Body, }); const generateHTMLPackage = (message: RequireOnly<Message, 'Body'>): PackageDirect => ({ Addresses: {}, MIMEType: DEFAULT, // We NEVER upconvert, if the user wants html: plaintext is actually fine as well Body: message.Body, }); /** * Generates all top level packages. The top level packages have unencrypted bodies which are encrypted later on * once the sub level packages are attached, so we know with which keys we need to encrypt the bodies with. * Top level packages that are not needed are not generated. */ export const generateTopPackages = ({ message, sendPreferencesMap, attachmentData, }: { message: RequireOnly<Message, 'Body'>; sendPreferencesMap: SimpleMap<SendPreferences>; attachmentData: { attachment: AttachmentDirect; data: string }; }): SimpleMap<PackageDirect> => { const packagesStatus: PackageStatus = Object.values(sendPreferencesMap) .filter(isTruthy) .reduce( (packages, { encrypt, sign, pgpScheme, mimeType }) => ({ [PLAINTEXT]: packages[PLAINTEXT] || mimeType === MIME_TYPES.PLAINTEXT, [DEFAULT]: packages[DEFAULT] || mimeType === DEFAULT || (pgpScheme === PACKAGE_TYPE.SEND_PGP_MIME && !encrypt && !sign), [MIME]: packages[MIME] || (pgpScheme === PACKAGE_TYPE.SEND_PGP_MIME && (encrypt || sign)), }), { [PLAINTEXT]: false, [DEFAULT]: false, [MIME]: false, } as PackageStatus ); const demandedPackages = Object.values(MIME_TYPES).filter((k) => packagesStatus[k]); const packages: SimpleMap<PackageDirect> = {}; demandedPackages.map(async (type) => { switch (type) { case MIME: packages[MIME] = generateMimePackage(message, attachmentData); return; case PLAINTEXT: packages[PLAINTEXT] = generatePlainTextPackage(message); return; case DEFAULT: packages[DEFAULT] = generateHTMLPackage(message); return; default: throw new Error(); // Should never happen. } }); return packages; };
8,704
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mnemonic/bip39Wrapper.ts
import { entropyToMnemonic, mnemonicToEntropy, validateMnemonic as validateMnemonicBip39 } from '@protontech/bip39'; import { base64StringToUint8Array, uint8ArrayToBase64String } from '../helpers/encoding'; export const generateMnemonicBase64RandomBytes = () => { const length = 16; const randomValues = crypto.getRandomValues(new Uint8Array(length)); return uint8ArrayToBase64String(randomValues); }; export const generateMnemonicFromBase64RandomBytes = (base64RandomBytes: string) => { const randomBytes = base64StringToUint8Array(base64RandomBytes); return entropyToMnemonic(randomBytes); }; export const mnemonicToBase64RandomBytes = async (mnemonicWords: string) => { const randomBytes = await mnemonicToEntropy(mnemonicWords); return uint8ArrayToBase64String(randomBytes); }; export const validateMnemonic = (mnemonic: string) => { return validateMnemonicBip39(mnemonic); };
8,705
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mnemonic/helpers.ts
import { CryptoProxy } from '@proton/crypto'; import { computeKeyPassword, generateKeySalt } from '@proton/srp'; import { Api, DecryptedKey } from '../interfaces'; import { srpGetVerify } from '../srp'; import { generateMnemonicBase64RandomBytes, generateMnemonicFromBase64RandomBytes } from './bip39Wrapper'; export interface MnemonicData { salt: string; randomBytes: string; mnemonic: string; } export const generateMnemonicWithSalt = async () => { const salt = generateKeySalt(); const randomBytes = generateMnemonicBase64RandomBytes(); const mnemonic = await generateMnemonicFromBase64RandomBytes(randomBytes); return { salt, randomBytes, mnemonic, }; }; interface GenerateMnemonicPayloadParams { randomBytes: string; salt: string; userKeys: DecryptedKey[]; api: Api; username: string; } export const generateMnemonicPayload = async ({ randomBytes, salt, userKeys, api, username, }: GenerateMnemonicPayloadParams) => { const hashedPassphrase = await computeKeyPassword(randomBytes, salt); const reEncryptedKeys = await Promise.all( userKeys.map(async ({ ID, privateKey }) => { const PrivateKey = await CryptoProxy.exportPrivateKey({ privateKey, passphrase: hashedPassphrase, }); return { ID, PrivateKey, }; }) ); const { Auth } = await srpGetVerify({ api, credentials: { username, password: randomBytes, }, }); return { MnemonicUserKeys: reEncryptedKeys, MnemonicSalt: salt, MnemonicAuth: Auth, }; };
8,706
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/mnemonic/index.ts
export * from './bip39Wrapper'; export * from './helpers';
8,707
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/addressesModel.js
import { getAllAddresses } from '../api/addresses'; import updateCollection from '../helpers/updateCollection'; export const AddressesModel = { key: 'Addresses', get: getAllAddresses, update: (model, events) => updateCollection({ model, events, itemKey: 'Address' }), };
8,708
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/apiEnvironmentConfigModel.js
import { getApiEnvConfig } from '../api/apiEnvironmentConfig'; import updateCollection from '../helpers/updateCollection'; export const getApiEnvironmentConfigModel = (api) => { return api(getApiEnvConfig()).then(({ Config }) => Config); }; export const ApiEnvironmentConfigModel = { key: 'ApiEnvironmentConfig', get: getApiEnvironmentConfigModel, update: (model, events) => updateCollection({ model, events, itemKey: 'Config' }), };
8,709
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/cache.ts
export enum STATUS { PENDING = 1, RESOLVED = 2, REJECTED = 3, }
8,710
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/calendarSettingsModel.js
import { getCalendarUserSettings } from '../api/calendars'; import updateObject from '../helpers/updateObject'; export const getCalendarUserSettingsModel = (api) => { return api(getCalendarUserSettings()).then(({ CalendarUserSettings }) => CalendarUserSettings); }; export const CalendarUserSettingsModel = { key: 'CalendarUserSettings', get: getCalendarUserSettingsModel, update: updateObject, };
8,711
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/calendarsModel.js
import { queryCalendars } from '../api/calendars'; import updateCollection from '../helpers/updateCollection'; export const CALENDARS_CACHE_KEY = 'Calendars'; export const getCalendars = async (api) => { const result = await api(queryCalendars()); return result.Calendars; }; export const CalendarsModel = { key: CALENDARS_CACHE_KEY, get: getCalendars, update: (model, events) => { updateCollection({ model, events, itemKey: 'Calendar' }); }, };
8,712
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/contactEmailsModel.js
import { queryContactEmails } from '../api/contacts'; import queryPages from '../api/helpers/queryPages'; import { CONTACTS_REQUESTS_PER_SECOND, CONTACT_EMAILS_LIMIT } from '../constants'; import updateCollection from '../helpers/updateCollection'; export const getContactEmailsModel = (api) => { return queryPages( (page, pageSize) => { return api( queryContactEmails({ Page: page, PageSize: pageSize, }) ); }, { pageSize: CONTACT_EMAILS_LIMIT, pagesPerChunk: CONTACTS_REQUESTS_PER_SECOND, delayPerChunk: 1000, } ).then((pages) => { return pages.flatMap(({ ContactEmails }) => ContactEmails); }); }; export const ContactEmailsModel = { key: 'ContactEmails', get: getContactEmailsModel, update: (model, events) => updateCollection({ model, events, itemKey: 'ContactEmail' }), };
8,713
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/contactsModel.js
import { queryContacts } from '../api/contacts'; import queryPages from '../api/helpers/queryPages'; import { CONTACTS_LIMIT, CONTACTS_REQUESTS_PER_SECOND } from '../constants'; import updateCollection from '../helpers/updateCollection'; /** * 1. Specific fields from the contact is picked to store less data in the cache * since all of the contacts are fetched and stored. * 2. It also handles the updates from the event manager where all of the contact * data is received. */ const pick = ({ ID, Name, LabelIDs }) => ({ ID, Name, LabelIDs }); const compareName = (a, b) => a.Name.localeCompare(b.Name); export const getContactsModel = (api) => { return queryPages( (Page, PageSize) => api( queryContacts({ Page, PageSize, }) ), { pageSize: CONTACTS_LIMIT, pagesPerChunk: CONTACTS_REQUESTS_PER_SECOND, } ).then((pages) => { return pages.flatMap(({ Contacts }) => Contacts.map(pick)).sort(compareName); }); }; const mergeModel = (oldModel, newModel) => { // Contacts events return the full new model return newModel; }; export const ContactsModel = { key: 'Contacts', get: getContactsModel, update: (model, events) => updateCollection({ model, events, item: ({ Contact }) => pick(Contact), itemKey: 'Contact', merge: mergeModel, }).sort(compareName), };
8,714
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/conversationCountsModel.js
import { queryConversationCount } from '../api/conversations'; import updateCounter from '../helpers/updateCounter'; export const getConversationCountsModel = (api) => { return api(queryConversationCount()).then(({ Counts }) => Counts); }; export const ConversationCountsModel = { key: 'ConversationCounts', get: getConversationCountsModel, update: updateCounter, };
8,715
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/domainsModel.js
import { queryDomains } from '../api/domains'; import queryPages from '../api/helpers/queryPages'; import updateCollection from '../helpers/updateCollection'; export const getDomainsModel = (api) => { return queryPages((page, pageSize) => { return api( queryDomains({ Page: page, PageSize: pageSize, }) ); }).then((pages) => { return pages.flatMap(({ Domains }) => Domains); }); }; export const DomainsModel = { key: 'Domains', get: getDomainsModel, update: (model, events) => updateCollection({ model, events, itemKey: 'Domain' }), };
8,716
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/filtersModel.js
import { queryFilters } from '../api/filters'; import updateCollection from '../helpers/updateCollection'; export const getFiltersModel = (api) => { return api(queryFilters()).then(({ Filters }) => Filters); }; export const FiltersModel = { key: 'Filters', get: getFiltersModel, update: (model, events) => updateCollection({ model, events, itemKey: 'Filter' }), };
8,717
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/helper.ts
import { Cache } from '../helpers/cache'; import { Api } from '../interfaces'; import { STATUS } from './cache'; interface Args { api: Api; cache: Cache<string, any>; useCache?: boolean; } export const loadModels = async (models: any[] = [], { api, cache, useCache = true }: Args): Promise<any[]> => { const result = await Promise.all( models.map((model) => { // Special case to not re-fetch the model if it exists. This can happen for // the user model which is set at login. if (useCache && cache.has(model.key)) { return cache.get(model.key).value as any; } return model.get(api); }) ); models.forEach((model, i) => { cache.set(model.key, { value: result[i], status: STATUS.RESOLVED, }); }); return result; };
8,718
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/holidaysCalendarsModel.ts
import { getDirectoryCalendars } from '@proton/shared/lib/api/calendars'; import { CALENDAR_TYPE } from '@proton/shared/lib/calendar/constants'; import { Api } from '@proton/shared/lib/interfaces'; import { HolidaysDirectoryCalendar } from '@proton/shared/lib/interfaces/calendar'; export const getHolidaysCalendarsModel = (api: Api) => { return api<{ Calendars: HolidaysDirectoryCalendar }>(getDirectoryCalendars(CALENDAR_TYPE.HOLIDAYS)).then( ({ Calendars }) => { return Calendars; } ); }; export const HolidaysCalendarsModel = { key: 'HolidaysCalendars', get: getHolidaysCalendarsModel, };
8,719
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/importersModel.js
import { getImportReportsList, getImportsList } from '@proton/activation/src/api'; import updateCollection from '../helpers/updateCollection'; export const getImportsModel = (api) => { return api(getImportsList()) .then(({ Importers }) => Importers) .catch(() => []); }; export const getImportReportsModel = (api) => { return api(getImportReportsList()) .then(({ Reports }) => Reports) .catch(() => []); }; export const ImportersModel = { key: 'Imports', get: getImportsModel, update: (model, events) => updateCollection({ model, events, itemKey: 'Importer', merge: (oldModel, newModel) => newModel, }), }; export const ImportReportsModel = { key: 'ImportReports', get: getImportReportsModel, update: (model, events) => updateCollection({ model, events, itemKey: 'ImportReport', }), };
8,720
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/incomingAddressForwardingModel.js
import { queryAllIncomingForwardings } from '../api/forwardings'; import updateCollection from '../helpers/updateCollection'; export const IncomingAddressForwardingModel = { key: 'IncomingAddressForwardings', get: queryAllIncomingForwardings, update: (model, events) => updateCollection({ model, events, itemKey: 'IncomingAddressForwarding' }), };
8,721
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/index.js
export { AddressesModel } from './addressesModel'; export { ApiEnvironmentConfigModel } from './apiEnvironmentConfigModel'; export { ContactEmailsModel } from './contactEmailsModel'; export { ContactsModel } from './contactsModel'; export { DomainsModel } from './domainsModel'; export { FiltersModel } from './filtersModel'; export { HolidaysCalendarsModel } from './holidaysCalendarsModel'; export { PaymentMethodsModel } from './paymentMethodsModel'; export { LabelsModel } from './labelsModel'; export { MailSettingsModel } from './mailSettingsModel'; export { MembersModel } from './membersModel'; export { UserInvitationModel } from './userInvitationModel'; export { OrganizationModel } from './organizationModel'; export { UserModel } from './userModel'; export { UserSettingsModel } from './userSettingsModel'; export { SubscriptionModel } from './subscriptionModel'; export { CalendarsModel } from './calendarsModel'; export { CalendarUserSettingsModel } from './calendarSettingsModel'; export { ConversationCountsModel } from './conversationCountsModel'; export { MessageCountsModel } from './messageCountsModel'; export { ImportersModel, ImportReportsModel } from './importersModel'; export { IncomingAddressForwardingModel } from './incomingAddressForwardingModel'; export { OutgoingAddressForwardingModel } from './outgoingAddressForwardingModel';
8,722
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/labelsModel.js
import { getContactGroup, getFolders, getLabels, getSystemFolders } from '../api/labels'; import updateCollection from '../helpers/updateCollection'; const extractLabels = ({ Labels = [] }) => Labels; export const getLabelsModel = async (api) => { const [labels = [], folders = [], contactGroups = [], systemFolders = []] = await Promise.all([ api(getLabels()).then(extractLabels), api(getFolders()).then(extractLabels), api(getContactGroup()).then(extractLabels), api(getSystemFolders()).then(extractLabels), ]); return [...labels, ...folders, ...contactGroups, ...systemFolders]; }; export const LabelsModel = { key: 'Labels', get: getLabelsModel, update: (model, events) => updateCollection({ model, events, itemKey: 'Label', merge: (a, b) => b }), };
8,723
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/mailSettingsModel.js
import { getMailSettings } from '../api/mailSettings'; import updateObject from '../helpers/updateObject'; export const getMailSettingsModel = (api) => { return api(getMailSettings()).then(({ MailSettings }) => MailSettings); }; export const handleMailSettingsEvents = updateObject; export const MailSettingsModel = { key: 'MailSettings', get: getMailSettingsModel, update: updateObject, };
8,724
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/mailUtmTrackers.ts
export interface MessageUTMTracker { originalURL: string; cleanedURL: string; removed: { key: string; value: string }[]; }
8,725
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/membersModel.js
import { getAllMembers } from '../api/members'; import updateCollection from '../helpers/updateCollection'; export const MembersModel = { key: 'Members', get: getAllMembers, update: (model, events) => updateCollection({ model, events, itemKey: 'Member' }), };
8,726
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/messageCountsModel.js
import { queryMessageCount } from '../api/messages'; import updateCounter from '../helpers/updateCounter'; export const getMessageCountsModel = (api) => { return api(queryMessageCount()).then(({ Counts }) => Counts); }; export const MessageCountsModel = { key: 'MessageCounts', get: getMessageCountsModel, update: updateCounter, };
8,727
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/organizationModel.js
import { getOrganization } from '../api/organization'; import updateObject from '../helpers/updateObject'; export const getOrganizationModel = (api) => { return api(getOrganization()).then(({ Organization }) => Organization); }; export const OrganizationModel = { key: 'Organization', get: getOrganizationModel, update: updateObject, };
8,728
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/outgoingAddressForwardingModel.js
import { queryAllOutgoingForwardings } from '../api/forwardings'; import updateCollection from '../helpers/updateCollection'; export const OutgoingAddressForwardingModel = { key: 'OutgoingAddressForwardings', get: queryAllOutgoingForwardings, update: (model, events) => updateCollection({ model, events, itemKey: 'OutgoingAddressForwarding' }), };
8,729
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/paymentMethodsModel.js
import { queryPaymentMethods } from '../api/payments'; import updateCollection from '../helpers/updateCollection'; export const getPaymentMethodsModel = (api) => { return api(queryPaymentMethods()).then(({ PaymentMethods }) => PaymentMethods); }; export const PaymentMethodsModel = { key: 'PaymentMethods', get: getPaymentMethodsModel, update: (model, events) => updateCollection({ model, events, itemKey: 'PaymentMethod' }), };
8,730
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/subscriptionModel.js
import { getSubscription } from '../api/payments'; import updateObject from '../helpers/updateObject'; import formatSubscription from '../subscription/format'; /** * @param {*} api * @returns {Promise<import('../interfaces').SubscriptionModel>} */ export const getSubscriptionModel = (api) => { return api(getSubscription()).then(({ Subscription, UpcomingSubscription }) => formatSubscription(Subscription, UpcomingSubscription) ); }; export const SubscriptionModel = { key: 'Subscription', get: getSubscriptionModel, update: (model, events) => { let eventsSubscription = updateObject(model, events); /** * There are two possible cases in the events: UpcomingSubscription created and UpcomingSubscription deleted. * This branch handles the deletion case, whereas {@link updateObject()} above handles the creation case. */ if (events.UpcomingSubscription === undefined) { delete eventsSubscription.UpcomingSubscription; } /** * In contrast to {@link getSubscriptionModel()}, events have a different structure for the * UpcomingSubscription. For example, {@link getSubscription()} endpoint returns the both properties on the top * level: { Subscription: { ... }, UpcomingSubscription: { ... }} Events make the upcoming subscription nested: * { Subscription: { UpcomingSubscription: { ... }, ...} } */ return formatSubscription(eventsSubscription, eventsSubscription.UpcomingSubscription); }, };
8,731
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/userInvitationModel.js
import updateCollection from '../helpers/updateCollection'; import { fetchPendingUserInvitations } from './userInvitationModelApi'; export const UserInvitationModel = { key: 'UserInvitations', get: fetchPendingUserInvitations, update: (model, events) => updateCollection({ model, events, itemKey: 'UserInvitation' }), };
8,732
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/userInvitationModelApi.ts
import { getInvitations } from '@proton/shared/lib/api/user'; import { Api, PendingInvitation as PendingUserInvitation } from '@proton/shared/lib/interfaces'; export const fetchPendingUserInvitations = (api: Api) => api<{ UserInvitations: PendingUserInvitation[] }>(getInvitations()).then(({ UserInvitations }) => { return UserInvitations; });
8,733
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/userModel.js
import { getUser } from '../api/user'; import updateObject from '../helpers/updateObject'; import { getInfo } from '../user/helpers'; export const formatUser = (User) => { return { ...User, ...getInfo(User), }; }; export const getUserModel = (api) => { return api(getUser()).then(({ User }) => formatUser(User)); }; export const UserModel = { key: 'User', get: getUserModel, update: (model, events) => formatUser(updateObject(model, events)), };
8,734
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/models/userSettingsModel.ts
import { getSettings } from '../api/settings'; import updateObject from '../helpers/updateObject'; import { Api, UserSettings } from '../interfaces'; export const getUserSettingsModel = (api: Api) => { return api<{ UserSettings: UserSettings }>(getSettings()).then(({ UserSettings }) => { const userSettings: UserSettings = UserSettings; return userSettings; }); }; export const UserSettingsModel = { key: 'UserSettings', get: getUserSettingsModel, update: updateObject, };
8,735
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/organization/helper.ts
import { MEMBER_ROLE, MEMBER_SUBSCRIBER, PLANS } from '../constants'; import { CachedOrganizationKey, DOMAIN_STATE, Domain, Member, Organization } from '../interfaces'; export const isSuperAdmin = (members: Member[]) => (members || []).some(({ Subscriber, Self }) => Self === 1 && Subscriber === MEMBER_SUBSCRIBER.PAYER); export const getHasOtherAdmins = (members: Member[]) => members.some(({ Role, Self }) => Self !== 1 && Role === MEMBER_ROLE.ORGANIZATION_ADMIN); export const getNonPrivateMembers = (members: Member[]) => members.filter(({ Private }) => Private === 0); export const isOrganizationFamily = (organization: Organization) => organization.PlanName === PLANS.FAMILY; export const isOrganizationVisionary = (organization: Organization) => organization.PlanName === PLANS.NEW_VISIONARY; export const isOrganizationB2B = (organization?: Organization) => { return [ PLANS.MAIL_PRO, PLANS.DRIVE_PRO, PLANS.BUNDLE_PRO, PLANS.ENTERPRISE, PLANS.FAMILY, PLANS.NEW_VISIONARY, ].includes(organization?.PlanName as PLANS); }; export const getOrganizationKeyInfo = ( organization: Organization | undefined, organizationKey?: CachedOrganizationKey ) => { const organizationHasKeys = !!organization?.HasKeys; // If the user has the organization key (not the organization itself). const userHasActivatedOrganizationKeys = !!organizationKey?.Key?.PrivateKey; return { // If the user does not have the organization key but the organization has keys setup, it's inactive userNeedsToActivateKey: organizationHasKeys && !userHasActivatedOrganizationKeys, // If the user has the organization key, but it's not decrypted. Typically following a password reset userNeedsToReactivateKey: organizationHasKeys && userHasActivatedOrganizationKeys && !organizationKey?.privateKey, }; }; // Active domains is one that's verified or in warning state, but it can be used to create addresses to export const getIsDomainActive = (domain: Domain) => { return domain.State === DOMAIN_STATE.DOMAIN_STATE_VERIFIED || domain.State === DOMAIN_STATE.DOMAIN_STATE_WARN; };
8,736
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/pass/constants.ts
interface Client { title: string; link: string; icon: 'brand-chrome' | 'brand-android' | 'brand-apple' | 'brand-brave' | 'brand-firefox' | 'brand-edge'; } export enum Clients { Chrome, Android, iOS, Brave, Firefox, Edge, } export const clients: { [key in Clients]: Client } = { [Clients.Android]: { title: 'Android', link: 'https://play.google.com/store/apps/details?id=proton.android.pass', icon: 'brand-android', }, [Clients.iOS]: { title: 'iOS', link: 'https://apps.apple.com/us/app/id6443490629', icon: 'brand-apple', }, [Clients.Chrome]: { title: 'Chrome', link: 'https://chrome.google.com/webstore/detail/proton-pass/ghmbeldphafepmbegfdlkpapadhbakde', icon: 'brand-chrome', }, [Clients.Brave]: { title: 'Brave', link: 'https://chrome.google.com/webstore/detail/proton-pass/ghmbeldphafepmbegfdlkpapadhbakde', icon: 'brand-brave', }, [Clients.Edge]: { title: 'Edge', link: 'https://chrome.google.com/webstore/detail/proton-pass/ghmbeldphafepmbegfdlkpapadhbakde', icon: 'brand-edge', }, [Clients.Firefox]: { title: 'Firefox', link: 'https://addons.mozilla.org/en-US/firefox/addon/proton-pass', icon: 'brand-firefox', }, } as const;
8,737
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/pow/pbkdfWorker.ts
import { uint8ArrayToBase64String } from '../helpers/encoding'; const Pbkdf2PRFKeySize = 32; const Pbkdf2ChallengeSize = 3 * Pbkdf2PRFKeySize + 32 + 4; const Pbkdf2OutputSize = 32; const sha256Size = 32; function areBuffersEqual(buf1: ArrayBuffer, buf2: ArrayBuffer): boolean { if (buf1.byteLength !== buf2.byteLength) { return false; } const dv1 = new Uint8Array(buf1); const dv2 = new Uint8Array(buf2); for (let i = 0; i !== buf1.byteLength; i++) { if (dv1[i] !== dv2[i]) { return false; } } return true; } async function solveChallengePbkdf2Preimage(b64challenge: string, deadlineUnixMilli: number) { const buffer = new ArrayBuffer(8); const challenge = Uint8Array.from(atob(b64challenge), (c) => c.charCodeAt(0)); if (challenge.length !== Pbkdf2ChallengeSize) { throw new Error('Invalid challenge length'); } const prfKeys = challenge.subarray(0, 3 * Pbkdf2PRFKeySize); const goal = challenge.subarray(3 * Pbkdf2PRFKeySize, 3 * Pbkdf2PRFKeySize + sha256Size); const pbkdf2Params = challenge.subarray(3 * Pbkdf2PRFKeySize + sha256Size, Pbkdf2ChallengeSize); const iterations = new DataView(pbkdf2Params.buffer, pbkdf2Params.byteOffset, pbkdf2Params.byteLength).getUint32( 0, true ); const startTime = Date.now(); let stage: ArrayBuffer = new ArrayBuffer(0); let i: number = 0; const prePRFKey = await crypto.subtle.importKey( 'raw', prfKeys.subarray(0, Pbkdf2PRFKeySize), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'] ); const postPRFKey = await crypto.subtle.importKey( 'raw', prfKeys.subarray(2 * Pbkdf2PRFKeySize), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'] ); const salt = prfKeys.subarray(Pbkdf2PRFKeySize, 2 * Pbkdf2PRFKeySize); while (true) { if (Date.now() - startTime > deadlineUnixMilli) { throw new Error('Operation timed out'); } new DataView(buffer).setUint32(0, i, true); const prePRFHash = await crypto.subtle.sign('HMAC', prePRFKey, buffer); const derivedKey = await crypto.subtle.importKey('raw', prePRFHash, 'PBKDF2', false, ['deriveBits']); stage = await crypto.subtle.deriveBits( { name: 'PBKDF2', salt: salt, iterations: iterations, hash: 'SHA-256', }, derivedKey, Pbkdf2OutputSize * 8 ); const postPRFHash = await crypto.subtle.sign('HMAC', postPRFKey, stage); if (areBuffersEqual(postPRFHash, goal)) { break; } i++; } let solution = new Uint8Array(buffer.byteLength + stage.byteLength); solution.set(new Uint8Array(buffer), 0); solution.set(new Uint8Array(stage), buffer.byteLength); const duration = Date.now() - startTime; return { solution, duration }; } self.onmessage = async function (event) { const { b64Source } = event.data; const result = await solveChallengePbkdf2Preimage(b64Source, 15000); const b64 = uint8ArrayToBase64String(result.solution); self.postMessage(b64 + `, ${result.duration}`); };
8,738
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/pow/pbkdfWorkerWrapper.ts
export default function pbkdfWorkerWrapper() { return new Worker(new URL('./pbkdfWorker.ts', import.meta.url)); }
8,739
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/pow/wasmWorker.ts
interface WasmApi { instance: { exports: { b64_output: { value: number; }; solve: () => number; memory: { buffer: Uint8Array; }; }; }; } self.onmessage = async function (event) { const { b64Source } = event.data; const decodeBase64 = (base64: string) => { return atob(base64); }; const decodeWasmBinary = (base64: string) => { const text = decodeBase64(base64); const binary = new Uint8Array(new ArrayBuffer(text.length)); for (let i = 0; i < text.length; i++) { binary[i] = text.charCodeAt(i); } return binary; }; const loadWasmModule = async (source: string) => { const wasmBinary = decodeWasmBinary(source); const result = await WebAssembly.instantiate(wasmBinary); return result as typeof result & WasmApi; }; const result = await loadWasmModule(b64Source); const b64OutputPtr = result.instance.exports.b64_output.value; const startTime = Date.now(); const b64OutputLen = result.instance.exports.solve(); const endTime = Date.now(); const duration = endTime - startTime; const b64Output = new Uint8Array(result.instance.exports.memory.buffer, b64OutputPtr, b64OutputLen); const b64 = new TextDecoder().decode(b64Output); self.postMessage(b64 + `, ${duration}`); };
8,740
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/pow/wasmWorkerWrapper.ts
export default function wasmWorkerWrapper() { return new Worker(new URL('./wasmWorker.ts', import.meta.url)); }
8,741
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/recoveryFile/deviceRecovery.ts
import { getAllKeysReactivationRequests } from '@proton/components/containers/keys/reactivateKeys/getAllKeysToReactive'; import getLikelyHasKeysToReactivate from '@proton/components/containers/keys/reactivateKeys/getLikelyHasKeysToReactivate'; import { KeyReactivationRequestStateData } from '@proton/components/containers/keys/reactivateKeys/interface'; import { getInitialStates } from '@proton/components/containers/keys/reactivateKeys/state'; import { CryptoProxy, PrivateKeyReference } from '@proton/crypto'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import uniqueBy from '@proton/utils/uniqueBy'; import { setNewRecoverySecret } from '../api/settingsRecovery'; import { getItem, removeItem, setItem } from '../helpers/storage'; import { Address, Api, DecryptedKey, KeyPair, PreAuthKTVerify, User } from '../interfaces'; import { getDecryptedAddressKeysHelper, getDecryptedUserKeysHelper, reactivateKeysProcess } from '../keys'; import { generateRecoveryFileMessage, generateRecoverySecret, getIsRecoveryFileAvailable, getKeyWithRecoverySecret, getRecoverySecrets, parseRecoveryFiles, validateRecoverySecret, } from './recoveryFile'; const getRecoveryMessageId = (userID: string) => `dr-${userID}`; const setRecoveryMessage = (userID: string, recoveryMessage: string) => { setItem(getRecoveryMessageId(userID), recoveryMessage); }; const getRecoveryMessage = (userID: string) => { return getItem(getRecoveryMessageId(userID)); }; export const getHasRecoveryMessage = (userID: string) => { return !!getRecoveryMessage(userID); }; export const removeDeviceRecovery = (userID: string) => { removeItem(getRecoveryMessageId(userID)); }; export const getKeysFromDeviceRecovery = async (user: User) => { const recoveryMessage = getRecoveryMessage(user.ID); const recoverySecrets = getRecoverySecrets(user.Keys); if (!recoveryMessage || !recoverySecrets.length) { return; } const armouredKeys = await parseRecoveryFiles([recoveryMessage], recoverySecrets); return Promise.all( armouredKeys.map(({ armoredKey }) => CryptoProxy.importPrivateKey({ armoredKey, passphrase: null })) ); }; export const attemptDeviceRecovery = async ({ user, addresses, keyPassword, api, preAuthKTVerify, }: { user: User; addresses: Address[] | undefined; keyPassword: string; api: Api; preAuthKTVerify: PreAuthKTVerify; }) => { const privateUser = Boolean(user.Private); if (!addresses || !privateUser) { return; } const hasKeysToReactivate = getLikelyHasKeysToReactivate(user, addresses); if (!hasKeysToReactivate) { return; } const userKeys = await getDecryptedUserKeysHelper(user, keyPassword); const addressesKeys = await Promise.all( addresses.map(async (address) => { return { address, keys: await getDecryptedAddressKeysHelper(address.Keys, user, userKeys, keyPassword), }; }) ); const allKeysToReactivate = getAllKeysReactivationRequests(addressesKeys, user, userKeys); const initialStates = await getInitialStates(allKeysToReactivate); const keys = await getKeysFromDeviceRecovery(user); if (!keys) { return; } const mapToUploadedPrivateKey = ({ id, Key, fingerprint }: KeyReactivationRequestStateData) => { const uploadedPrivateKey = keys.find((decryptedBackupKey) => { return fingerprint === decryptedBackupKey.getFingerprint(); }); if (!uploadedPrivateKey) { return; } return { id, Key, privateKey: uploadedPrivateKey, }; }; const keyReactivationRecords = initialStates .map((keyReactivationRecordState) => { const uploadedKeysToReactivate = keyReactivationRecordState.keysToReactivate .map(mapToUploadedPrivateKey) .filter(isTruthy); if (!uploadedKeysToReactivate.length) { return; } return { ...keyReactivationRecordState, keysToReactivate: uploadedKeysToReactivate, }; }) .filter(isTruthy); const keyTransparencyVerify = preAuthKTVerify(userKeys); let numberOfReactivatedKeys = 0; await reactivateKeysProcess({ api, user, userKeys, addresses, keyReactivationRecords, keyPassword, onReactivation: (_, result) => { if (result === 'ok') { numberOfReactivatedKeys++; } }, keyTransparencyVerify, }); return numberOfReactivatedKeys; }; const storeRecoveryMessage = async ({ user, userKeys, recoverySecret, }: { user: User; userKeys: KeyPair[]; recoverySecret: string; }) => { const currentDeviceRecoveryKeys = (await getKeysFromDeviceRecovery(user)) || []; // Merge current device recovery keys with new keys to store. This way the act of storing device recovery information is not destructive. const keysToStore = [...userKeys.map(({ privateKey }) => privateKey), ...currentDeviceRecoveryKeys]; const uniqueKeysToStore = uniqueBy(keysToStore, (key: PrivateKeyReference) => key.getFingerprint()); const recoveryMessage = await generateRecoveryFileMessage({ recoverySecret, privateKeys: uniqueKeysToStore }); setRecoveryMessage(user.ID, recoveryMessage); }; export const storeDeviceRecovery = async ({ api, user, userKeys, }: { api: Api; user: User; userKeys: DecryptedKey[]; }) => { const privateUser = Boolean(user.Private); if (!privateUser) { return; } const primaryUserKey = userKeys?.[0]; if (!primaryUserKey) { return; } const primaryRecoverySecret = getKeyWithRecoverySecret(user.Keys.find((key) => key.ID === primaryUserKey.ID)); if (!primaryRecoverySecret) { const { recoverySecret, signature } = await generateRecoverySecret(primaryUserKey.privateKey); const silentApi = <T>(config: any) => api<T>({ ...config, silence: true }); await silentApi( setNewRecoverySecret({ RecoverySecret: recoverySecret, Signature: signature, }) ); await storeRecoveryMessage({ user, userKeys, recoverySecret }); return; } const valid = await validateRecoverySecret(primaryRecoverySecret, primaryUserKey.publicKey).catch(noop); if (!valid) { return; } await storeRecoveryMessage({ user, userKeys, recoverySecret: primaryRecoverySecret.RecoverySecret, }); }; export const getIsDeviceRecoveryAvailable = getIsRecoveryFileAvailable;
8,742
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/recoveryFile/recoveryFile.ts
import { CryptoProxy, PrivateKeyReference, PublicKeyReference, VERIFICATION_STATUS } from '@proton/crypto'; import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding'; import isTruthy from '@proton/utils/isTruthy'; import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays'; import { APPS, APP_NAMES, KEY_FILE_EXTENSION } from '../constants'; import downloadFile from '../helpers/downloadFile'; import { Address, DecryptedKey, Key, KeyWithRecoverySecret, User } from '../interfaces'; import { ArmoredKeyWithInfo, getHasMigratedAddressKeys, getPrimaryKey } from '../keys'; const decryptRecoveryFile = (recoverySecrets: KeyWithRecoverySecret[]) => async (file: string) => { try { return await Promise.any( recoverySecrets.map(async ({ RecoverySecret }) => { const { data } = await CryptoProxy.decryptMessage({ armoredMessage: file, passwords: RecoverySecret, format: 'binary', }); return data; }) ); } catch (error: any) { return undefined; } }; export const parseRecoveryFiles = async (filesAsStrings: string[] = [], recoverySecrets: KeyWithRecoverySecret[]) => { const decryptedFiles = (await Promise.all(filesAsStrings.map(decryptRecoveryFile(recoverySecrets)))).filter( isTruthy ); const decryptedArmoredKeys = ( await Promise.all( decryptedFiles.map((concatenatedBinaryKeys) => CryptoProxy.getArmoredKeys({ binaryKeys: concatenatedBinaryKeys }) ) ) ).flat(); return Promise.all( decryptedArmoredKeys.map( async (armoredKey): Promise<ArmoredKeyWithInfo> => ({ ...(await CryptoProxy.getKeyInfo({ armoredKey })), armoredKey, }) ) ); }; export const generateRecoverySecret = async (privateKey: PrivateKeyReference) => { const length = 32; const randomValues = crypto.getRandomValues(new Uint8Array(length)); const recoverySecret = uint8ArrayToBase64String(randomValues); const signature = await CryptoProxy.signMessage({ textData: recoverySecret, stripTrailingSpaces: true, signingKeys: privateKey, detached: true, }); return { signature, recoverySecret, }; }; export const generateRecoveryFileMessage = async ({ recoverySecret, privateKeys, }: { recoverySecret: string; privateKeys: PrivateKeyReference[]; }) => { const userKeysArray = await Promise.all( privateKeys.map((privateKey) => CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase: null, format: 'binary' }) ) ); const { message } = await CryptoProxy.encryptMessage({ binaryData: mergeUint8Arrays(userKeysArray), passwords: [recoverySecret], }); return message; }; export const exportRecoveryFile = async ({ recoverySecret, userKeys, }: { recoverySecret: string; userKeys: DecryptedKey[]; }) => { const message = await generateRecoveryFileMessage({ recoverySecret, privateKeys: userKeys.map(({ privateKey }) => privateKey), }); const blob = new Blob([message], { type: 'text/plain' }); downloadFile(blob, `proton_recovery${KEY_FILE_EXTENSION}`); }; export const validateRecoverySecret = async (recoverySecret: KeyWithRecoverySecret, publicKey: PublicKeyReference) => { const { RecoverySecret, RecoverySecretSignature } = recoverySecret; const { verified } = await CryptoProxy.verifyMessage({ textData: RecoverySecret, stripTrailingSpaces: true, verificationKeys: publicKey, armoredSignature: RecoverySecretSignature, }); return verified === VERIFICATION_STATUS.SIGNED_AND_VALID; }; export const getKeyWithRecoverySecret = (key: Key | undefined) => { if (!key?.RecoverySecret || !key?.RecoverySecretSignature) { return; } return key as KeyWithRecoverySecret; }; export const getRecoverySecrets = (Keys: Key[] = []): KeyWithRecoverySecret[] => { return Keys.map(getKeyWithRecoverySecret).filter(isTruthy); }; export const getPrimaryRecoverySecret = (Keys: Key[] = []): KeyWithRecoverySecret | undefined => { return getKeyWithRecoverySecret(Keys?.[0]); }; export const getIsRecoveryFileAvailable = ({ user, addresses, userKeys, appName, }: { user: User; addresses: Address[]; userKeys: DecryptedKey[]; appName: APP_NAMES; }) => { const hasMigratedKeys = getHasMigratedAddressKeys(addresses); const primaryKey = getPrimaryKey(userKeys); const isPrivateUser = Boolean(user.Private); return !!primaryKey?.privateKey && hasMigratedKeys && isPrivateUser && appName !== APPS.PROTONVPN_SETTINGS; };
8,743
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/sanitize/escape.ts
/* * This is valid * - background:&#117;r&#108;( * - background:&#117;r&#108;( * - background:url&lpar; * - etc. */ const CSS_URL = '((url|image-set)(\\(|&(#40|#x00028|lpar);))'; const REGEXP_URL_ATTR = new RegExp(CSS_URL, 'gi'); const REGEXP_HEIGHT_PERCENTAGE = /((?:min-|max-|line-)?height)\s*:\s*([\d.,]+%)/gi; const REGEXP_POSITION_ABSOLUTE = /position\s*:\s*absolute/gi; const REGEXP_MEDIA_DARK_STYLE_2 = /Color-scheme/gi; export const escape = (string: string) => { const UNESCAPE_HTML_REGEX = /[&<>"']/g; const HTML_ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', }; return string.replace(UNESCAPE_HTML_REGEX, HTML_ESCAPES as any); }; export const unescape = (string: string) => { const ESCAPED_HTML_REGEX = /&(?:amp|lt|gt|quot|#39);/g; const HTML_UNESCAPES = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", }; return string.replace(ESCAPED_HTML_REGEX, HTML_UNESCAPES as any); }; /** * Unescape a string in hex or octal encoding. * See https://www.w3.org/International/questions/qa-escapes#css_other for all possible cases. */ export const unescapeCSSEncoding = (str: string) => { // Regexp declared inside the function to reset its state (because of the global flag). // cf https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results const UNESCAPE_CSS_ESCAPES_REGEX = /\\([0-9A-Fa-f]{1,6}) ?/g; const UNESCAPE_HTML_DEC_REGEX = /&#(\d+)(;|(?=[^\d;]))/g; const UNESCAPE_HTML_HEX_REGEX = /&#x([0-9A-Fa-f]+)(;|(?=[^\d;]))/g; const OTHER_ESC = /\\(.)/g; const handleEscape = (radix: number) => (ignored: any, val: string) => { try { return String.fromCodePoint(Number.parseInt(val, radix)); } catch { // Unescape regexps have some limitations, for those rare situations, fromCodePoint can throw // One real found is: `font-family:\2018Calibri` return ''; } }; /* * basic unescaped named sequences: &amp; etcetera, lodash does not support a lot, but that is not a problem for our case. * Actually handling all escaped sequences would mean keeping track of a very large and ever growing amount of named sequences */ const namedUnescaped = unescape(str); // lodash doesn't unescape &#160; or &#xA0; sequences, we have to do this manually: const decUnescaped = namedUnescaped.replace(UNESCAPE_HTML_DEC_REGEX, handleEscape(10)); const hexUnescaped = decUnescaped.replace(UNESCAPE_HTML_HEX_REGEX, handleEscape(16)); // unescape css backslash sequences const strUnescapedHex = hexUnescaped.replace(UNESCAPE_CSS_ESCAPES_REGEX, handleEscape(16)); return strUnescapedHex.replace(OTHER_ESC, (_, char) => char); }; /** * Input can be escaped multiple times to escape replacement while still works * Best solution I found is to escape recursively * This is done 5 times maximum. If there are too much escape, we consider the string * "invalid" and we prefer to return an empty string * @argument str style to unescape * @augments stop extra security to prevent infinite loop */ export const recurringUnescapeCSSEncoding = (str: string, stop = 5): string => { const escaped = unescapeCSSEncoding(str); if (escaped === str) { return escaped; } else if (stop === 0) { return ''; } else { return recurringUnescapeCSSEncoding(escaped, stop - 1); } }; /** * Escape some WTF from the CSSParser, cf spec files * @param {String} style * @return {String} */ export const escapeURLinStyle = (style: string) => { // handle the case where the value is html encoded, e.g.: // background:&#117;rl(&quot;https://i.imgur.com/WScAnHr.jpg&quot;) const unescapedEncoding = recurringUnescapeCSSEncoding(style); const escapeFlag = unescapedEncoding !== style; const escapedStyle = unescapedEncoding.replace(/\\r/g, 'r').replace(REGEXP_URL_ATTR, 'proton-$2('); if (escapedStyle === unescapedEncoding) { // nothing escaped: just return input return style; } return escapeFlag ? escape(escapedStyle) : escapedStyle; }; export const escapeForbiddenStyle = (style: string): string => { let parsedStyle = style .replaceAll(REGEXP_POSITION_ABSOLUTE, 'position: relative') .replaceAll(REGEXP_HEIGHT_PERCENTAGE, (rule, prop) => { // Replace nothing in this case. if (['line-height', 'max-height'].includes(prop)) { return rule; } return `${prop}: unset`; }) // To replace if we support dark styles in the future. // Disable the Color-scheme so that the message do not use dark mode, message always being displayed on a white bg today .replaceAll(REGEXP_MEDIA_DARK_STYLE_2, 'proton-disabled-Color-scheme'); return parsedStyle; }; const HTML_ENTITIES_TO_REMOVE_CHAR_CODES: number[] = [ 9, // Tab : &Tab; - &#x00009; - &#9; 10, // New line : &NewLine; - &#x0000A; - &#10; 173, // Soft hyphen : &shy; - &#x000AD; - &#173; 8203, // Zero width space : &ZeroWidthSpace; - &NegativeVeryThinSpace; - &NegativeThinSpace; - &NegativeMediumSpace; - &NegativeThickSpace; - &#x0200B; - &#8203; ]; /** * Remove completely some HTML entities from a string * @param {String} string * @return {String} */ export const unescapeFromString = (string: string) => { const toRemove = HTML_ENTITIES_TO_REMOVE_CHAR_CODES.map((charCode) => String.fromCharCode(charCode)); const regex = new RegExp(toRemove.join('|'), 'g'); return string.replace(regex, ''); };
8,744
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/sanitize/index.ts
export { input as sanitizeString, message, protonizer, content, html } from './purify';
8,745
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/sanitize/purify.ts
import DOMPurify, { Config } from 'dompurify'; import { escapeForbiddenStyle, escapeURLinStyle } from './escape'; const toMap = (list: string[]) => list.reduce<{ [key: string]: true | undefined }>((acc, key) => { acc[key] = true; return acc; }, {}); const LIST_PROTON_ATTR = ['data-src', 'src', 'srcset', 'background', 'poster', 'xlink:href', 'href']; const MAP_PROTON_ATTR = toMap(LIST_PROTON_ATTR); const PROTON_ATTR_TAG_WHITELIST = ['a', 'base', 'area']; const MAP_PROTON_ATTR_TAG_WHITELIST = toMap(PROTON_ATTR_TAG_WHITELIST.map((tag) => tag.toUpperCase())); const shouldPrefix = (tagName: string, attributeName: string) => { return !MAP_PROTON_ATTR_TAG_WHITELIST[tagName] && MAP_PROTON_ATTR[attributeName]; }; const CONFIG: { [key: string]: any } = { default: { ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|blob|xmpp|data):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i, // eslint-disable-line no-useless-escape ADD_TAGS: ['proton-src', 'base'], ADD_ATTR: ['target', 'proton-src'], FORBID_TAGS: ['style', 'input', 'form'], FORBID_ATTR: ['srcset', 'for'], // Accept HTML (official) tags only and automatically excluding all SVG & MathML tags USE_PROFILES: { html: true }, }, // When we display a message we need to be global and return more information raw: { WHOLE_DOCUMENT: true, RETURN_DOM: true }, html: { WHOLE_DOCUMENT: false, RETURN_DOM: true }, protonizer: { FORBID_TAGS: ['input', 'form'], // Override defaults to allow style (will be processed by juice afterward) FORBID_ATTR: {}, ADD_ATTR: ['target', ...LIST_PROTON_ATTR.map((attr) => `proton-${attr}`)], WHOLE_DOCUMENT: true, RETURN_DOM: true, }, content: { ALLOW_UNKNOWN_PROTOCOLS: true, WHOLE_DOCUMENT: false, RETURN_DOM: true, RETURN_DOM_FRAGMENT: true, }, contentWithoutImg: { ALLOW_UNKNOWN_PROTOCOLS: true, WHOLE_DOCUMENT: false, RETURN_DOM: true, RETURN_DOM_FRAGMENT: true, FORBID_TAGS: ['style', 'input', 'form', 'img'], }, }; const getConfig = (type: string): Config => ({ ...CONFIG.default, ...(CONFIG[type] || {}) }); /** * Rename some attributes adding the proton- prefix configured in LIST_PROTON_ATTR * Also escape urls in style attributes */ const beforeSanitizeElements = (node: Node) => { // We only work on elements if (node.nodeType !== 1) { return node; } const element = node as HTMLElement; // Manage styles element if (element.tagName === 'STYLE') { const escaped = escapeForbiddenStyle(escapeURLinStyle(element.innerHTML || '')); element.innerHTML = escaped; } Array.from(element.attributes).forEach((type) => { const item = type.name; if (shouldPrefix(element.tagName, item)) { element.setAttribute(`proton-${item}`, element.getAttribute(item) || ''); element.removeAttribute(item); } // Manage element styles tag if (item === 'style') { const escaped = escapeForbiddenStyle(escapeURLinStyle(element.getAttribute('style') || '')); element.setAttribute('style', escaped); } }); return element; }; const purifyHTMLHooks = (active: boolean) => { if (active) { DOMPurify.addHook('beforeSanitizeElements', beforeSanitizeElements); return; } DOMPurify.removeHook('beforeSanitizeElements'); }; const clean = (mode: string) => { const config = getConfig(mode); return (input: string | Node): string | Element => { DOMPurify.clearConfig(); const value = DOMPurify.sanitize(input, config) as string | Element; purifyHTMLHooks(false); // Always remove the hooks if (mode === 'str') { // When trusted types is available, DOMPurify returns a trustedHTML object and not a string, force cast it. return `${value}`; } return value; }; }; /** * Custom config only for messages */ export const message = clean('str') as (input: string) => string; /** * Sanitize input with a config similar than Squire + ours */ export const html = clean('raw') as (input: Node) => Element; /** * Sanitize input with a config similar than Squire + ours */ export const protonizer = (input: string, attachHooks: boolean): Element => { const process = clean('protonizer'); purifyHTMLHooks(attachHooks); return process(input) as Element; }; /** * Sanitize input and returns the whole document */ export const content = clean('content') as (input: string) => Node; /** * Sanitize input without images and returns the whole document */ export const contentWithoutImage = clean('contentWithoutImg') as (input: string) => Node; /** * Default config we don't want any custom behaviour */ export const input = (str: string) => { const result = DOMPurify.sanitize(str, {}); return `${result}`; }; /** * We don't want to display images inside the autoreply composer. * There is an issue on Firefox where images can still be added by drag&drop, * and squire is not able to detect them. That's why we are removing them here. */ export const removeImagesFromContent = (message: string) => { const div = document.createElement('div'); div.innerHTML = message; // Remove all images from the message const allImages = div.querySelectorAll('img'); allImages.forEach((img) => img.remove()); return { message: div.innerHTML, containsImages: allImages.length > 0 }; }; export const sanitizeSignature = (input: string) => { const process = clean('default'); return process(input.replace(/<a\s.*href="(.+?)".*>(.+?)<\/a>/, '[URL: $1] $2')); };
8,746
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/settings/helper.ts
import { WeekStartsOn } from '../date-fns-utc/interface'; import { browserDateLocale } from '../i18n'; import { getIsLocaleAMPM } from '../i18n/dateFnLocale'; import { SETTINGS_TIME_FORMAT, SETTINGS_WEEK_START, UserSettings } from '../interfaces'; export const getDefaultDateFormat = () => { return browserDateLocale.formatLong?.date({ width: 'short' }); }; export const getDefaultTimeFormat = () => { const isAMPM = getIsLocaleAMPM(browserDateLocale); return isAMPM ? SETTINGS_TIME_FORMAT.H12 : SETTINGS_TIME_FORMAT.H24; }; export const getDefaultWeekStartsOn = (): WeekStartsOn => { const localeWeekStartsOn = browserDateLocale?.options?.weekStartsOn; if (localeWeekStartsOn !== undefined && localeWeekStartsOn >= 0 && localeWeekStartsOn <= 6) { return localeWeekStartsOn; } return 0; }; export const getWeekStartsOn = ({ WeekStart }: Pick<UserSettings, 'WeekStart'>): WeekStartsOn => { if (WeekStart === SETTINGS_WEEK_START.LOCALE_DEFAULT) { return getDefaultWeekStartsOn(); } if (WeekStart >= 1 && WeekStart <= 7) { return (WeekStart % 7) as WeekStartsOn; } return 0; };
8,747
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/settings/twoFactor.ts
import { hasBit } from '../helpers/bitset'; import { generateSharedSecret, getUri } from '../helpers/twofa'; import { SETTINGS_2FA_ENABLED, UserSettings } from '../interfaces'; export const TWO_FA_CONFIG = { PERIOD: 30, DIGITS: 6, ALGORITHM: 'SHA1', }; export const getHasTOTPEnabled = (Enabled?: number) => { return hasBit(Enabled || 0, SETTINGS_2FA_ENABLED.OTP); }; export const getHasFIDO2Enabled = (Enabled?: number) => { return hasBit(Enabled || 0, SETTINGS_2FA_ENABLED.FIDO2); }; export const getHasTOTPSettingEnabled = (userSettings?: Pick<UserSettings, '2FA'>) => { return getHasTOTPEnabled(userSettings?.['2FA']?.Enabled); }; export const getHasFIDO2SettingEnabled = (userSettings?: Pick<UserSettings, '2FA'>) => { return getHasFIDO2Enabled(userSettings?.['2FA'].Enabled); }; export const getTOTPData = (identifier: string) => { const sharedSecret = generateSharedSecret(); const period = TWO_FA_CONFIG.PERIOD; const digits = TWO_FA_CONFIG.DIGITS; const uri = getUri({ identifier, issuer: 'Proton', sharedSecret, period, digits, algorithm: TWO_FA_CONFIG.ALGORITHM, }); return { sharedSecret, digits, period, uri, }; };
8,748
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/shortcuts/helpers.ts
import { isDialogOpen, isDropdownOpen, isEditing, isModalOpen } from '../busy'; import { isMac } from '../helpers/browser'; import { KeyboardKeyType } from '../interfaces'; const HTML_TAGS_TO_IGNORE = ['input', 'select', 'textarea', 'button', 'a']; export const isBusy = (e: KeyboardEvent) => { const { tagName, isContentEditable } = e.target as HTMLElement; return ( HTML_TAGS_TO_IGNORE.includes(tagName.toLowerCase()) || isContentEditable || isDialogOpen() || isModalOpen() || isDropdownOpen() || isEditing() ); }; export const isValidShortcut = (shortcut: KeyboardKeyType[], event: KeyboardEvent): boolean => { const shortcutKeys = shortcut.map((key) => key.toLowerCase()); const eventKey = event.key.toLowerCase(); const eventMetaKeyPressed = isMac() ? event.metaKey : event.ctrlKey; const eventShiftKeyPressed = event.shiftKey; const shouldNotPressMetaKey = !shortcutKeys.includes('meta') && eventMetaKeyPressed; const shouldNotPressShiftKey = !shortcutKeys.includes('shift') && eventShiftKeyPressed; if (shouldNotPressMetaKey || shouldNotPressShiftKey) { return false; } let isOk = shortcut.map(() => false); shortcutKeys.forEach((shortcutKey, index) => { if ( (shortcutKey === 'shift' && eventShiftKeyPressed) || (shortcutKey === 'meta' && eventMetaKeyPressed) || shortcutKey === eventKey ) { isOk[index] = true; return; } isOk[index] = false; }); if (isOk.every((item) => item === true)) { return true; } return false; };
8,749
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/shortcuts/mail.ts
import { c } from 'ttag'; import isTruthy from '@proton/utils/isTruthy'; import { altKey, isSafari as checkIsSafari, metaKey, shiftKey } from '../helpers/browser'; import { KeyboardKeyType } from '../interfaces'; export const editorShortcuts: Record<string, KeyboardKeyType[]> = { addAttachment: ['Meta', 'Shift', 'A'], addEncryption: ['Meta', 'Shift', 'E'], addExpiration: ['Meta', 'Shift', 'X'], addLink: ['Meta', 'K'], close: ['Escape'], deleteDraft: ['Meta', 'Alt', 'Backspace'], maximize: ['Meta', 'Shift', 'M'], minimize: ['Meta', 'M'], save: ['Meta', 'S'], send: ['Meta', 'Enter'], emojiPicker: ['Meta', 'E'] as KeyboardKeyType[], }; export const getShortcuts = () => { const isSafari = checkIsSafari(); return [ { name: c('Keyboard shortcut section name').t`Basic navigation`, alwaysActive: true, shortcuts: [ { name: c('Keyboard shortcut name').t`Move up`, keys: '↑', }, { name: c('Keyboard shortcut name').t`Jump to first`, keys: `${metaKey} + ↑`, }, { name: c('Keyboard shortcut name').t`Move down`, keys: '↓', }, { name: c('Keyboard shortcut name').t`Jump to last`, keys: `${metaKey} + ↓`, }, { name: c('Keyboard shortcut name').t`Move right / expand`, keys: '→', }, { name: c('Keyboard shortcut name').t`Move left / collapse`, keys: '←', }, ], }, { name: c('Keyboard shortcut section name').t`Basic actions`, alwaysActive: true, shortcuts: [ { name: c('Keyboard shortcut name').t`Apply / open`, keys: 'Enter', }, { name: c('Keyboard shortcut name').t`Cancel / close`, keys: 'Escape', }, { name: c('Keyboard shortcut name').t`Open this modal`, keys: '?', }, { name: c('Keyboard shortcut name').t`Select / unselect`, keys: 'Space', }, { name: c('Keyboard shortcut name').t`Open command panel`, keys: `${metaKey} + K`, }, ], }, { name: c('Keyboard shortcut section name').t`Folder shortcuts`, shortcuts: [ { name: c('Keyboard shortcut name').t`Go to Inbox`, keys: ['G', 'I'], }, { name: c('Keyboard shortcut name').t`Go to Archive`, keys: ['G', 'A'], }, { name: c('Keyboard shortcut name').t`Go to Sent`, keys: ['G', 'E'], }, { name: c('Keyboard shortcut name').t`Go to Starred`, keys: ['G', '*'], }, { name: c('Keyboard shortcut name').t`Go to Drafts`, keys: ['G', 'D'], }, { name: c('Keyboard shortcut name').t`Go to Trash`, keys: ['G', 'T'], }, { name: c('Keyboard shortcut name').t`Go to Spam`, keys: ['G', 'S'], }, { name: c('Keyboard shortcut name').t`Go to All Mail`, keys: ['G', 'M'], }, ], }, { name: c('Keyboard shortcut section name').t`Composer shortcuts`, shortcuts: [ { name: c('Keyboard shortcut name').t`Save draft`, keys: `${metaKey} + S`, }, { name: c('Keyboard shortcut name').t`Send email`, keys: `${metaKey} + Enter`, }, { name: c('Keyboard shortcut name').t`Close draft`, keys: `Escape`, }, !isSafari && { name: c('Keyboard shortcut name').t`Minimize / maximize composer`, keys: `${metaKey} + M`, }, !isSafari && { name: c('Keyboard shortcut name').t`Expand / contract composer`, keys: `${metaKey} + ${shiftKey} + M`, }, { name: c('Keyboard shortcut name').t`Attach file`, keys: `${metaKey} + ${shiftKey} + A`, }, { name: c('Keyboard shortcut name').t`Add expiration time`, keys: `${metaKey} + ${shiftKey} + X`, }, { name: c('Keyboard shortcut name').t`Add encryption`, keys: `${metaKey} + ${shiftKey} + E`, }, { name: c('Keyboard shortcut name').t`Insert link`, keys: `${metaKey} + K`, }, { name: c('Keyboard shortcut name').t`Discard draft`, keys: `${metaKey} + ${altKey} + Backspace`, }, ].filter(isTruthy), }, { name: c('Keyboard shortcut section name').t`List shortcuts`, shortcuts: [ { name: c('Keyboard shortcut name').t`Open previous message`, keys: 'K', }, { name: c('Keyboard shortcut name').t`Open next message`, keys: 'J', }, { name: c('Keyboard shortcut name').t`Select / unselect`, keys: 'X', }, { name: c('Keyboard shortcut name').t`Show unread emails`, keys: `${shiftKey} + U`, }, { name: c('Keyboard shortcut name').t`Show all emails`, keys: `${shiftKey} + A`, }, { name: c('Keyboard shortcut name').t`Select / unselect all`, keys: `${metaKey} + A`, }, { name: c('Keyboard shortcut name').t`Search`, keys: '/', }, ], }, { name: c('Keyboard shortcut section name').t`Action shortcuts`, shortcuts: [ { name: c('Keyboard shortcut name').t`New message`, keys: 'N', }, { name: c('Keyboard shortcut name').t`Star`, keys: '*', }, { name: c('Keyboard shortcut name').t`Mark as unread`, keys: 'U', }, { name: c('Keyboard shortcut name').t`Mark as read`, keys: 'R', }, { name: c('Keyboard shortcut name').t`Label as...`, keys: 'L', }, { name: c('Keyboard shortcut name').t`Move to...`, keys: 'M', }, { name: c('Keyboard shortcut name').t`Move to Inbox`, keys: 'I', }, { name: c('Keyboard shortcut name').t`Move to Archive`, keys: 'A', }, { name: c('Keyboard shortcut name').t`Move to Spam`, keys: 'S', }, { name: c('Keyboard shortcut name').t`Move to Trash`, keys: 'T', }, { name: c('Keyboard shortcut name').t`Delete permanently`, keys: `${metaKey} + Backspace`, }, ], }, { name: c('Keyboard shortcut section name').t`Message shortcuts`, shortcuts: [ { name: c('Keyboard shortcut name').t`Reply`, keys: 'R', }, { name: c('Keyboard shortcut name').t`Reply all`, keys: `${shiftKey} + R`, }, { name: c('Keyboard shortcut name').t`Forward`, keys: `${shiftKey} + F`, }, { name: c('Keyboard shortcut name').t`Load remote content`, keys: `${shiftKey} + C`, }, { name: c('Keyboard shortcut name').t`Load embedded images`, keys: `${shiftKey} + E`, }, { name: c('Keyboard shortcut name').t`Show original message`, keys: 'O', }, ], }, ]; };
8,750
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/spotlight/helpers.ts
import { EnvironmentExtended } from '@proton/shared/lib/interfaces'; import { SpotlightDate } from '@proton/shared/lib/spotlight/interface'; export const getEnvironmentDate = ( currentEnvironment: EnvironmentExtended | undefined, spotlightDates: SpotlightDate ) => { if (currentEnvironment) { const environmentDate = spotlightDates[currentEnvironment]; if (environmentDate !== undefined) { return environmentDate; } } return spotlightDates.default; };
8,751
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/spotlight/interface.ts
export interface SpotlightDate { default: number; beta?: number; alpha?: number; }
8,752
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/subscription/format.js
import { isManagedByMozilla } from './helpers'; /** * @param {*} subscription * @param {*} [UpcomingSubscription] * @returns {import('../interfaces').SubscriptionModel} */ const format = (subscription = {}, UpcomingSubscription) => { return { ...subscription, UpcomingSubscription, isManagedByMozilla: isManagedByMozilla(subscription), }; }; export default format;
8,753
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/subscription/freePlans.ts
import { CYCLE, DEFAULT_CURRENCY, DEFAULT_CYCLE, PLANS, PLAN_SERVICES, PLAN_TYPES } from '../constants'; import { Currency, Cycle, Plan, SubscriptionCheckResponse } from '../interfaces'; export const FREE_PLAN = { ID: 'free', Name: 'free' as PLANS, Title: `Proton Free`, Type: PLAN_TYPES.PLAN, Currency: DEFAULT_CURRENCY, Cycle: DEFAULT_CYCLE, Amount: 0, MaxDomains: 0, MaxAddresses: 1, MaxSpace: 524288000, MaxMembers: 0, MaxVPN: 1, MaxTier: 0, Services: PLAN_SERVICES.MAIL + PLAN_SERVICES.VPN, Quantity: 1, State: 1, Features: 0, Pricing: { [CYCLE.MONTHLY]: 0, [CYCLE.YEARLY]: 0, [CYCLE.TWO_YEARS]: 0, [CYCLE.THIRTY]: 0, [CYCLE.FIFTEEN]: 0, }, } as Plan; export const getFreeCheckResult = ( currency: Currency = DEFAULT_CURRENCY, cycle: Cycle = DEFAULT_CYCLE ): SubscriptionCheckResponse => { return { Amount: 0, AmountDue: 0, Proration: 0, Credit: 0, Currency: currency, Cycle: cycle, Gift: 0, CouponDiscount: 0, Coupon: null, Additions: null, PeriodEnd: 0, }; };
8,754
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/subscription/helpers.ts
import { PLAN_TYPES } from '../constants'; export const isManagedByMozilla = ({ CouponCode }: { CouponCode?: string | null } = {}) => { const coupon = CouponCode || ''; // CouponCode can be null return coupon.startsWith('MOZILLA') || coupon.startsWith('MOZTEST'); }; interface SubcriptionPlan { Type: PLAN_TYPES; Title: string; } export const getSubscriptionPlans = <P extends SubcriptionPlan>({ Plans = [] }: { Plans: P[] }) => Plans.filter(({ Type }) => Type === PLAN_TYPES.PLAN); export const getSubscriptionTitle = <P extends SubcriptionPlan>({ Plans = [] }: { Plans: P[] }) => { return getSubscriptionPlans({ Plans }) .map(({ Title }) => Title) .join(', '); };
8,755
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/subscription/redirect.ts
export const getRedirect = (redirect: string | null | undefined) => { return redirect && /^(\/$|\/[^/]|proton(vpn|mail|drive)?:\/\/)/.test(redirect) ? redirect : undefined; };
8,756
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/supported/interface.ts
export const enum SupportedBrowserValue { Unsupported = 0, Supported = 1, Other = -1, } declare global { interface Window { protonSupportedBrowser: SupportedBrowserValue | undefined; } }
8,757
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/supported/pre.ts
import { SupportedBrowserValue } from './interface'; const preScriptNode = document.querySelector<HTMLScriptElement>('script[src*="/pre"]'); // The tag that we're interested in is the main script file. Normally that's index.js but there's also lite and eo take // into account and we fallback to the nextSibling in those scenarios since pre.js is supposed to be first. const scriptNode = document.querySelector<HTMLScriptElement>('script[src*="/index"]') || (preScriptNode?.nextSibling as HTMLScriptElement); if (scriptNode) { scriptNode.onerror = () => { window.protonSupportedBrowser = SupportedBrowserValue.Other; }; scriptNode.onload = () => { if (window.protonSupportedBrowser === undefined) { window.protonSupportedBrowser = SupportedBrowserValue.Unsupported; } }; }
8,758
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/supported/supported.ts
import { SupportedBrowserValue } from './interface'; /** * This file is included in the main bundle. Its main purpose is to find out if the main bundle could execute, * or if it errored out due to a Syntax Error since the main bundle is only compiled against a specific list * of browsers. We also check some specific browsers here. * The unsupported.js script is included as another script tag and relies on this variable. */ const isUnsupported = () => { // IE11 or old edge (not chromium based) are not supported. const isOldEdgeOrIE = !('reversed' in document.createElement('ol')); // If these function get polyfilled they'll exist, this is a safety mechanism for when we stop supporting it return isOldEdgeOrIE || !Object.fromEntries || !''.trimStart || !window.crypto.subtle; }; window.protonSupportedBrowser = isUnsupported() ? SupportedBrowserValue.Unsupported : SupportedBrowserValue.Supported;
8,759
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/supported/unsupported.ts
// eslint-disable-next-line import/no-unresolved import errorImg from '@proton/styles/assets/img/errors/error-generic.svg'; import unsupportedBrowser from '@proton/styles/assets/img/errors/unsupported-browser.svg'; import { SupportedBrowserValue } from './interface'; const showUnsupported = () => { const isProtonVPN = (document.location.origin || document.location.href).indexOf('protonvpn') !== -1; const hostname = document.location.hostname; const kbUrl = isProtonVPN ? 'https://protonvpn.com/support/browsers-supported/' : `https://${hostname.slice(hostname.indexOf('.') + 1)}/support/recommended-browsers`; // Not using getKnowledgeBaseUrl( to minimize the bundle size since it apparently doesn't tree-shake the bundle correctly and adds an extra 40k document.body.innerHTML = ` <div class='h-full flex flex-align-items-center pb-14 scroll-if-needed'> <div class='m-auto text-center max-w-custom' style='--max-w-custom: 30em'> <h1 class='text-bold text-4xl'>Unsupported browser</h1> <p> You are using an unsupported browser. Please update it to the latest version or use a different browser. </p> <a class='primary-link bold' target='_blank' rel='noopener noreferrer' href='${kbUrl}'>More info</a> <div class='mt-8'> <img src='${unsupportedBrowser}' alt='Unsupported browser'/> </div> </div> </div> `; document.title = 'Unsupported browser'; }; const showError = () => { document.body.innerHTML = ` <div class='h-full flex flex-align-items-center pb-14 scroll-if-needed'> <div class='m-auto text-center max-w-custom' style='--max-w-custom: 30em'> <div class='mb-8'> <img src='${errorImg}' alt='Error'/> </div> <h1 class='text-bold text-4xl'>Oops, something went wrong</h1> <p> Please <button id='refresh' class='link align-baseline'>refresh the page</button> or try again later. </p> </div> </div> `; document.querySelector<HTMLButtonElement>('#refresh')?.addEventListener('click', () => { window.location.reload(); }); document.title = 'Oops, something went wrong'; }; const run = () => { if (window.protonSupportedBrowser === SupportedBrowserValue.Unsupported) { showUnsupported(); /* * undefined equality is also checked because the `onerror` handler is called immediately on failures in firefox, and not * after execution has started like it does on webkit. so if the index.js file fails before the pre.js file has * gotten parsed, the handler never triggers. so it assumes that undefined means network failure. the `onload` behavior seems * different and is executed in order, so parsing failures should always happen through the onload handler (in pre.js) * which would set it to 0. */ } else if ( window.protonSupportedBrowser === SupportedBrowserValue.Other || window.protonSupportedBrowser === undefined ) { showError(); } }; // In a timeout to avoid race conditions with the onerror handler window.setTimeout(run, 33);
8,760
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/themes/helpers.ts
import { DARK_MODE_CLASS } from '../constants'; /** * Given a theme, return true if it corresponds to dark mode, false otherwise */ export const isDarkTheme = () => { return document.body.classList.contains(DARK_MODE_CLASS); };
8,761
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/themes/themes.ts
import { c } from 'ttag'; // @ts-ignore import carbonTheme from '@proton/colors/themes/dist/carbon.theme.css'; // @ts-ignore import classicTheme from '@proton/colors/themes/dist/classic.theme.css'; // @ts-ignore import contrastDarkTheme from '@proton/colors/themes/dist/contrast-dark.theme.css'; // @ts-ignore import contrastLightTheme from '@proton/colors/themes/dist/contrast-light.theme.css'; // @ts-ignore import duotoneTheme from '@proton/colors/themes/dist/duotone.theme.css'; // @ts-ignore import legacyTheme from '@proton/colors/themes/dist/legacy.theme.css'; // @ts-ignore import monokaiTheme from '@proton/colors/themes/dist/monokai.theme.css'; // @ts-ignore import passTheme from '@proton/colors/themes/dist/pass.theme.css'; // @ts-ignore import snowTheme from '@proton/colors/themes/dist/snow.theme.css'; import { decodeBase64URL, encodeBase64URL } from '@proton/shared/lib/helpers/encoding'; export enum ThemeTypes { Duotone = 0, Carbon = 1, Snow = 2, Monokai = 3, ContrastLight = 4, Legacy = 5, Classic = 6, ContrastDark = 7, Pass = 8, } export const PROTON_DEFAULT_THEME = ThemeTypes.Duotone; export const PROTON_THEMES_MAP = { [ThemeTypes.Duotone]: { label: 'Proton', identifier: ThemeTypes.Duotone, thumbColors: { prominent: '#44348C', standard: '#ffffff', primary: '#936DFF', weak: '#9186BE', }, theme: duotoneTheme.toString(), }, [ThemeTypes.Carbon]: { label: 'Carbon', identifier: ThemeTypes.Carbon, thumbColors: { prominent: '#372E45', standard: '#453C56', primary: '#936DFF', weak: '#7A6E80', }, theme: carbonTheme.toString(), }, [ThemeTypes.Monokai]: { label: 'Monokai', identifier: ThemeTypes.Monokai, thumbColors: { prominent: '#16141C', standard: '#2B293D', primary: '#D3597B', weak: '#706878', }, theme: monokaiTheme.toString(), }, [ThemeTypes.Snow]: { label: 'Snow', identifier: ThemeTypes.Snow, thumbColors: { prominent: '#FFFFFF', standard: '#FAF8F6', primary: '#6D4AFF', weak: '#C7C4C1', }, theme: snowTheme.toString(), }, [ThemeTypes.ContrastLight]: { label: 'Ivory', identifier: ThemeTypes.ContrastLight, thumbColors: { prominent: '#FFFFFF', standard: '#FAF8F6', primary: '#4E33BF', weak: '#333333', }, theme: contrastLightTheme.toString(), }, [ThemeTypes.ContrastDark]: { label: 'Ebony', identifier: ThemeTypes.ContrastDark, thumbColors: { prominent: '#131313', standard: '#000000', primary: '#8C94FD', weak: '#555555', }, theme: contrastDarkTheme.toString(), }, [ThemeTypes.Legacy]: { label: 'Legacy', identifier: ThemeTypes.Legacy, thumbColors: { prominent: '#535364', standard: '#F5F5F5', primary: '#9498CB', weak: '#BABAC1', }, theme: legacyTheme.toString(), }, [ThemeTypes.Classic]: { label: 'Classic', identifier: ThemeTypes.Classic, thumbColors: { prominent: '#282F54', standard: '#F5F4F2', primary: '#6A7FE0', weak: '#585E78', }, theme: classicTheme.toString(), }, [ThemeTypes.Pass]: { label: 'Pass', identifier: ThemeTypes.Pass, thumbColors: { prominent: '#16141C', standard: '#2A2833', primary: '#6D4AFF', weak: '#6c6b70', }, theme: passTheme.toString(), }, } as const; export const getDarkThemes = () => [ThemeTypes.Carbon, ThemeTypes.Monokai, ThemeTypes.ContrastDark, ThemeTypes.Pass]; export const getProminentHeaderThemes = () => [ThemeTypes.Classic, ThemeTypes.Legacy]; export const getThemes = () => { return [ ThemeTypes.Duotone, ThemeTypes.Classic, ThemeTypes.Snow, ThemeTypes.Legacy, ThemeTypes.Carbon, ThemeTypes.Monokai, ThemeTypes.ContrastDark, ThemeTypes.ContrastLight, ].map((id) => PROTON_THEMES_MAP[id]); }; export enum ThemeModeSetting { Auto, Dark, Light, } export enum ColorScheme { Dark, Light, } export enum MotionModeSetting { No_preference, Reduce, } export enum ThemeFontSizeSetting { DEFAULT = 0, X_SMALL, SMALL, LARGE, X_LARGE, } interface ThemeFontSizeSettingValue { label: () => string; value: number; } export const ThemeFontSizeSettingMap: { [key in ThemeFontSizeSetting]: ThemeFontSizeSettingValue } = { [ThemeFontSizeSetting.X_SMALL]: { label: () => c('Font size option').t`Very small`, value: 10, }, [ThemeFontSizeSetting.SMALL]: { label: () => c('Font size option').t`Small`, value: 12, }, [ThemeFontSizeSetting.DEFAULT]: { label: () => c('Font size option').t`Medium (recommended)`, value: 14, }, [ThemeFontSizeSetting.LARGE]: { label: () => c('Font size option').t`Large`, value: 16, }, [ThemeFontSizeSetting.X_LARGE]: { label: () => c('Font size option').t`Very large`, value: 18, }, }; export const getThemeFontSizeEntries = () => { return Object.entries(ThemeFontSizeSettingMap) .map(([key, value]): [ThemeFontSizeSetting, ThemeFontSizeSettingValue] => { const themeFontSizeSettingKey: ThemeFontSizeSetting = Number(key); return [themeFontSizeSettingKey, value]; }) .sort((a, b) => a[1].value - b[1].value); }; export enum ThemeFontFaceSetting { DEFAULT, SYSTEM, ARIAL, TIMES, DYSLEXIC, } interface ThemeFontFaceSettingValue { label: () => string; value: string | null; } export const ThemeFontFaceSettingMap: { [key in ThemeFontFaceSetting]: ThemeFontFaceSettingValue } = { [ThemeFontFaceSetting.DEFAULT]: { label: () => { /* translator: This is the text proposed in a dropdown menu in the Accessibility settings. Here the user can choose the "Font family", and this string proposes the choice of "Theme font", the font of the chosen theme. */ return c('Font face option').t`Theme font`; }, value: null, }, [ThemeFontFaceSetting.SYSTEM]: { label: () => { /* translator: This is the text proposed in a dropdown menu in the Accessibility settings. Here the user can choose the "Font family", and this string proposes the choice of "System default", the default font of the user's operating system. */ return c('Font face option').t`System default`; }, value: 'system-ui, sans-serif', }, [ThemeFontFaceSetting.ARIAL]: { label: () => 'Arial', value: 'Arial, Helvetica, sans-serif', }, [ThemeFontFaceSetting.TIMES]: { label: () => 'Times New Roman', value: "'Times New Roman', Times, serif", }, [ThemeFontFaceSetting.DYSLEXIC]: { label: () => 'OpenDyslexic', value: 'OpenDyslexic, cursive', }, }; export const getThemeFontFaceEntries = () => { return Object.entries(ThemeFontFaceSettingMap).map( ([key, value]): [ThemeFontFaceSetting, ThemeFontFaceSettingValue] => { const themeFontFaceSettingKey: ThemeFontFaceSetting = Number(key); return [themeFontFaceSettingKey, value]; } ); }; export enum ThemeFeatureSetting { DEFAULT, SCROLLBARS_OFF, ANIMATIONS_OFF, } export interface ThemeSetting { Mode: ThemeModeSetting; LightTheme: ThemeTypes; DarkTheme: ThemeTypes; FontSize: ThemeFontSizeSetting; FontFace: ThemeFontFaceSetting; Features: ThemeFeatureSetting; } export const getDefaultThemeSetting = (themeType?: ThemeTypes): ThemeSetting => { return { Mode: ThemeModeSetting.Light, LightTheme: themeType || PROTON_DEFAULT_THEME, DarkTheme: ThemeTypes.Carbon, FontSize: ThemeFontSizeSetting.DEFAULT, FontFace: ThemeFontFaceSetting.DEFAULT, Features: ThemeFeatureSetting.DEFAULT, }; }; const getValidatedThemeType = (themeType: number): ThemeTypes | undefined => { if (themeType >= ThemeTypes.Duotone && themeType <= ThemeTypes.ContrastDark) { return themeType; } }; const getParsedThemeType = (maybeThemeType: any): ThemeTypes | undefined => { return getValidatedThemeType(Number(maybeThemeType)); }; const getValidatedThemeMode = (maybeThemeMode: number | undefined): ThemeModeSetting | undefined => { if ( maybeThemeMode !== undefined && maybeThemeMode >= ThemeModeSetting.Auto && maybeThemeMode <= ThemeModeSetting.Light ) { return maybeThemeMode; } }; const getValidatedFontSize = (maybeFontSize: number | undefined) => { if ( maybeFontSize !== undefined && maybeFontSize >= ThemeFontSizeSetting.DEFAULT && maybeFontSize <= ThemeFontSizeSetting.X_LARGE ) { return maybeFontSize; } }; const getValidatedFontFace = (maybeFontFace: number | undefined) => { if ( maybeFontFace !== undefined && maybeFontFace >= ThemeFontFaceSetting.DEFAULT && maybeFontFace <= ThemeFontFaceSetting.DYSLEXIC ) { return maybeFontFace; } }; const getValidatedFeatures = (maybeFeatures: number | undefined) => { if (maybeFeatures !== undefined && maybeFeatures >= 0 && maybeFeatures <= 32) { return maybeFeatures; } }; export const getParsedThemeSetting = (storedThemeSetting: string | undefined): ThemeSetting => { // The theme cookie used to contain just the theme number type. if (storedThemeSetting && storedThemeSetting?.length === 1) { const maybeParsedThemeType = getParsedThemeType(storedThemeSetting); if (maybeParsedThemeType !== undefined) { return getDefaultThemeSetting(maybeParsedThemeType); } } const defaultThemeSetting = getDefaultThemeSetting(PROTON_DEFAULT_THEME); // Now it contains JSON if (storedThemeSetting && storedThemeSetting?.length >= 10) { try { const parsedTheme: any = JSON.parse(decodeBase64URL(storedThemeSetting)); return { Mode: getValidatedThemeMode(parsedTheme.Mode) ?? defaultThemeSetting.Mode, LightTheme: getValidatedThemeType(parsedTheme.LightTheme) ?? defaultThemeSetting.LightTheme, DarkTheme: getValidatedThemeType(parsedTheme.DarkTheme) ?? defaultThemeSetting.DarkTheme, FontFace: getValidatedFontSize(parsedTheme.FontFace) ?? defaultThemeSetting.FontFace, FontSize: getValidatedFontFace(parsedTheme.FontSize) ?? defaultThemeSetting.FontSize, Features: getValidatedFeatures(parsedTheme.Features) ?? defaultThemeSetting.Features, }; } catch (e: any) {} } return defaultThemeSetting; }; const getDiff = (a: ThemeSetting, b: ThemeSetting): Partial<ThemeSetting> => { return Object.entries(a).reduce<Partial<ThemeSetting>>((acc, [_key, value]) => { const key = _key as keyof ThemeSetting; const otherValue = b[key] as any; if (value !== otherValue) { acc[key] = otherValue; } return acc; }, {}); }; export const serializeThemeSetting = (themeSetting: ThemeSetting) => { const diff = getDiff(getDefaultThemeSetting(), themeSetting); const keys = Object.keys(diff) as (keyof ThemeSetting)[]; if (!keys.length) { return; } if (keys.length === 1 && keys[0] === 'LightTheme') { return `${diff.LightTheme}`; } return encodeBase64URL(JSON.stringify(diff)); }; export const getThemeType = (theme: ThemeSetting, colorScheme: ColorScheme): ThemeTypes => { let value: ThemeTypes; switch (theme.Mode) { case ThemeModeSetting.Auto: value = colorScheme === ColorScheme.Dark ? theme.DarkTheme : theme.LightTheme; break; case ThemeModeSetting.Dark: value = theme.DarkTheme; break; default: case ThemeModeSetting.Light: value = theme.LightTheme; break; } return getValidatedThemeType(value) ?? PROTON_DEFAULT_THEME; };
8,762
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/user/format.ts
import { User } from '@proton/shared/lib/interfaces'; import { canPay, isAdmin, isFree, isMember, isPaid } from './helpers'; const format = (user: User) => { return { ...user, isFree: isFree(user), isPaid: isPaid(user), isAdmin: isAdmin(user), isMember: isMember(user), canPay: canPay(user), }; }; export default format;
8,763
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/user/helpers.ts
import { PRODUCT_BIT, UNPAID_STATE, USER_ROLES } from '../constants'; import { hasBit } from '../helpers/bitset'; import { decodeBase64URL } from '../helpers/encoding'; import { User } from '../interfaces'; const { ADMIN_ROLE, MEMBER_ROLE, FREE_ROLE } = USER_ROLES; export const hasPaidMail = (user: User) => hasBit(user.Subscribed, PRODUCT_BIT.Mail); export const hasPaidDrive = (user: User) => hasBit(user.Subscribed, PRODUCT_BIT.Drive); export const hasPaidVpn = (user: User) => hasBit(user.Subscribed, PRODUCT_BIT.VPN); export const hasPaidPass = (user: User) => hasBit(user.Subscribed, PRODUCT_BIT.PASS); export const isPaid = (user: User) => !!user.Subscribed; export const isPrivate = (user: User) => user.Private === 1; export const isFree = (user: User) => !isPaid(user); export const isAdmin = (user: User) => user.Role === ADMIN_ROLE; export const isMember = (user: User) => user.Role === MEMBER_ROLE; export const isSubUser = (user: User) => typeof user.OrganizationPrivateKey !== 'undefined'; export const isDelinquent = (user: User) => !!user.Delinquent; export const getHasNonDelinquentScope = (user: User) => user.Delinquent < UNPAID_STATE.DELINQUENT; export const canPay = (user: User) => [ADMIN_ROLE, FREE_ROLE].includes(user.Role) && !isSubUser(user); export const getInfo = (User: User) => { return { isAdmin: isAdmin(User), isMember: isMember(User), isFree: isFree(User), isPaid: isPaid(User), isPrivate: isPrivate(User), isSubUser: isSubUser(User), isDelinquent: isDelinquent(User), hasNonDelinquentScope: getHasNonDelinquentScope(User), hasPaidMail: hasPaidMail(User), hasPaidVpn: hasPaidVpn(User), hasPaidDrive: hasPaidDrive(User), canPay: canPay(User), }; }; export const getUserByte = (user: User) => { const userID = user?.ID || ''; const byteCharacters = decodeBase64URL(userID); return byteCharacters.charCodeAt(0); };
8,764
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/vpn/features.ts
import { c, msgid } from 'ttag'; export const getServersInWithoutPlus = (numberOfServers: string, numberOfCountries: number) => { // translator: numberOfServers is a string that looks like `20 servers`. It has been pluralized earlier. return c('VPN Plan Feature').ngettext( msgid`${numberOfServers} in ${numberOfCountries} country`, `${numberOfServers} in ${numberOfCountries} countries`, numberOfCountries ); }; export const getServersIn = (numberOfServers: string, numberOfCountries: number) => { // translator: numberOfServers is a string that looks like `1300+ servers`, It has been pluralized earlier. return c('VPN Plan Feature').ngettext( msgid`${numberOfServers} across ${numberOfCountries} country`, `${numberOfServers} across ${numberOfCountries}+ countries`, numberOfCountries ); }; export const getVpnConnections = (n = 0) => { return c('VPN Plan Feature').ngettext(msgid`${n} VPN connection`, `${n} VPN connections`, n); }; export const getVpnServers = (n = 0) => { return c('VPN Plan Feature').ngettext(msgid`${n} server`, `${n}+ servers`, n); }; export const getVpnServersWithoutPlus = (n = 0) => { return c('VPN Plan Feature').ngettext(msgid`${n} server`, `${n} servers`, n); }; export const getPlusServers = (servers = 1300, countries = 0) => { return getServersIn(getVpnServers(servers), countries); }; export const getBasicServers = (servers = 350, countries = 0) => { return getServersIn(getVpnServers(servers), countries); }; export const getFreeServers = (servers = 0, countries = 0) => { return getServersInWithoutPlus(getVpnServersWithoutPlus(servers), countries); };
8,765
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/webauthn/create.ts
import { arrayToBinaryString, encodeBase64 } from '@proton/crypto/lib/utils'; import { PublicKeyCredentialCreationOptionsSerialized, RegisterCredentials, RegisterCredentialsPayload, } from './interface'; export * from './interface'; const convertCreationToExpectedFormat = ( publicKey: PublicKeyCredentialCreationOptionsSerialized ): CredentialCreationOptions => { const { challenge, user, excludeCredentials, ...rest } = publicKey; return { publicKey: { ...rest, challenge: new Uint8Array(challenge).buffer, user: { ...user, id: new Uint8Array(user.id), }, excludeCredentials: excludeCredentials?.map((credentials) => ({ ...credentials, id: new Uint8Array(credentials.id), })), }, }; }; export const getCreatePayload = async ( registerCredentials: RegisterCredentials ): Promise<RegisterCredentialsPayload> => { const credentialCreationOptions = convertCreationToExpectedFormat( registerCredentials.RegistrationOptions.publicKey ); const credentials = await navigator.credentials.create(credentialCreationOptions); const publicKeyCredentials = credentials as PublicKeyCredential; if (!credentials || !('rawId' in credentials) || !('attestationObject' in publicKeyCredentials.response)) { throw new Error('No credentials received'); } const response = publicKeyCredentials.response as AuthenticatorAttestationResponse & { getTransports: () => string[]; }; return { RegistrationOptions: registerCredentials.RegistrationOptions, ClientData: response.clientDataJSON ? encodeBase64(arrayToBinaryString(new Uint8Array(response.clientDataJSON))) : null!, AttestationObject: response.attestationObject ? encodeBase64(arrayToBinaryString(new Uint8Array(response.attestationObject))) : null!, Transports: response.getTransports?.() || [], Name: '', }; };
8,766
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/webauthn/get.ts
import { arrayToBinaryString, encodeBase64 } from '@proton/crypto/lib/utils'; import { AuthenticationCredentialsPayload, AuthenticationOptions, PublicKeyCredentialRequestOptionsSerialized, } from './interface'; export * from './interface'; const convertRequestToExpectedFormat = ( publicKey: PublicKeyCredentialRequestOptionsSerialized ): CredentialRequestOptions => { const { challenge, allowCredentials, ...rest } = publicKey; return { publicKey: { ...rest, challenge: new Uint8Array(challenge).buffer, allowCredentials: allowCredentials?.map((credentials) => ({ ...credentials, id: new Uint8Array(credentials.id), })), }, }; }; export const getAuthentication = async ( authenticationOptions: AuthenticationOptions ): Promise<AuthenticationCredentialsPayload> => { const credentialRequestOptions = convertRequestToExpectedFormat(authenticationOptions.publicKey); const credentials = await navigator.credentials.get(credentialRequestOptions); const publicKeyCredentials = credentials as PublicKeyCredential; if (!credentials || !('rawId' in credentials)) { throw new Error('No credentials received, unsupported browser'); } const response = publicKeyCredentials.response as AuthenticatorAttestationResponse & { signature: ArrayBuffer; authenticatorData: ArrayBuffer; }; return { AuthenticationOptions: authenticationOptions, ClientData: response.clientDataJSON ? encodeBase64(arrayToBinaryString(new Uint8Array(response.clientDataJSON))) : null!, AuthenticatorData: response.authenticatorData ? encodeBase64(arrayToBinaryString(new Uint8Array(response.authenticatorData))) : null!, Signature: response.signature ? encodeBase64(arrayToBinaryString(new Uint8Array(response.signature))) : null!, CredentialID: publicKeyCredentials.rawId ? [...new Uint8Array(publicKeyCredentials.rawId)] : null!, }; };
8,767
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/webauthn/helper.ts
import { APPS, APP_NAMES } from '@proton/shared/lib/constants'; import { getHasWebAuthnSupport } from '@proton/shared/lib/helpers/browser'; export const getHasFIDO2Support = (appName: APP_NAMES, hostname: string) => { // Explicitly not testing the production domain for test domain support return appName === APPS.PROTONACCOUNT && !hostname.endsWith('.onion') && getHasWebAuthnSupport(); };
8,768
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/webauthn/id.ts
import { encodeBase64URL, uint8ArrayToString } from '@proton/shared/lib/helpers/encoding'; import { RegisteredKey } from '@proton/shared/lib/webauthn/interface'; export const getId = (registeredKey: RegisteredKey) => { return encodeBase64URL(uint8ArrayToString(new Uint8Array(registeredKey.CredentialID))); };
8,769
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/webauthn/interface.ts
export interface PublicKeyCredentialUserEntitySerialized extends Omit<PublicKeyCredentialUserEntity, 'id'> { id: number[]; } export interface PublicKeyCredentialDescriptorSerialized extends Omit<PublicKeyCredentialDescriptor, 'id'> { id: number[]; } export interface PublicKeyCredentialCreationOptionsSerialized extends Omit<PublicKeyCredentialCreationOptions, 'challenge' | 'user' | 'excludeCredentials'> { challenge: number[]; user: PublicKeyCredentialUserEntitySerialized; excludeCredentials?: PublicKeyCredentialDescriptorSerialized[]; } export interface RegistrationOptions { publicKey: PublicKeyCredentialCreationOptionsSerialized; } export interface PublicKeyCredentialRequestOptionsSerialized extends Omit<PublicKeyCredentialRequestOptions, 'challenge' | 'allowCredentials'> { challenge: number[]; allowCredentials: PublicKeyCredentialDescriptorSerialized[]; } export interface AuthenticationOptions { publicKey: PublicKeyCredentialRequestOptionsSerialized; } export enum AttestationFormat { None = 'none', AndroidKey = 'android-key', AndroidSafetyNet = 'android-safetynet', Apple = 'apple', FidoU2F = 'fido-u2f', Packed = 'packed', TPM = 'tpm', } export interface RegisteredKey { AttestationFormat: AttestationFormat; CredentialID: number[]; Name: string; } export interface RegisterCredentials { RegisteredKeys: RegisteredKey[]; RegistrationOptions: RegistrationOptions; AttestationFormats: AttestationFormat[]; } export interface RegisterCredentialsPayload { RegistrationOptions: RegistrationOptions; ClientData: string; AttestationObject: string; Transports: string[]; Name: string; } export interface AuthenticationCredentialsPayload { AuthenticationOptions: AuthenticationOptions; ClientData: string; AuthenticatorData: string; Signature: string; CredentialID: number[]; }
8,770
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/window/index.ts
/* * Need to keep a reference of the window object so that we can mock it during unit tests. * In order to avoid breaking non-window contexts (ie: service workers) expose the globalThis object */ export default globalThis;
8,771
0
petrpan-code/ProtonMail/WebClients/packages/shared
petrpan-code/ProtonMail/WebClients/packages/shared/test/index.spec.js
import { CryptoProxy } from '@proton/crypto'; import { Api as CryptoApi } from '@proton/crypto/lib/worker/api'; // Initialize CryptoProxy using a non-worker endpoint CryptoProxy.setEndpoint(new CryptoApi(), (endpoint) => endpoint.clearKeyStore()); (function (defineProperty) { Object.defineProperty = (obj, prop, desc) => { desc.configurable = true; return defineProperty(obj, prop, desc); }; })(Object.defineProperty); const testsContext = require.context('.', true, /.spec.(js|tsx?)$/); testsContext.keys().forEach(testsContext);
8,772
0
petrpan-code/ProtonMail/WebClients/packages/shared
petrpan-code/ProtonMail/WebClients/packages/shared/test/karma.conf.js
const karmaJasmine = require('karma-jasmine'); const karmaWebpack = require('karma-webpack'); const karmaSpecReporter = require('karma-spec-reporter'); const karmaChromeLauncher = require('karma-chrome-launcher'); const { chromium } = require('playwright'); process.env.CHROME_BIN = chromium.executablePath(); module.exports = (config) => { config.set({ basePath: '..', frameworks: ['jasmine', 'webpack'], plugins: [karmaJasmine, karmaWebpack, karmaChromeLauncher, karmaSpecReporter], files: ['test/index.spec.js'], preprocessors: { 'test/index.spec.js': ['webpack'], }, webpack: { mode: 'development', resolve: { extensions: ['.js', '.ts', '.tsx'], fallback: { crypto: false, buffer: false, stream: false, }, // Mock JSBI to avoid using BigInt alias: { jsbi: 'jsbi/dist/jsbi-cjs.js', }, }, module: { rules: [ { test: /\.tsx?$/, use: [ { loader: 'ts-loader', options: { transpileOnly: true }, }, ], exclude: /node_modules\/(?!.*(bip39|pmcrypto))/, }, ], }, devtool: 'inline-source-map', }, mime: { 'text/x-typescript': ['ts', 'tsx'], }, reporters: ['spec'], specReporter: { suppressSkipped: true, // do not print information about skipped tests }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, customLaunchers: { ChromeHeadlessCI: { base: 'ChromeHeadless', flags: ['--no-sandbox'], }, }, browsers: ['ChromeHeadlessCI'], singleRun: true, concurrency: Infinity, client: { jasmine: { timeoutInterval: 10000, }, }, }); };
8,773
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/api/apiError.spec.ts
import { isNotExistError } from '@proton/shared/lib/api/helpers/apiErrorHelper'; describe('isNotExistError', () => { it('should be a not exist error', () => { // Invalid id const error1 = { data: { Code: 2061, }, }; // Message does not exists const error2 = { data: { Code: 2501, }, }; // Conversation does not exists const error3 = { data: { Code: 20052, }, }; expect(isNotExistError(error1)).toBeTruthy(); expect(isNotExistError(error2)).toBeTruthy(); expect(isNotExistError(error3)).toBeTruthy(); }); it('should not be a not exist error', () => { const error1 = {}; const error2 = { data: { Code: 'something else', }, }; const error3 = { data: {}, }; expect(isNotExistError(error1)).toBeFalsy(); expect(isNotExistError(error2)).toBeFalsy(); expect(isNotExistError(error3)).toBeFalsy(); }); });
8,774
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/api/authHandlers.spec.js
import withApiHandlers, { InactiveSessionError } from '../../lib/api/helpers/withApiHandlers'; import { withUIDHeaders } from '../../lib/fetch/headers'; const getApiError = ({ message, response = { headers: { get: () => '' } }, data, status }) => { const error = new Error(message); error.status = status; error.data = data; error.response = response; return error; }; const getApiResult = (result) => { return { headers: { get: () => '', }, status: 200, json: () => result, }; }; describe('auth handlers', () => { it('should unlock', async () => { const call = jasmine .createSpy('call') .and.returnValues(Promise.reject(getApiError({ status: 403 })), Promise.resolve(getApiResult('123'))); const handleMissingScopes = jasmine.createSpy('unlock').and.callFake(({ options }) => { return call(options); }); const api = withApiHandlers({ call, onMissingScopes: handleMissingScopes }); const result = await api({}).then((r) => r.json()); expect(result).toBe('123'); expect(handleMissingScopes).toHaveBeenCalledTimes(1); expect(call).toHaveBeenCalledTimes(2); }); it('should unlock and be cancellable', async () => { const unlockError = getApiError({ status: 403 }); const call = jasmine.createSpy('call').and.returnValues(Promise.reject(unlockError)); const handleUnlock = jasmine.createSpy('unlock').and.returnValues(Promise.reject(unlockError)); const handleError = jasmine.createSpy('error').and.callFake((e) => { return e; }); const api = withApiHandlers({ call, onMissingScopes: handleUnlock }); const error = await api({}).catch(handleError); expect(error).toBe(unlockError); expect(handleError).toHaveBeenCalledTimes(1); expect(handleUnlock).toHaveBeenCalledTimes(1); expect(call).toHaveBeenCalledTimes(1); }); it('should retry 429 status', async () => { const call = jasmine .createSpy('call') .and.returnValues(Promise.reject(getApiError({ status: 429 })), Promise.resolve(getApiResult('123'))); const handleError = jasmine.createSpy('error').and.callFake((e) => { return e; }); const api = withApiHandlers({ call }); const result = await api({}) .then((r) => r.json()) .catch(handleError); expect(result).toBe('123'); expect(call).toHaveBeenCalledTimes(2); expect(handleError).toHaveBeenCalledTimes(0); }); it('should not retry 429 status if disabled', async () => { const call = jasmine .createSpy('call') .and.returnValues(Promise.reject(getApiError({ status: 429 })), Promise.resolve(getApiResult('123'))); const handleError = jasmine.createSpy('error').and.callFake((e) => { return e; }); const api = withApiHandlers({ call }); const error = await api({ ignoreHandler: [429] }).catch(handleError); expect(error.status).toBe(429); expect(call).toHaveBeenCalledTimes(1); expect(handleError).toHaveBeenCalledTimes(1); }); it('should retry maximum 5 times', async () => { const returns = [ () => Promise.reject(getApiError({ status: 429 })), () => Promise.reject(getApiError({ status: 429 })), () => Promise.reject(getApiError({ status: 429 })), () => Promise.reject(getApiError({ status: 429 })), () => Promise.reject(getApiError({ status: 429 })), ]; let i = 0; const call = jasmine.createSpy('call').and.callFake(() => returns[i++]()); const handleError = jasmine.createSpy('error').and.callFake((e) => { return e; }); const api = withApiHandlers({ call }); const error = await api({}).catch(handleError); expect(error.status).toBe(429); expect(call).toHaveBeenCalledTimes(5); expect(handleError).toHaveBeenCalledTimes(1); }); it('should not handle retry when its greater than 10', async () => { const call = jasmine .createSpy('call') .and.returnValues(Promise.reject(getApiError({ status: 429, response: { headers: { get: () => '10' } } }))); const handleError = jasmine.createSpy('error').and.callFake((e) => { return e; }); const api = withApiHandlers({ call }); const error = await api({}).catch(handleError); expect(error.status).toBe(429); expect(call).toHaveBeenCalledTimes(1); expect(handleError).toHaveBeenCalledTimes(1); }); it('should not refresh if has no session', async () => { const call = jasmine.createSpy('call').and.returnValues(Promise.reject(getApiError({ status: 401 }))); const handleError = jasmine.createSpy('error').and.callFake((e) => { return e; }); const api = withApiHandlers({ call }); const error = await api({}).catch(handleError); expect(error.status).toBe(401); expect(call).toHaveBeenCalledTimes(1); expect(handleError).toHaveBeenCalledTimes(1); }); it('should refresh once (if has session)', async () => { let refreshed = false; let refreshCalls = 0; const call = jasmine.createSpy('call').and.callFake(async (args) => { if (args.url === 'auth/refresh') { refreshed = true; refreshCalls++; return { headers: { get: () => '1' }, }; } if (!refreshed) { throw getApiError({ status: 401 }); } return args; }); const handleError = jasmine.createSpy('error').and.callFake((e) => { return e; }); const apiWithHandlers = withApiHandlers({ call, UID: '123' }); const api = (a) => apiWithHandlers(a).catch(handleError); const result = await Promise.all([api(123), api(231), api(321)]); expect(result).toEqual([123, 231, 321]); expect(call).toHaveBeenCalledTimes(7); expect(handleError).toHaveBeenCalledTimes(0); expect(refreshCalls).toBe(1); }); it('should refresh once and fail all active calls (if has session)', async () => { const call = jasmine.createSpy('call').and.callFake(async (args) => { if (args.url === 'auth/refresh') { throw getApiError({ status: 422, data: args }); } throw getApiError({ status: 401, data: args }); }); const handleError = jasmine.createSpy('error').and.callFake((e) => { throw e; }); const apiWithHandlers = withApiHandlers({ call, UID: '123' }); const api = (a) => apiWithHandlers(a).catch(handleError); const [p1, p2, p3] = [api(123), api(231), api(321)]; await expectAsync(p1).toBeRejectedWith(InactiveSessionError()); await expectAsync(p2).toBeRejectedWith(InactiveSessionError()); await expectAsync(p3).toBeRejectedWith(InactiveSessionError()); expect(call).toHaveBeenCalledTimes(4); expect(handleError).toHaveBeenCalledTimes(3); }); it('should refresh once and only logout if it is a 4xx error', async () => { const returns = [ () => Promise.reject(getApiError({ status: 401 })), () => Promise.reject(getApiError({ status: 500 })), () => Promise.reject(getApiError({ status: 401 })), () => Promise.reject(getApiError({ status: 422 })), ]; let i = 0; const call = jasmine.createSpy('call').and.callFake(() => returns[i++]()); const handleError = jasmine.createSpy('error').and.callFake((e) => { return e; }); const api = withApiHandlers({ call, UID: '123' }); const error = await api(123).catch(handleError); expect(error.status).toBe(500); expect(call).toHaveBeenCalledTimes(2); expect(handleError).toHaveBeenCalledTimes(1); const r2 = api(123); await expectAsync(r2).toBeRejectedWith(InactiveSessionError()); expect(call).toHaveBeenCalledTimes(4); }); it('should only error with InactiveSession if the initial UID is the same', async () => { const returns = [ () => Promise.reject(getApiError({ status: 401 })), () => Promise.reject(getApiError({ status: 400 })), () => Promise.reject(getApiError({ status: 401 })), () => Promise.reject(getApiError({ status: 400 })), ]; let i = 0; const call = jasmine.createSpy('call').and.callFake(() => returns[i++]()); const handleError = jasmine.createSpy('error').and.callFake((e) => { return e; }); const api = withApiHandlers({ call, UID: '123' }); const error = await api(withUIDHeaders('321', {})).catch(handleError); expect(error.status).toBe(401); expect(call).toHaveBeenCalledTimes(2); expect(handleError).toHaveBeenCalledTimes(1); const error2 = await api({}).catch(handleError); expect(error2.name).toBe('InactiveSession'); expect(call).toHaveBeenCalledTimes(4); expect(handleError).toHaveBeenCalledTimes(2); }); it('should refresh once and handle 429 max attempts', async () => { const returns = [ () => Promise.reject(getApiError({ status: 401 })), () => Promise.reject(getApiError({ status: 429 })), () => Promise.reject(getApiError({ status: 429 })), () => Promise.reject(getApiError({ status: 429 })), () => Promise.reject(getApiError({ status: 429 })), () => Promise.reject(getApiError({ status: 429 })), () => Promise.reject(getApiError({ status: 429 })), ]; let i = 0; const call = jasmine.createSpy('call').and.callFake(() => returns[i++]()); const api = withApiHandlers({ call, UID: '126' }); await expectAsync(api(123)).toBeRejectedWith(InactiveSessionError()); expect(call).toHaveBeenCalledTimes(6); }); it('should refresh once and handle 429', async () => { const returns = [ () => Promise.reject(getApiError({ status: 401 })), // need refresh () => Promise.reject(getApiError({ status: 429 })), // retry () => Promise.reject(getApiError({ status: 429 })), // retry () => Promise.resolve(getApiResult('')), // refresh ok () => Promise.resolve(getApiResult('123')), // actual result ]; let i = 0; const call = jasmine.createSpy('call').and.callFake(() => returns[i++]()); const api = withApiHandlers({ call, UID: 'abc' }); const result = await api(123).then((result) => result.json()); expect(call).toHaveBeenCalledTimes(5); expect(result).toBe('123'); }); it('should fail all calls after it has logged out', async () => { const call = jasmine.createSpy('call').and.callFake(async (args) => { throw getApiError({ status: 401, data: args }); }); const api = withApiHandlers({ call, UID: '128' }); await expectAsync(api()).toBeRejectedWith(InactiveSessionError()); expect(call).toHaveBeenCalledTimes(2); await expectAsync(api()).toBeRejectedWith(InactiveSessionError()); expect(call).toHaveBeenCalledTimes(2); }); });
8,775
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/api/getPublicKeysEmailHelper.spec.js
import getPublicKeysEmailHelper from '../../lib/api/helpers/getPublicKeysEmailHelper'; import { KEY_FLAG, RECIPIENT_TYPES } from '../../lib/constants'; import { KeyTransparencyActivation } from '../../lib/interfaces'; const getApiError = ({ message, response = { headers: { get: () => '' } }, data, status }) => { const error = new Error(message); error.status = status; error.data = data; error.response = response; return error; }; const getMockedApi = (mockApiResponse, isError) => { const response = isError ? Promise.reject(mockApiResponse) : Promise.resolve(mockApiResponse); return jasmine.createSpy('api').and.returnValue(response); }; // `internalKeysOnly` is not being tested atm as it only affects the API returned data describe('getPublicKeysEmailHelper', () => { const ktActivation = KeyTransparencyActivation.DISABLED; const testKeyA = `-----BEGIN PGP PUBLIC KEY BLOCK----- Comment: email is [email protected] xjMEZVeZjRYJKwYBBAHaRw8BAQdA39O4dS41Fqwvj0Xo/xWioK5Q7BudKJ/H tna/S6Rl9KvNDjxhYWFAdGVzdC5jb20+wokEEBYKADsFgmVXmY0DCwkHCZCg Jdhc+VtnygMVCAoCFgACGQECmwMCHgEWIQQgf6DlToGVRDJ8fuKgJdhc+Vtn ygAAj2wA/3Zj6NrRdnUWMt5bqSOr49i9nJCplDlEDsUo15eWssQbAPwJ4toM 1eTmSXuHPe0qmV4bH+rmz2R1CojffAlBgHrhDs44BGVXmY0SCisGAQQBl1UB BQEBB0CccwR7RDG2BrJUlko0XWcWz9r8tbKSZN/beWKBl2ORfgMBCAfCeAQY FgoAKgWCZVeZjQmQoCXYXPlbZ8oCmwwWIQQgf6DlToGVRDJ8fuKgJdhc+Vtn ygAAQu4A/isbPn6kW7t8Kz/JhcNbXYNLxzwUz2WYgU+b8IZA6iT2AQDN5Z6V o641lFnk8Bo1GSevHgItogC7uU90n6i/fCrQBg== -----END PGP PUBLIC KEY BLOCK-----`; const testKeyB = `-----BEGIN PGP PUBLIC KEY BLOCK----- Comment: email is [email protected] xjMEZVeZkRYJKwYBBAHaRw8BAQdA1dHIjjOu9APYbRpYCdbDOB7aw0CPYOkd qR7yuhSpqL3NDjxiYmJAdGVzdC5jb20+wokEEBYKADsFgmVXmZEDCwkHCZBG XNa/N9gwHgMVCAoCFgACGQECmwMCHgEWIQS0U9zqvzhJRPKLh4VGXNa/N9gw HgAAgv0A/AzlMq39rVpNTjNbrvIlh95wRflNTw86oadFtpocuWSWAQCZB1a3 BaOXeVZoHte7e7k7rTaAzZ8e0haSJPpy4qWpA844BGVXmZESCisGAQQBl1UB BQEBB0CKHsFTozeEl7L0l9ueitptl9Bf2Tk/Q2yAZUgXVFbXHAMBCAfCeAQY FgoAKgWCZVeZkQmQRlzWvzfYMB4CmwwWIQS0U9zqvzhJRPKLh4VGXNa/N9gw HgAA4F0BAP3QbD5trB7BemDyRIET8pvs0J/s1ruMWV8/SC4u50nbAP9AIRON vqg5tCgoAiPlCv5xna6ypuLS4rnVUVdNbYVRAA== -----END PGP PUBLIC KEY BLOCK-----`; describe('mail encryption use case', () => { it('internal recipient with mail-capable address keys', async () => { // test with a mix of mail-capable and non-capable keys, even though it's unclear if this scenario can ever happen. const mockApiResponse = { Address: { Keys: [ { PublicKey: testKeyA, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED, }, { PublicKey: testKeyB, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED | KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT, }, ], }, ProtonMX: false, }; const api = getMockedApi(mockApiResponse); const result = await getPublicKeysEmailHelper({ api, ktActivation, email: '[email protected]' }); expect(result.RecipientType).toBe(RECIPIENT_TYPES.TYPE_INTERNAL); expect(result.isInternalWithDisabledE2EEForMail).toBe(false); expect(result.publicKeys).toHaveSize(1); expect(result.publicKeys[0].publicKey.getUserIDs()[0]).toMatch(/[email protected]/); }); it('internal recipient with no mail-capable address keys', async () => { const mockApiResponse = { Address: { Keys: [ { PublicKey: testKeyA, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED | KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT, }, ], }, ProtonMX: true, }; const api = getMockedApi(mockApiResponse); const result = await getPublicKeysEmailHelper({ api, ktActivation, email: '[email protected]' }); expect(result.RecipientType).toBe(RECIPIENT_TYPES.TYPE_EXTERNAL); expect(result.isInternalWithDisabledE2EEForMail).toBe(true); expect(result.publicKeys).toHaveSize(0); }); it('external account with internal address keys and wkd keys', async () => { const mockApiResponse = { Address: { Keys: [ { PublicKey: testKeyA, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED | KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT, }, ], }, Unverified: { Keys: [ { PublicKey: testKeyB, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED, }, ], }, ProtonMX: false, }; const api = getMockedApi(mockApiResponse); const result = await getPublicKeysEmailHelper({ api, ktActivation, email: '[email protected]' }); expect(result.RecipientType).toBe(RECIPIENT_TYPES.TYPE_EXTERNAL); expect(result.isInternalWithDisabledE2EEForMail).toBe(false); expect(result.publicKeys).toHaveSize(1); expect(result.publicKeys[0].publicKey.getUserIDs()[0]).toMatch(/[email protected]/); }); it('external recipient with wkd keys', async () => { const mockApiResponse = { Address: { Keys: [], }, Unverified: { Keys: [ { PublicKey: testKeyB, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED, }, ], }, ProtonMX: false, }; const api = getMockedApi(mockApiResponse); const result = await getPublicKeysEmailHelper({ api, ktActivation, email: '[email protected]' }); expect(result.RecipientType).toBe(RECIPIENT_TYPES.TYPE_EXTERNAL); expect(result.isInternalWithDisabledE2EEForMail).toBe(false); expect(result.publicKeys).toHaveSize(1); }); }); describe('includeInternalKeysWithE2EEDisabledForMail', () => { it('internal recipient with mail-capable address keys', async () => { const mockApiResponse = { Address: { Keys: [ { PublicKey: testKeyA, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED, }, ], }, ProtonMX: true, }; const api = getMockedApi(mockApiResponse); const result = await getPublicKeysEmailHelper({ api, ktActivation, email: '[email protected]', includeInternalKeysWithE2EEDisabledForMail: true, }); expect(result.RecipientType).toBe(RECIPIENT_TYPES.TYPE_INTERNAL); expect(result.isInternalWithDisabledE2EEForMail).toBe(false); expect(result.publicKeys).toHaveSize(1); }); it('internal recipient with mail-capable address keys and bad MX settings', async () => { // test with a mix of mail-capable and non-capable keys, even though it's unclear if this scenario can ever happen. const mockApiResponse = { Address: { Keys: [ { PublicKey: testKeyA, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED, }, { PublicKey: testKeyB, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED | KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT, }, ], }, ProtonMX: false, }; const api = getMockedApi(mockApiResponse); const result = await getPublicKeysEmailHelper({ api, ktActivation, email: '[email protected]', includeInternalKeysWithE2EEDisabledForMail: true, }); expect(result.RecipientType).toBe(RECIPIENT_TYPES.TYPE_INTERNAL); expect(result.isInternalWithDisabledE2EEForMail).toBe(false); expect(result.publicKeys).toHaveSize(2); }); it('internal recipient with no mail-capable address keys', async () => { const mockApiResponse = { Address: { Keys: [ { PublicKey: testKeyA, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED | KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT, }, ], }, ProtonMX: true, }; const api = getMockedApi(mockApiResponse); const result = await getPublicKeysEmailHelper({ api, ktActivation, email: '[email protected]', includeInternalKeysWithE2EEDisabledForMail: true, }); expect(result.RecipientType).toBe(RECIPIENT_TYPES.TYPE_INTERNAL); expect(result.isInternalWithDisabledE2EEForMail).toBe(true); expect(result.publicKeys).toHaveSize(1); }); it('external account with internal address keys and wkd keys', async () => { const mockApiResponse = { Address: { Keys: [ { PublicKey: testKeyA, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED | KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT, }, ], }, Unverified: { Keys: [ { PublicKey: testKeyB, Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED, }, ], }, ProtonMX: false, }; const api = getMockedApi(mockApiResponse); const result = await getPublicKeysEmailHelper({ api, ktActivation, email: '[email protected]', includeInternalKeysWithE2EEDisabledForMail: true, }); expect(result.RecipientType).toBe(RECIPIENT_TYPES.TYPE_EXTERNAL); expect(result.isInternalWithDisabledE2EEForMail).toBe(false); // the internal address keys is always ignored for external accounts expect(result.publicKeys).toHaveSize(1); expect(result.publicKeys[0].publicKey.getUserIDs()[0]).toMatch(/[email protected]/); }); it('external address with wkd keys - internalKeysOnly', async () => { // this simulates the error that the API currently gives, to ensure we handle it properly const mockApiResponse = getApiError({ status: 422, data: { Code: 33102, Error: 'This address does not exist. Please try again', Details: { Address: '[email protected]', }, }, }); const api = getMockedApi(mockApiResponse, true); const result = await getPublicKeysEmailHelper({ api, ktActivation, email: '[email protected]', internalKeysOnly: true, }); expect(result.RecipientType).toBe(undefined); expect(result.isInternalWithDisabledE2EEForMail).toBe(undefined); expect(result.publicKeys).toHaveSize(0); }); }); });
8,776
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/api/headers.ts
import { getClientID } from '../../lib/apps/helper'; import { APPS, APP_NAMES } from '../../lib/constants'; import { getAppVersionHeaders } from '../../lib/fetch/headers'; describe('app version headers', () => { it('should return new app headers', () => { const test = (app: APP_NAMES, version: string, expectation: string) => { expect(getAppVersionHeaders(getClientID(app), version)).toEqual({ 'x-pm-appversion': expectation }); }; for (const { app, version, expectation } of [ { app: APPS.PROTONMAIL, version: '4.999.999', expectation: '[email protected]', }, { app: APPS.PROTONMAIL, version: '4.14.6', expectation: '[email protected]', }, { app: APPS.PROTONCALENDAR, version: '4.0.1', expectation: '[email protected]', }, { app: APPS.PROTONVPN_SETTINGS, version: '4.999.999', expectation: '[email protected]', }, { app: APPS.PROTONVERIFICATION, version: '4.1.0', expectation: '[email protected]', }, { app: APPS.PROTONADMIN, version: '4.12.12', expectation: '[email protected]', }, ]) { test(app, version, expectation); } }); });
8,777
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/api/queryPages.spec.ts
import queryPages from '../../lib/api/helpers/queryPages'; describe('query pages', () => { it('should be able to process multiple pages', async () => { const result = await queryPages( async (n) => { return { Value: n, Total: 5, }; }, { pageSize: 1, pagesPerChunk: 1, delayPerChunk: 1, } ).then((pages) => { return pages.map(({ Value }) => Value); }); expect(result).toEqual([0, 1, 2, 3, 4]); }); it('should return the first page without a total', async () => { const result = await queryPages( async () => { return { Value: 0, } as any; }, { pageSize: 100, pagesPerChunk: 20, delayPerChunk: 1, } ).then((pages) => { return pages.map(({ Value }) => Value); }); expect(result).toEqual([0]); }); it('should return several pages', async () => { const result = await queryPages( async (n) => { return { Value: n, Total: 4, }; }, { pageSize: 2, pagesPerChunk: 20, delayPerChunk: 1, } ).then((pages) => { return pages.map(({ Value }) => Value); }); expect(result).toEqual([0, 1]); }); });
8,778
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/api/safeApiRequests.spec.ts
import { processApiRequestsSafe } from '../../lib/api/helpers/safeApiRequests'; import { wait } from '../../lib/helpers/promise'; describe('safe api requests', () => { it('it can process the full batch', async () => { const generators = [1, 1].map((n, i) => { return async () => { await wait(n); return i; }; }); const result = await processApiRequestsSafe(generators, 2, 100); expect(result).toEqual([0, 1]); }); it('it returns the result in order', async () => { const generators = [2000, 500, 2, 300, 100, 1000].map((n, i) => { return async () => { await wait(n); return i; }; }); const result = await processApiRequestsSafe(generators, 2, 100); expect(result).toEqual([0, 1, 2, 3, 4, 5]); }); });
8,779
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/apps/helper.spec.ts
import { getAppHref } from '../../lib/apps/helper'; import { APPS } from '../../lib/constants'; const location = { hostname: 'calendar.protonmail.com', protocol: 'https:', port: '', }; describe('sso app href', () => { it('should produce links relative to the current second level domain', () => { expect(getAppHref('/', APPS.PROTONACCOUNT, undefined, location)).toBe(`https://account.protonmail.com`); }); it('should produce links relative to localhost', () => { const location = { hostname: 'localhost', protocol: 'http:', port: '', }; expect(getAppHref('/', APPS.PROTONACCOUNT, undefined, location)).toBe(`http://account.localhost`); }); it('should produce links relative to the current top domain', () => { const location = { hostname: 'protonmail.com', protocol: 'https:', port: '', }; expect(getAppHref('/', APPS.PROTONACCOUNT, undefined, location)).toBe(`https://account.protonmail.com`); }); it('should produce links relative to the current domain, with a local id', () => { expect(getAppHref('/', APPS.PROTONACCOUNT, 1, location)).toBe(`https://account.protonmail.com/u/1`); }); it('should produce links to other apps', () => { expect(getAppHref('/', APPS.PROTONCALENDAR, 2, location)).toBe(`https://calendar.protonmail.com/u/2`); }); it('should produce links to other apps with another location', () => { const location = { hostname: 'test.com', protocol: 'https:', port: '', }; expect(getAppHref('/', APPS.PROTONCALENDAR, 2, location)).toBe(`https://calendar.test.com/u/2`); }); it('should produce links respecting the port', () => { const location = { hostname: 'test.com', protocol: 'https:', port: '4443', }; expect(getAppHref('/', APPS.PROTONCALENDAR, 2, location)).toBe(`https://calendar.test.com:4443/u/2`); }); it('should produce links to other apps with another location', () => { const location = { hostname: 'test.com', protocol: 'https:', port: '', }; expect(getAppHref('/', APPS.PROTONCALENDAR, 2, location)).toBe(`https://calendar.test.com/u/2`); }); it('should override protonvpn hostname', () => { const location = { hostname: 'account.protonvpn.com', protocol: 'https:', port: '', }; expect(getAppHref('/', APPS.PROTONCALENDAR, 2, location)).toBe(`https://calendar.proton.me/u/2`); }); it('should produce links stripping previous local id basenames', () => { const location = { hostname: 'account.protonmail.com', protocol: 'https:', port: '', }; expect(getAppHref('/u/0/mail', APPS.PROTONACCOUNT, 2, location)).toBe( `https://account.protonmail.com/u/2/mail` ); expect(getAppHref('/u/0/mail', APPS.PROTONACCOUNT, 0, location)).toBe( `https://account.protonmail.com/u/0/mail` ); }); });
8,780
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/authentication/login.data.js
export const Modulus = ` -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 S02yU4ENpYwmYK2fZlNRMHEpnpo4z3r7dbpfsW6tV9InIFXXk53k7gpC40WgyiHtF7EMUQ2hRmKLCpPhK27qkIGHpRBoVzKj9NbjZ2b+f79otH7cLVwpsioJwMmP12lK8uKB4RTS9tQiLPczs4F6fshGfhDcTb45ygIZ+KCX4j0znDEpf/R0FQeBto1Vy/mPnu21NuWZcDVukQkZKYsefylixszYRtBfynESmStzu9wmm75fH74JptuAbkq6KZtosYdLRk96yIcIXr6T9XazDZz47VWrS3fQACGY/wKmW1n7z3rkkEKCRplWzSJOIOS6fH35f1p/G72j8ZHu9M8Z3w== -----BEGIN PGP SIGNATURE----- Version: ProtonMail Comment: https://protonmail.com wl4EARYIABAFAlwB1j4JEDUFhcTpUY8mAABIbgD9HllIcS6Mc2Vy8SVODWwY 2dw231bE2o+k6ypYxjQdr5oBAIRQKlN6e7mTWa9DayR2ix3wS0NinK+BO+h3 EL8XnJcB =NaAE -----END PGP SIGNATURE----- `; export const ServerEphemeral = '4yh6FbkEaiHVq7/sAQqa7sE1zfkyyKShGzRWneNCqsqtGwGoehV4lTWmAmLXiCoLE4Q4RDa2tWHnUy+CTJbV7rBgvCe4oRC+0Rf8v3BZCDTakAdqMQgX8A1Xjuvbokl4pVnO6Yry5WM6Iko6HIFD91JAWBWd+FKAhe0CjJFrwEzmoumJSBns/WQju2e0RFnwP3i9p5APGlBzB2fpLqLEkgVGJ2fkdzJcdbw82CCryfa5tszkkQSoQAIdIDq60+PKZJEXXMu28lBL5YRgPBuc3joq+Ic1obn2IWLA8fUcFkIeIVZDdD2P/WduZq4M08Wf1SadROM4Rz0VLDoGOD8slQ=='; export const Salt = 'fHu36wAR86rBDo/1bEiW7w=='; export const ServerProof = 'BeUSaRql+ab+1hNYGoeZUy8yoK0i3ad3zO4tUjCDsMmARBYyM1yO2fM2J+6UFBlVLSLmqYHgg5A8RJcCEOvCa4i6unG41lYaIxEqmvZIG8tf7zGdOpN8Bj2XwrWpVIHtEjXV0gY6YnbjuAzj0BaV31O54bxhp0ZTB/sgyt/iHtivf7BvMPZM//8UDa2y+PsugqpAEMFzRYXSPH3S4dpV2VKXKT0NdG2wRSL5CzI/dlXpFEuO/aX+rQmGxdGp1sNnXqJRyPFrbLwkaNURQQc8V7pY+g21SdIPB0QrehPalwccs6nTHwqTz60PO+Dr6ENqWZDF0s3YHr0CC96/8CJECw=='; export const INFO_RESPONSE = { Salt, ServerEphemeral, Modulus, Version: 4, '2FA': { TOTP: 1, U2F: null, }, }; export const INFO_RESPONSE_NO_2FA = { Salt, ServerEphemeral, Modulus, Version: 4, '2FA': { TOTP: 0, U2F: null, }, }; const PrivateKey = '-----BEGIN PGP PRIVATE KEY BLOCK-----\nVersion: ProtonMail\nComment: https://protonmail.com\n\nxcMGBFyrS04BCACBgtwInaHKPg/pOR4IsgSF4/z9iDgTTt7pTr407VFLUebR\niymA0m3Adx3OLKlwo/kDgYpaltwR1BPTOpVpIYrpE9zvlLNs6V1/Ub3CKumz\nhXSM2mQkWp51/C7/AwAER1aKukd34Iq/HiToBXxWlk2ajyr7O/LX2i8uoVrX\n35bly0Qaa+T9vHdNpJ4hL/GR8GXgX0dItipUT2Mp0RRZJ7hL8QzyXg53Voyy\nX4PpvoIeys9wtx/DH0r9q1UsKgpP1+VLlEXkr0YeokUcSvApf2IB7POYYZ9X\nxIs87+hsalX2uux6fPFpAfKo4lY4qlraM3K+gRVM9loJ/lhWCgmo+qlFABEB\nAAH+CQMIPyxNFMp7oRJgDDdUMEaqAavMzfG32SliGvRZevba9sS4/5h/3gHx\nyWLSDTJ7oeRP2ZV792nsfm7c0lCeQjNKfWRW1qKv3jjtOvbEoRLZ7TFJLu2n\nNkVtILnM5cF05mv4lVAq83iJJDQT61wmMrrOA/Ko8GtzHJN2/6hxdFkSSAFb\nKvi98IvqZxJoDbo/16FCSAXyLga4Zc+0D7cqHuVfcb7ql1Vii/xcSzFruRuQ\njXOf2/VI8fc0YWU8jk079nST52GTX0hW947pXI/PJ/EkJb3AxhMbCgb8Fsqi\necIXiVLEdV8QaVZmBcUssu6YhSYvtT1UPC7vvAVN/Wq8xjj8ripvoCe/cNgN\nthWGeY7coyNfjxD26jCr7Vnt9bcpJ5pp6INs9Wnz6oKtRWlFdw1zeZz/wtLu\nJ36oNojKBes9gRurMukE1+O5uipqHbsGFDrGrI+WPoqPfqCinUkpIxjnNYfG\n8kY4jRgymK/9B37IjrI2osGEDzrAH8MTX5EGMW452+jAiP9su4f+WDuNm80w\nFwOf1azN8vTNMZqP92QofbMQi6blI4V3fhT9LQR7sjmcHM+qpNDDdgvrOWah\nPk4yZ1nm3d9pqPWivbuM8a/r2bGg/4DdoS6poQCikAPJf70fhOfcqcc/adxI\nG7DxdOGf0KCAkF5MqApQX3vTvUoHROyfWiuvnwh9jgnvINweyANisNg1HNOD\nnzUV/cY7wZ0hzbPn301UAx2W5qhIU8zHlwCJ1Cc0TdRn7h1uuhnZXEWaWT95\nZrFMAgPmmfIe+FVa255l9hbWMn8NpOrreVQ7/sGHx7qLn5O9uZVQtjfACxj9\nn5Ey4Oeii9Y9XXOdIpW1sbtRaPxC92PCGx/FmlC0JPK8Nk6PNhqcO/T21801\nB/GlT65xvMltF0bKAXPy6ZQeMBLTjDGlzTEibXRlc3QyMDBAcHJvdG9ubWFp\nbC5jaCIgPG10ZXN0MjAwQHByb3Rvbm1haWwuY2g+wsB1BBABCAAfBQJcq0tO\nBgsJBwgDAgQVCAoCAxYCAQIZAQIbAwIeAQAKCRAnBvJyu/cMYfiiB/4s1wve\n9Va7REU5OdO+1xwsm7UVv0E86z9e9DDGZAehE+Uco79y6NIXHhm8utj08P+Y\n/b1dtRVnWj1Rx931l6g8gj+i0B8NZUule0b1+qAdxgm2duP33b7UgRqOry5f\nEmWOrywNO+hWwAT4AA8QH8ZGFHUX6plk2LQLfWzI+J43/s+V3K64/ue2FOgs\n4Cm8xmZkgsF80jAhp+K7m3qtqsKTmblkOu/auga6G/glqOgrssvenikbxtOE\nJaexCuBNYR/nz/g/H+eMooXBir5ffYm1hmhgds4Phs4BNqDeJ7HfaG7Gwvs1\niEanhvE8/qgbfC9CwnN7w8UaFJvdCVAbIFF4x8MGBFyrS04BCAC9bQguYNjH\n759kMKxclzWv7EhOZEvXcGZ8WgA3VKDcWmmuzHsOTH2OQ8VeaZzNHxsKMAiv\neBxwF4Ln0R1IYcPHnGDtDU+ga1fd0HCJi7f5SkWbXfw7vwmVVySCdTAiejmq\nj8h0Jtk6S2xzge3Tdf1KHa6BQ3CQCVHF3OaCMxtTPlukJjvEKEQAwR7wU7ev\nx64rC70BhmOrrLactRDWv8mDFT0JStbO30C4Ylp1Kyyxxer8EtC8XLhSmdnX\nY4ncZCp/b5/lATn7d0aaYISDtBMUcNAkpKgU2Cfp7SR4YQmq7vxyZi+RT6ur\n2w1h9bOmSF0IAHQx8pM+HhrGR+MatcQ7ABEBAAH+CQMIJshbCogLt+NgCxSb\nDEUfTwfUVp1H91JhEVUcs2pg28x95mN5nVd+V77Ck1tcrkOj0Cjih9Gt5RZR\nklAl1PDjr3JRzNFLsJHKrDHH0mEGsT04eQrT7fodVcEyx90NDaNdkv8O5x30\n1Ll6uKKcmnFM+oHUkyLyV+dxcemYijR8Rr1d877p6Y8OYyY44Dt8c9p/AUj5\ngS4Eq2Wr0tIbajZS2PUGUTjMjsNjCDWk6oFxcau92s63pzO1neH4dzeO8Agq\nArH41xfMFrdwMcQCl7omeTSVsDE0aJhjbqcnZL5Sa6FpddxFji52Paiwbwo6\nCy+UnOoFG1ud/pCAG07UYKk+jg85Z/Y9NK2Bp5DYMSJSa83txcgbvcO1+zqV\nhwKSI/q7SFbFh0q3V0NR8FypNZtt/nTmyhZyZDH62MbdPQ04+Evc99Ifl5IR\nuRSyFKk29aXN9UyydfR+32peIBFeNulKERvSIiL3G/ieTtHuVsehZyy7jdEc\nBtmP8E2nmm6uIneNIdzDxeTnF8Bl2Dp0aMBGC78OCT4VUIOeF8YTZy7xcs0e\nO5czNIPXFHIdxbnlpAuLpBjK51QGa8tuWsXh1yhK+oCYHWuLvfTqEVPFQs0F\ndJvMv47WVmeqH9gcvNmqnnK6xR3Ry1l6jnVbKMHT0kkMmCTMNWHNn06EZWLk\ns/eZiQduWIZu87hpEh4uPRLzpA0i6Y7oCXy2WQZ/TeY2+6jxC8XlPXB/BEKD\nXDpffkI7X6goOk/sX0SIasN2S2pEqXiLPgPpM5O39c0S8XVv4k+tp8Z1JTS4\n0xR5r+r3/IXxmJzpAM8M/xzbS/I1DXOGDHD47fROnWqlnbHyPATua7iZ0JY4\nm6ezhgAj4qzNNeO29O7ac7lMbmEjP6W9Qh3MxCSXFDkN4UJnF9HseSSejRDN\n4mffNuU2wsBfBBgBCAAJBQJcq0tOAhsMAAoJECcG8nK79wxhlSYH/jglsWN6\nalN+ERyI7PNr1/hd8YfPNGedQC2zh1/Sbuj8sNWWQmjagTjmEGUHLSjZH1na\nPecujlUMGLRAkFjND/nplUk+pWvtX9j0902qsJh1sT0J1lCdaWlG1YuHw08H\nRBDpfbrE2H4pkcX+f6E5Idau9l/Wk2j5GB/0TvS1tnlY5+5ZTbYXCwHhRdY6\n4WOAOJijxyfaWPKlWgwbDIUSdlnOX1t5F3TrM2m8YgFXd9kE/QcjO9ib0nnq\nqTQ3ZTlRVsyftC/0htXiAGntAgZ8P4KLCMoM+03/fkih1H9qKgcTg5xPFqDY\nqxNXJd5vAkDBhT7GE3SynVm5htlqqP971VI=\n=1a6B\n-----END PGP PRIVATE KEY BLOCK-----\n'; const PrivateKeyUnlock = '-----BEGIN PGP PRIVATE KEY BLOCK-----\nVersion: ProtonMail\nComment: https://protonmail.com\n\nxcMGBFvhxDsBCACvjB7lxqPt2H14H2zbg8pMPQ+zE5yfdCMSAQwC35MX/MTE\nF4qirZ2HyfgISp7LUZpnAx4uUDltGpCbMgVDTqo/2YhnPIDdg5lwvx+iOl7e\nS2NRPUzTSTkY/D2mWFfMVcjL3QlRPue+vLIiYKUvFxyUOK6P4eap8wEjbsNu\nkt8DsdLVIuApz+QI0yyivp3RvEL/V4E3YgP8X1hYjBQkyaHRxgLyOfulMhiY\nePc14DF8ZExJ6Lau+9X3wjiBeQl23N80K2piRWaeELdlb1bz5E2wxz+O0nkR\nLdtWkGyxFdTfjDN70wNoGLh33PQsHBDZlI/j4nUNQd15MY5X/92Ob1NFABEB\nAAH+CQMIRSp2W2qMxDRglq5TPXl1mN6tLMFNDFo0S33Worw4ksagI8/RL3zp\nZ02h1c002Jfrqf/yBeluMhQpFNkOr4XuW1/gToPqawsGEDOd9XguB0dgNsfi\nZNwAD7RUuVB/0Ea0DQfsIoVxAmIcNL9jC/cZgod3LL9rqGczetehmiTRqwn1\nRNGeKLDKiAMEoD7P95WjU6oGXHMbb2WoFjjvb+z4WemOZNC/5AeNePeWNTug\nl2cDE/uPcKEWl1bDRt3SzWHsAcHhGwo7qrxWAemQIh883BUvUzHpYcgzN5rF\nhH5/KGUspZE7L9m2ZSWnXG/QDpfT/9pistIcigJu+4b1amUHX3eJSKFVyhp8\ndmVXNi4rK4d20dUBKBw/wPsXG/V5T3bLl5VthyJi90yNbH2VXSvwpR6SFmMS\n7ZRFl+ze+u/Wpu15MGLP1uCVK5veTpZSHE594uFuzWUAyWvH3yWyNlSvWns9\nqrFoeUQqoDxpB7qbElUNNaeky+DLNbqLnGN8Nwq9MbFhRiWd/4CqTlaBq6Qw\ndz7y+gzZ/E9WAiVXfrWHHChy2mbVaKsPRMcNp53jnbZlZuq+yayeAdgbV2Pr\nvad10nM8pO4HWg01Ye1IcQebuBg77ChMpldQypMimZnuy4WPsd0ddiclNydc\nuqfj+Ryb3cbMoIDSVDGSOetyBGn/bLK+It1xOH+Qyyh4XCMPIH+pzOQftybh\nT7adyD08PcO54Hc/ZHUOqUkh6uXtQQke35RzsxdyNHEEV1NfNXUm8uJRqBSL\nBcas64i3lHVljRxH7aKpFpQf9y/hD+gDrf+5plpQrO0jV2l2LFzxadEyR7Et\nzrBa5YW2pOFJmNXrGYSF7y80pvTnSRumHFyw1pQ/2Z0mN3KxA0FZTyhePEeD\nhd5xBZ8xfY5z+vqR+phRwhye272eNbXozTUibXRlc3QyMDBAcHJvdG9ubWFp\nbC5ibHVlIiA8bXRlc3QyMDBAcHJvdG9ubWFpbC5ibHVlPsLAfwQQAQgAKQUC\nW+HEOwYLCQcIAwIJEB40czCB7XHgBBUICgIDFgIBAhkBAhsDAh4BAAoJEB40\nczCB7XHgwuUIAKdXHYaN2PMulqPmd741lPVrV6VnWa6RrXLg5MT67TVqvllw\ncTNLZLFMbY8auQ4tJhMUI0KSuZDqp+3EHo1ZbrrBZWCYL8VAOvXR37lxeQ0a\n0M6gOI3+cx0/J+IV0WT4xlvV2jhHwLqMJZ5LkrdEtSSnxDbZpfKntUdZHHj1\nTTecm8NFkaggGDb5kTPhX3s5R66KSP9J+HN1KnIMHrXP6DKN53sWu6ORz+bV\nGOJZDMFdPH3cES3wjw5ea2wQ5wLNhN+SHG2aYPl4itqCP3jBrgWlT+wrSwNo\nwMLC+42A0W1i3CTLdcNbOmxxupWgYjMF6Hw4r+Ulr5gGqc15MOd8WY7HwwYE\nW+HEOwEIANmRqsRwlJ81rpsNI0LYRYD2RH0UHOaU4pTfcxe12zw3uPTgeUyM\nGWEbb8g3MePiCoNXAMeOwVfAfQKVQoMG6IEe3yT0kwZXl2/RTCWHhGnTZq5K\nG6Y45++zG8EithRmPElnl4VJq3zOHYDDpAWa1BgJg7WZ6EwzAG2svAjk972T\nYxJUGpHFNAfYnSLBWWWqB0u5QpChHk8UJZvjXwAqZZaIBpCCQ3jwByr4uFsd\n2RRyVCSu52oA4f/PeDX/0oEaBZAE3TxJqo1bwO+J2Z6wRFd3Rfu8srUNvxxU\n5s16xwpVMRBq1KtYM+a5dCvu4noyPV2YAYy2ewXaMrGvRY4RyncAEQEAAf4J\nAwi5WUBQ4SKjVmAATu/YA2qjU0ACUR06gz5RVZ3s43EJSVkzNbyWWGuARzgU\nLGV5oZdOOByvzBE7QXdr+D/3KMAocSAE3A/vaM+VkVLJV9TaybwA9/MlTsCc\nhAyXbwtOjyHGxPgTfjkn/CQ8CZj6wAlYW7QhvAcovbMQJwWM67jDJWOf4doJ\nSxgIxLzXizpY5cLJqB6XwHAIS33AYYyEh9UVFF/RuywmxJgmF9hvaAvS/CA9\nw85kRSmUH+V5zo4mdkKIcEzmLSz+W8HA4zt4Piz1c8aA3vx7ODAmwPzZSWuL\n1nSbcP2lwaghl9oUy9cLDoOsdZEQxjH/AtSthQ0mnGXeQDqlg94CULR29O1J\n+a4nTsXI4QV6cEeuVEykjPX7YlMEAzW+r9Achp0nb5NH+jG4UQSk8Zvr7P7S\njXQk1eectUzIIx4GEPVHI72NEUn8GRZVuOfhnOu0UEwTvwZXfRdejKAQCDXm\ny6PqaObobxB6O9gjd0wBcVISm5eHZTtd3WKe2qcwXTILaBb98g4mt4HepHBc\nopFWM/SsOmF+noTtgbv+5uUXUVrx7XL/nJ/ParHLtG1PU2Z6narmNqQJD+gH\n3yLYgesltUYFwozhpjYRyIT4jYzpj/tYc/m/8o9c93703PdTd7sixJPAVUpx\nqJO7GWel71g8K2AoSJFFgJXGx8HjryXm5uNpA5xmZYG4k0lL/8MNfjkkTB/N\nKxcHKxvcgfHl6oBfhK+SQtwAusZby/9+7s8gtnaHy45A4K9cA89V+2iTkNIn\n90ma2CjWEdeKbcMqtHNerhvWOQbfrzGLZUnpcKASppgeycxGvWoXYEq+mhOY\nqBP74s4kDGrRBoh323FNQGZCHiHSs1VL/VHq86eW0qk6GeRcu+SDxcQezMWr\n6M7ODACNUYDfReo0ecslpb2zykTCwGkEGAEIABMFAlvhxDsJEB40czCB7XHg\nAhsMAAoJEB40czCB7XHgqOIH/R2iYMwKP1D43FQc2+Jw/95KWU2jlW4CtLaG\nF3TAcDzI++hKp/1nwlUurSJcJTFaCfRIFrRPuQDLL0vaLCq62N+9nH0bfM8m\noSPz0Knu5EyXToS/phBlG24V2V26iy2jTlupWfdDCosaavlVpNzGBCsYiOxo\nC5Yek/1iAvAmwT/WlxReMDl7X4Lf7P2oluheXYCPjBiK9MuqFoTDA4bzGQm5\nYjl/ILUQemZNsWEw2+hAr0PAGas1SKVINx/pgFopVh8eWexMYW8NBZiPCgx3\n3fhf5MlPyZrpr9PTpzHIACX8llgJIzi6ZcnCLG76ZFKxZlIW+LBJ5l66JCnF\nGH6PtWY=\n=bc9T\n-----END PGP PRIVATE KEY BLOCK-----\n'; export const AUTH_RESPONSE_NO_UNLOCK = { AccessToken: '-----BEGIN PGP MESSAGE-----\nVersion: ProtonMail\nComment: https://protonmail.com\n\nwcBMA51hbeAaVlxHAQf/Qj7Hs+1apJsX/XXkcnOl62sCFOI15yR6HiIxeuyB\n5bil2G0sTepsj9ilk3r9rt2tshZDbFDFmIrp4ikJ7qs54eySALLGWd6hV2GN\n9ZiTucSWomBA6iHUk5RjTXIqU/AilnLgZhxr0YHZUXmqb7VnFUgqpXa3e8Bg\nNeBllmOzueYX3qCWBkrX98vKjh7HkaB7jMB/up1ej6DmvKRH7c38GqjHpu9U\nnLBHzJkP8mTOdwMVFTuwHmTB0zv/czLa5ouCsYaUvtPoaBbnFcxVSpJgTEj9\nR6EultpJmHdyGKjltiHJfKebWuZZYXFBGGg2ZGgRa/iwDAhqhci2RQ+Qis07\nINJgAZMc26Bw14uBLk8z3aUE7WJp8qj0pnldtkCW+v2D+7SU35Wkqp7SWEDB\nYrihq+GBLUmBaa/zRx2kvCBreIzzQXfBPPPIqS/YcoIsa7sqera1XTEJJRhc\nZOSaWhCorMhY\n=Rpgx\n-----END PGP MESSAGE-----\n', UID: '95c0ea8d92f759c13c2a17d3921daa75e761ce92', PasswordMode: 1, '2FA': { TOTP: 1, U2F: null, }, PrivateKey, KeySalt: Salt, ServerProof, }; export const AUTH_RESPONSE = { AccessToken: '-----BEGIN PGP MESSAGE-----\nVersion: ProtonMail\nComment: https://protonmail.com\n\nwcBMA7cnl/90zomAAQgAsaZrXlDG5gIPtsUiW4uu/dUz61tCub+1OzVfKHxP\nZOtwuLUynI1VqfXneE3HzRxWSCqZyHZSxemPuk09F3P6/H03yPPV9FffDKr7\nyQADaA5EAVNMj2iab2ZrPZupz3dfnbWZzdwtNX5ruKuxArIrR2vjrK6QyZQh\n+UWAl1IwJMbRjRx+9Tj0f+I+QhXbDIgYp0KuKOBnJT/p3vqBCcjuMcD24tIC\n8+PQNRr8z0x20pv6l9Q7zJP24b24gYWNbx0lmOIJwmoqhvED+Z2zx2gP0wmB\neyEV1cCA7Kz33Cg1dN9aXTyp7IJJNDT7xScD0IVL8au58+3eMhJmefIyPMqV\neNJgAZEfZ4MbQ+5F3Gq1+DjRUI/DqEpq99roHIcGGSeEQcG9pSZ3oY3MnP54\nn7zyIOrgFDgh/JD9qWGW0l+dau0tF59HSxjGLkEyQu537jc5GJYFCrapZOvM\nPpv89mFWjXkM\n=Jxxl\n-----END PGP MESSAGE-----\n', UID: '95c0ea8d92f759c13c2a17d3921daa75e761ce92', PasswordMode: 2, '2FA': { TOTP: 1, U2F: null, }, PrivateKey: PrivateKeyUnlock, KeySalt: 'CmCqJDEjv0c5yGNMfUVcZw==', ServerProof, }; export const AUTH_RESPONSE_CLEARTEXT = { AccessToken: '123', UID: '95c0ea8d92f759c13c2a17d3921daa75e761ce92', PasswordMode: 2, '2FA': { TOTP: 1, U2F: null, }, ServerProof, }; export const COOKIE_RESPONSE = {}; export const USER_RESPONSE = { User: { Keys: [ { ID: '6T3seNEkkEFpQIiSQw5SUNrzoeUDOzbcf9_Hm6g1CRnzSsXBfU2kIM8DlAq8ffl5l-go8VM5fBjhglJlRsqqeQ==', Primary: 1, PrivateKey: '-----BEGIN PGP PRIVATE KEY BLOCK-----\nVersion: ProtonMail\nComment: https://protonmail.com\n\nxcMGBFx1N0EBCAC1UM4jicJiaO6M+v1G4Lvll3fMmHrGLjKyCXojn3h50FDe\nsN644VJeR7LbhXNGwAeti1/KjNXHNnuPV4jZoPBVjgLo7SC/EXIDStETyhGA\nJCkAArIIOFKKAqFr/wXfhy0jkPtFHO8wNjfKNqZUzw9JGsCF3w/103YXI5tG\nbdq6R2KN6HCDqF7iKZKHAlQ1qcLDD+66IFtpKb11XyBjCAgsltrdcr9jyfPb\n5yw1sfxP7vMoaTVWMyKSCCF4AHXsC9qFB1QuPopjCMDxA4e+ObwYH+M/TOQf\n8rweZKxj+J2MTuJr+KFIfu/DNMqmyAfjjJEN7d4L7v5zOAmmZ6rcfUPNABEB\nAAH+CQMI8Yeq/Yf1E9tg3PZ1B8CzRfWgIrc4kRICnAvORF/BoKRep4gIZ8+3\nvEUw2kEZ8RE0g6MKKP7CzBUBcVx24LMLNbkiTO5rAdOsIt+OeqHtVTvpIiwM\nlgrJ+Cio3OzZ19jSA/mqfq/dV7DWhGROVyqAhzzuPxB+WAruyLMGcWmRHlSe\nkFG3pbsFlcRHPq6Y4ZrvdrxkHm+n9k+vIJq+sKPUoE0ImninDVspiJi60Vdt\nsZXFkDijngqaA4uaTn5t1Durn7/vMWUFs4lRR5RyMrEpG7zo3IF2QZCNAn/6\nmI9ev9Nq5VN7QSa2UUNaJsjMyaID9TuB4dM75fg9DjuwtdmEIlqDD4YRjr8K\ndazemmSDyybdWCMO8d4oZBUrMccvk97J788uzPziaFArAoeK+FUxLzi+NPQA\nbKbjsY8plMtY7aS9Fs2Td/AAyAWefnvjxMCKw8k8BIZvlmOZH4DbnwoEe/6L\nyYMnWZZimACYy1+DbYa8EdFgJS6OWNWJrsw1ordxyXrk5NmnKyBwgAliy5kw\nc4pW9gdiVVSrnsttrYTZ6w4IjSyOjUh1fhet80qfkwzCcK11Yo2DaGWg7f+E\nImrPxfpfOhjl80UNCUpJwjrPrQZPIcGsfi4tV4G4FWjSmOABYVjqwS/6dYiS\nH9mtFpfj/GaYi0kCWKo8uUxKBRQ6On5SK1KH2HEpoksM3vwKagh/VmpB0aVX\n5VeosIzavPhleQxh1lwOALGKx5GzB6ltvPK3DUSii82mo0yC+HaCMxXH2nFh\nhYM9M0yYeBSOYtGDc+DtOMKgPe6Z78/ZjqimOizp4K/x/0Tb7h65BqjnKU48\ntk8YI+T49CMztzz0nSol9qf2nVYMSyHx+8gHRcscenxbNuY+7/Rhj1ZLNEvF\n2SDouJwA6UtS9vqiAiTrNVo8OQ5kcvq9zTUibXRlc3QxMDBAcHJvdG9ubWFp\nbC5ibHVlIiA8bXRlc3QxMDBAcHJvdG9ubWFpbC5ibHVlPsLAdQQQAQgAHwUC\nXHU3QQYLCQcIAwIEFQgKAgMWAgECGQECGwMCHgEACgkQSlSdfkGeUJhBkwgA\ngQcX9GE5x71P/nZ8Hhch5Z5O6n53a3fW95X2QosY3kP4IIB9ntgZ9Vq01Sye\n1xJhI18w8eR0lL2mPZEH/rmy0zgS0o8f1Sdd0fJs7wp4OmfJc76crwHGH1NV\n5btmozLSAfD8/Ca5OsSxtBrhgWwMUvgha1trL9ZPiFLTDRXMasqoTizkwpAg\nFsSXufMFmCg7fSVaKkfVShkx0N1e4Y+BYJp48VY0GJPA8+29X0/zRuGh9d+u\nE4pQM8JUmtgxXULwXVYmdED/Nj+RtZ02WkkOYRi0I7Sb+ZrNQVcUPf6+ws6L\nKVy5T5amDpo6FHKGjcNdXwvwpqo8Mo1uuvlw/rC1DMfDBgRcdTdBAQgAtJG+\nrUnHPG6hiUx4TFT6fM4GvvzZiWhQDHJAfwdn6sOEbJeFFpwAGh+TyU4xEZVj\nRn8OwQgNIhFnjrCMZ1nfpdnl2TYGDpTK0zR1KRH4Q60J7y6YqcO1jtujdx7J\nKZ37+g/yrWhWWBe8EzxRSdv7uHWn2q1UJ4SsvnxheHoEsVvVno2orSwkkEWE\nRI9fJpYopRM2MPDlXY2YGUp5PE3sLmCXwag64UmJGwjZat6tW+xuHeD5Vag3\nQpqtTiRt4INNWP4AJM/DH54AWQMvgpghjEXntoiyaClwFJGesqkU/bzj8xl7\nkABkZdN9xHH5NAgAHBDEe2l4/WIYuHP+o0DSfwARAQAB/gkDCGHUQacyySNI\nYD9QoK2uyPZWJLeXGJ4LmxtEF8GGks6zsA5SEZ7+emEF5iNz8qMLvxH6+Jfe\nCeTgavZ9EXZ+2bU5kbc/mN8iUKghptFd7y4bhk/KNmzinkK1GbZb8ZJUjsjP\nuR5Mrl3GryqLXyjHhIvHMRvBp7964OtPmXsATmJsCd0k0HalNEjVqaEg78s+\n82bs0l2Awwlwmelp70UQGkyxTgRu+A6pntUODvUeeYyKst8i4y8odzdKwbTS\nu+JAZL/K1Hzsc+HalEQRRCGvuCQKwaoV4Dw0itMUPxotQMw6ximxeZKwsFWi\n0I6uKYwmrBzJvj03ugJWh4ybQfqaXgqkF2lxKU5EZ16kM/ZXTfCZktgI8Ygp\nUUkDHpqrwIYrplHeAv3zn5562Rgyi9zZFnOat69Ez67SoH4DI1SyhkhFgv6m\ncZRflMwugcrOFD8DfCIvhi31vOJxmoJWn7gIWlx3uW/z3LM14XFM5G+nmy0p\nm6ssm9cKatBeZ/8c8GwG3+3YkzYB25QYgf7rKpSv717vlsx0c7OtOKLXkLwX\n32O6rYViCMKtekyLJsT7VdU0GPmCmo57zPYvbWQOs+SES5KMTmol2Ti+ozGj\n2Bi3kyF1O/eP+vXnt/RQLIsJAcFk5TouCdyLMkOY0TjESsV3XKb3DkWLTHsF\nrfMJIghJ0rYDe0tUx3X4jwjFsQvoCisP8/mI+/znUspqrH24U764WCV9DGyL\nDmWfCIvdgLFqvgmBqBvNKL+VsjDKnP+f9eXFKIq2PY0hq2zhBqrJ4wlSWdRi\n/cFdlSUaGfI2P/eEKLIOQ4V0p4nBn3a1+FtyLcHDXGd1uZFufFo1TRNNjKYH\nvvVXm0bKqgMQwZ7QpWqBZJa+xY6hVmejKSJ53EIyPsIlJ06L6Ch2i+3A6E5F\nTfrN1uMZWXe++8LAXwQYAQgACQUCXHU3QQIbDAAKCRBKVJ1+QZ5QmDvdCACu\n1d3U7ozK0AgVb226DZeY29A+15QK2ydY141yyzT6vV4JJSbTbqQA6Yw9U4vu\nlk5dyq5FhPW0IsdlDGH+TrHnj+WZnUqFrnFSkx/fQSSnjzMBSMZ7io3ROqJX\neFcoLOHLzGK++wN9q6xo70rO0s/Z1aZeIzEY9vBgWd3tb8PuQgmBL/1iVMWu\nmaGq+GGDnOK+NdVewaO2J5oP2UcFvV6JuD6j4zAJSAWB+Uo82VyCgmcC70rK\n707lRdcH5UWWyKowivXnC3eay8Y2rIjgDtY1orI9fQnDx0bHy6UIeRjad3hl\nwaHqSSdqchXFsuSaCkMsmiZx3rVTXyx6J1Hbkf9L\n=aLGy\n-----END PGP PRIVATE KEY BLOCK-----\n', }, { ID: 'ZtxF90vTPmN7sZO1G7wHoVcJWRu1BLFS_J2sYKpw-2xew8Ld0qIS0TjddC83v5QQWuUYmpk73R3pEQA4mEoSDA==', Primary: 0, PrivateKey: '-----BEGIN PGP PRIVATE KEY BLOCK-----\nVersion: ProtonMail\nComment: https://protonmail.com\n\nxcMGBFrPbwIBCAC6XY1gzkGYETAZRwUnLYXPvpvnw9P34NO6FhhEnBTa/oBc\ngY4ahchg2rPP3XiD8PX4VpGcfWt+FDwo8R0LbJ08aEzWuAYMTnm3jSmmMENd\ncJimAvIjKAX/fRrz81i9mtHAXGrna26mxEL/MMp+426eDmhpQyz4JloFdTet\n3I8aOIzAOL9xLxADXMIUN6bg6rMQSHsRcI5ficaZ1QKbspaxvcJJ28XvbQq4\npKl7+yAZHkz4WGwe2C+BuKyCvV4Krolpzlh8cO7nkpT/DW3SHKmtFIdgPkMu\nc19reVQ9WX/NlAMW3GREANNnaRUIh02ZEJHa+A3op3wTlr/O947WSXu1ABEB\nAAH+CQMIx0Mg/bM/Ur1gyqRv/W0wod+pYt/Ub9Rvc5bwmBMVTuSSMhTu+bZr\npkpLWKtkrCDqlo8Eb7SuTu8apmWxbZH8hJ0xT2E8IMs4jeJkwp3yL757EbXd\njM37wuEBQ6MObt6MBurgzNg+hG47Qr38A77y3cnpm0IXzTKx3yrzIFZ0pFj5\nTggVAkMvsEMtmjtlhf0m5BvxHtruZWjLreQ2MNSVj5sZIRlYYUx/9HOAM45L\nvdjLrHdX5fuf6tAyEHrtPhO6OqlbvIyTxCcKw4vNvY7pnofTZkIjIhwU6uc/\n761z0LVAUbLRYRBlk4boK1hq0fNslYRCR8pWQIJ/DbjY3uOFk3LBDmGNQP6v\nBaoGIJnsFxpzdS3UYJT4ny30UDIqWahtq658AOd2XKdIkwmx3aguM2iWZgO4\n+DN6JQg7rVE+pSm6CIqQJmvSJSpTAf/a76a8wOaTrvaii5Ce2NGc8B3YZZ4O\nyagmOVFreN0a+cs6x61uZgaxmyXLODsxMdlE09zb5GcVCkG7x3LT+0ks0g0j\njQ6fBjww10fNLZVasJ/A3whC0Lc6eTXTqsNMC/Ddfsy42BET+Af4ddxB+0+9\nmx0YFHnkuU+Wg/EbL8UWs+IB9/ay6RX3kxz8YXYNDnTYzIhJT7oRS09QNN2K\nqY7cvCx8d2TWxIxEIygh1qU0q6kgDq9HnUUYTSfD2pk3xKFEnS4LoNyTS1NQ\namia+/f3H+V9Y/CKBZO9U7zQ0Yvsm3J60fykUCED63Put6eCI4MmjOYwfuXb\nBSZ65L6VMidKxZz1Ttp6bnmrEo6Nxztuh9NnHHTqaSg0NnQ09lhZ2HWqBIbO\nCdNYcZiKg+z5ch9ngkxVoHiyIWGt5GoLG5SGQqBeGYsu9CfyxBLw6ptc4ZmR\nBOnJ3vIVD25OpR3/r7J5uBpVW7QWW08LzTNtdGVzdDEwMEBwcm90b25tYWls\nLmJsdWUgPG10ZXN0MTAwQHByb3Rvbm1haWwuYmx1ZT7CwHUEEAEIACkFAlrP\nbwMGCwkHCAMCCRB/4g3+H6/cWwQVCAoCAxYCAQIZAQIbAwIeAQAAwj0IAKUw\nYE0NuAbvktEaKFCEY3uhdkQ30KDh3pTK9pcum3nGHJXSjbhCCAieqpNJoyG2\nqLAwa1jhby8p6FTv6GfgUX4QIJk/PUlyr7m8hIy1G0EcsHj6datT1myhMUq3\ntYUhnxy5JfLhkTEMobMa3zYa5J2nb+W4Jch4DjShuaJYk7F6N7AObjnFUGdd\nLMLXS2umLqOybwu7jB0Ousim/HPssOJG7W3kP/EmfyENEWsSjtwI8qn2kW0k\npX5UI0oQkkVYDPRTZTAnyNoCp3JEjJ9ILAfmyWlXvO8ArzTfM3h5vtncSlPa\nQVtYqAhpMY6MYQ1/UBdRRA/2S0JP1s3uiW9fmiLHwwYEWs9vAgEIALy3d68L\nU3tzaspv90wuoKxoDMdRUmuYWbjHjokAr+MHNNYxEe/yLYrFmRwYfN/yned3\ntr+g6r3DtYNm3K3kxWVrgUdamjZBfqFV27LKADROTRHbuEFt+T7PE6liD5vx\nMGV+OaUxwY0glqoPLRV19dHw0qpLdIIPCqqS/GXsFDbuVIZGfd+/xad4Oudt\nplDCdWAe1fKB4eV/GW431+Rm+2zf8T7vwQa1o1YZFDkUte6XKbnLSRhlOxQF\n/+MoW0UKMdswWg1VBM+zKGD/ekc0PGICI9HSgR4ALKE11qm/VWiExuK55fBQ\ngEb8BGT8c95wuUTjuAGaTtpm32pklPD6PZcAEQEAAf4JAwhMb97zN5rjzWA9\nZ+Gft0O3ONlxVVi5XjE2wVuTmlDU5RW0fwJyOVkWsu3J+c88+GEZV/sItpW+\nx2p59DPV8/yjLqcHKYl+FwqjzFCOvYTkWaAou+IodeLWQUedtATvOkGa+QTo\nZRGu3bbaue1+DyE8kMNYQSYAIPGWIyzESb1fkPoV+pWt8g9Lg8lQU9MxXItb\nhFSrtOWOU5UKUjezN0Hj0vX54y2OTE0mOLa4/9oGz8mhv027p/LNwUV7xV+C\nYMflygc4sfVTjuUoCLzW2QoTHBNbHtROAFGkAe7+F0YIIjqfNzBXaaE29cMd\n/DeAFrcvwZicyLw8jF8kdoID1DpyvN8vbZ2SLpMnfV8w/sep6mkrpeJ/O6lV\nfZMjJr061A6i6bIuHo/2pGgH5dDwEkFKnw9+0tpxuvNDsKIEyxZqQe6mOke+\nzzVhxVYaiYD6Rw05GeY5A8qU9POhSS9zG/VaggjCXysSzB7mWhk8Pr78UGlT\nM8+37ah2C2cm6GtGCg1t0b+h/dSgw0ZV2Sp5LvJjqW8f4SyPGRzl702duFuw\nH/dNvMZVRyPs2ny0y/aYazb0A7IUkP3x8ati0TNjz35QzV2ddiCXIL1BvYec\ntsfmny05xgmhw6exL7ef1f+55D6IyLKrmKgHZtpC4B/KYX5ASY1Yr3YG5FAi\nxFJ6mL+g0lNF304MRRKBGKrUPqtFtdI0z9g69wtuhdYSmaTHoEH0pRWylEkF\nX7bkHnlsbTUWQEfVcnKhztwEGg0fVwkjzy3j7/JamN/xMz5Bnfo1T1U7v/C1\niQyZWKi6i9NuCgbMd7q68zawJt0wvhrqE4+V1lZ+tePi1K1tW3ZcZmImyUbW\nXZOQ1PhMdnTttGgDcv/gdKF4plgKCRRUziw2LjFFRUkCRFOvnrMxeRbkQX0L\nDdjEwSFmTTPCwF8EGAEIABMFAlrPbwMJEH/iDf4fr9xbAhsMAACWHgf/bN0k\nNomeevlfLtBkTo2ro0o9O4ywxyldFcfmBhvq+812OQ4j7YXce9WrkXjiu4Tz\nmrM/Xq7ZpMA09TsGkCXdtw612fSmPzAVY1zLdpjGB/8EVzlxoF14Nj9dEgah\nrvftQlJkfEJvqsxKGVlhBpdKIJqkBUEHK03DwTW+VpngZplPdp4bL3wXxll4\nL7FDpgCjm/rTykOvvXC+OODpEVldTJHsoSGrvv03z87sJhoJ/jiLSvUcbmUo\ns3ks9CT6QQcluDcFY2BMo37asXlefJuImr4tlwA1bJ64d2r4x1bh+ItzK3jq\n/P72/yFGChFiW0zc2F1SvaQYRToNLKFZVGYSGw==\n=CBJG\n-----END PGP PRIVATE KEY BLOCK-----\n', }, ], }, }; export const USER_RESPONSE_NO_KEYS = { User: { Keys: [], }, }; export const SALT_RESPONSE = { KeySalts: [ { ID: '6T3seNEkkEFpQIiSQw5SUNrzoeUDOzbcf9_Hm6g1CRnzSsXBfU2kIM8DlAq8ffl5l-go8VM5fBjhglJlRsqqeQ==', KeySalt: 'P1ep8VKlNMgMblolFu+F7Q==', }, { ID: 'ZtxF90vTPmN7sZO1G7wHoVcJWRu1BLFS_J2sYKpw-2xew8Ld0qIS0TjddC83v5QQWuUYmpk73R3pEQA4mEoSDA==', KeySalt: 'MDRDvBUu1bKtKyG3/v5BXw==', }, { ID: 'cLKeYpv7gDHugAfXyRKZtw3mO2p2-wh7gK0LzMZ3YEuuyCUkyXAiFwzqafHyTdfRmkomgeAfL3AIxnSlizUxnQ==', KeySalt: 'MDRDvBUu1bKtKyG3/v5BXw==', }, { ID: '8AoGzP-L1ZDAG-k2L96iHi6wZaA1voC8O8mL5dDigjWDaXyL0vn8xlLxnArS6b3WiAUDKNrV_ggV97fxUiPS3g==', KeySalt: 'MDRDvBUu1bKtKyG3/v5BXw==', }, { ID: 'LZf3JB-AHweqjyMgBDvKnLC7FoZcO0Qlz5-eMLlEuiA6epFioyddjNaEHLPAh39SyAcdeGDuUraxvBpSWHFD5A==', KeySalt: 'P1ep8VKlNMgMblolFu+F7Q==', }, ], };
8,781
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/authentication/loginWithFallback.spec.js
import { disableRandomMock, initRandomMock } from '@proton/testing/lib/mockRandomValues'; import loginWithFallback from '../../lib/authentication/loginWithFallback'; import { Modulus, Salt, ServerEphemeral, ServerProof } from './login.data'; const getInfoResult = (version) => ({ Username: 'test', Version: version, Modulus, ServerEphemeral, Salt, }); const getResponse = (json) => { const result = { clone: () => result, json: () => json, }; return result; }; describe('login with fallback', () => { beforeAll(() => initRandomMock()); afterAll(() => disableRandomMock()); it('should login directly with auth version 4', async () => { let authCalls = 0; const mockApi = async ({ url }) => { if (url.includes('info')) { return getInfoResult(4); } if (url === 'core/v4/auth') { authCalls++; return getResponse({ ServerProof, foo: 'bar', }); } }; const { authVersion, result } = await loginWithFallback({ api: mockApi, credentials: { username: 'test', password: '123' }, }); expect(authVersion).toEqual(4); expect(result).toEqual(jasmine.objectContaining({ foo: 'bar' })); expect(authCalls).toEqual(1); }); it('should login when the fallback version is unknown', async () => { const apiCalls = []; const mockApi = async (args) => { const { url } = args; if (url.includes('info')) { return getInfoResult(0); } if (url === 'core/v4/auth') { apiCalls.push(args); if (apiCalls.length === 1) { // eslint-disable-next-line return Promise.reject({ data: { Code: 8002 } }); } return Promise.resolve( getResponse({ ServerProof: 'ayugXfnft4D+YtSWCv/Kx1IIXAS850wY8R4BfnD1TwhvRWgu/Mzs0S3DuSwoIV6sE8BcjqimBhxFwZWW1L0Y059UM75FnJZ9H4D/o2CmMze3vOg2ShIpVdrfgMTV8BGlwhzHt6z2yH+m+6WfW7RSKmai46Q7Cj4brTrvxY7xWzsFtJVUbJcgwfSOmi6OBZ1Ouu/yKuwQi554tbBogaLky938SmMP3nDLpvhJCLM9j47eyN2QWU1kFOVu9yy9vN5i7ZuEhREApnX2D5qn3+63bWnxysB0Qx8LD30OnRrxGni4TgpxtsNXbbxMH1XdPrkkeyUxAL0Q25sbTZUdL+zfpA==', foo: 'bar', }) ); } }; const { authVersion, result } = await loginWithFallback({ api: mockApi, credentials: { username: 'test', password: '123' }, }); expect(authVersion).toEqual(0); expect(result).toEqual(jasmine.objectContaining({ foo: 'bar' })); expect(apiCalls.length).toEqual(2); }); it('not login when the credentials are incorrect', async () => { const mockApi = async (args) => { const { url } = args; if (url.includes('info')) { return getInfoResult(4); } if (url === 'core/v4/auth') { // eslint-disable-next-line return Promise.reject({ data: { Code: 8002 } }); } }; const promise = loginWithFallback({ api: mockApi, credentials: { username: 'test', password: '123' }, }); await expectAsync(promise).toBeRejectedWith({ data: { Code: 8002 }, }); }); it('not login when the credentials are incorrect and fallback', async () => { let authCalls = 0; const mockApi = async ({ url }) => { if (url.includes('info')) { return getInfoResult(0); } if (url === 'core/v4/auth') { authCalls++; // eslint-disable-next-line return Promise.reject({ data: { Code: 8002 } }); } }; const promise = loginWithFallback({ api: mockApi, credentials: { username: 'test', password: '123' }, }); await expectAsync(promise).toBeRejectedWith({ data: { Code: 8002 }, }); expect(authCalls, 2); }); });
8,782
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/authentication/pathnameHelper.spec.ts
import { getBasename, getLocalIDFromPathname } from '../../lib/authentication/pathnameHelper'; describe('basename helper', () => { [ { name: 'should get basename for 0', input: 0, output: '/u/0' }, { name: 'should get basename for 1', input: 1, output: '/u/1' }, ].forEach(({ name, input, output }) => { it(name, () => { expect(getBasename(input)).toEqual(output); }); }); }); describe('local id pathname helper', () => { [ { name: 'should get simple id 0', input: '/u/0', output: 0 }, { name: 'should get simple id 1', input: '/u/1', output: 1, }, { name: 'should get id with or without starting slash', input: 'u/1', output: 1, }, { name: 'should get from pathname', input: '/u/1/my-complicated/path/', output: 1, }, { name: 'should get id with or without starting slash', input: 'u/1', output: 1, }, { name: 'should get id with or without starting slash', input: 'u/123/my-complicated/path', output: 123, }, { name: 'should not get id if it does not starts with /foo', input: '/foo/u/2/my-complicated/path', output: undefined, }, { name: 'should not get id if it starts with foo', input: 'foo/u/2/my-complicated/path', output: undefined, }, { name: 'should not get id if it starts with a whitespace', input: ' /u/2/my-complicated/path', output: undefined, }, ].forEach(({ name, input, output }) => { it(name, () => { expect(getLocalIDFromPathname(input)).toEqual(output); }); }); });
8,783
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/alarms.spec.ts
import { differenceInDays, differenceInHours, differenceInMinutes, differenceInWeeks } from 'date-fns'; import { enUS } from 'date-fns/locale'; import { dedupeAlarmsWithNormalizedTriggers, dedupeNotifications, filterFutureNotifications, getAlarmMessage, sortNotificationsByAscendingTrigger, } from '../../lib/calendar/alarms'; import { normalizeTrigger } from '../../lib/calendar/alarms/trigger'; import { NOTIFICATION_TYPE_API, NOTIFICATION_UNITS, NOTIFICATION_WHEN } from '../../lib/calendar/constants'; import { propertyToUTCDate } from '../../lib/calendar/vcalConverter'; import { DAY, HOUR, MINUTE, WEEK } from '../../lib/constants'; import { convertUTCDateTimeToZone, convertZonedDateTimeToUTC, toUTCDate } from '../../lib/date/timezone'; import { pick } from '../../lib/helpers/object'; import { DateTime, NotificationModel, VcalDateProperty, VcalTriggerProperty, VcalValarmRelativeComponent, VcalVeventComponent, } from '../../lib/interfaces/calendar'; const formatOptions = { locale: enUS }; const tzidEurope = 'Europe/Zurich'; const tzidAsia = 'Asia/Seoul'; const getNow = (fakeZonedNow: DateTime, tzid = tzidEurope) => toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzid)); describe('getAlarmMessage', () => { const testFakeZonedDate = { year: 2019, month: 10, day: 13, hours: 20, minutes: 0, seconds: 0 }; const testComponent = { dtstart: { value: { ...testFakeZonedDate, isUTC: false }, parameters: { tzid: tzidEurope }, }, summary: { value: 'test alarm' }, } as VcalVeventComponent; const testFulldayComponent = { dtstart: { value: pick(testFakeZonedDate, ['year', 'month', 'day']), parameters: { type: 'date' }, }, summary: { value: 'test alarm' }, } as VcalVeventComponent; const start = toUTCDate(convertZonedDateTimeToUTC(testFakeZonedDate, tzidEurope)); it('treats the part day event as "starts now" when within 30 seconds of the beginning', () => { const commonProps = { component: testComponent, start, tzid: tzidEurope, formatOptions, }; expect( getAlarmMessage({ ...commonProps, now: getNow({ ...testFakeZonedDate, minutes: testFakeZonedDate.minutes - 1, seconds: 29 }), }) ).toEqual('test alarm starts at 8:00 PM'); expect( getAlarmMessage({ ...commonProps, now: getNow({ ...testFakeZonedDate, seconds: 31 }), }) ).toEqual('test alarm started at 8:00 PM'); expect( getAlarmMessage({ ...commonProps, now: getNow({ ...testFakeZonedDate, minutes: testFakeZonedDate.minutes - 1, seconds: 39 }), }) ).toEqual('test alarm starts now'); expect( getAlarmMessage({ ...commonProps, now: getNow({ ...testFakeZonedDate, seconds: 30 }), }) ).toEqual('test alarm starts now'); }); it('it should display the right notification for events happening today', () => { const fakeZonedNow = { ...testFakeZonedDate, hours: 1 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm starts at 8:00 PM' ); }); it('it should display the right notification for full-day events happening today', () => { const fakeZonedNow = { ...testFakeZonedDate, hours: 1 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect( getAlarmMessage({ component: testFulldayComponent, start, now, tzid: tzidEurope, formatOptions }) ).toEqual('test alarm starts today'); }); it('it should display the right notification for events happening tomorrow', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 12 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm starts tomorrow at 8:00 PM' ); }); it('it should display the right notification for full-day events happening tomorrow', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 12 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect( getAlarmMessage({ component: testFulldayComponent, start, now, tzid: tzidEurope, formatOptions }) ).toEqual('test alarm starts tomorrow'); }); it('it should display the right notification for full-day events happening yesterday', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 14 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect( getAlarmMessage({ component: testFulldayComponent, start, now, tzid: tzidEurope, formatOptions }) ).toEqual('test alarm started yesterday'); }); it('it should display the right notification for events happening yesterday', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 14 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm started yesterday at 8:00 PM' ); }); it('it should display the right notification for events happening later this month', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 5 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm starts on Sunday 13th at 8:00 PM' ); }); it('it should display the right notification for full-day events happening later this month', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 5 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect( getAlarmMessage({ component: testFulldayComponent, start, now, tzid: tzidEurope, formatOptions }) ).toEqual('test alarm starts on Sunday 13th'); }); it('it should display the right notification for events happening earlier this month', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 22 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm started on Sunday 13th at 8:00 PM' ); }); it('it should display the right notification for full-day events happening earlier this month', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 22 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect( getAlarmMessage({ component: testFulldayComponent, start, now, tzid: tzidEurope, formatOptions }) ).toEqual('test alarm started on Sunday 13th'); }); it('it should display the right notification for events happening later this year', () => { const fakeZonedNow = { ...testFakeZonedDate, month: 7 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm starts on Sunday 13th October at 8:00 PM' ); }); it('it should display the right notification for full-day events happening later this year', () => { const fakeZonedNow = { ...testFakeZonedDate, month: 7 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect( getAlarmMessage({ component: testFulldayComponent, start, now, tzid: tzidEurope, formatOptions }) ).toEqual('test alarm starts on Sunday 13th October'); }); it('it should display the right notification for events happening earlier this year', () => { const fakeZonedNow = { ...testFakeZonedDate, month: 12 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm started on Sunday 13th October at 8:00 PM' ); }); it('it should display the right notification for full-day events happening earlier this year', () => { const fakeZonedNow = { ...testFakeZonedDate, month: 12 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect( getAlarmMessage({ component: testFulldayComponent, start, now, tzid: tzidEurope, formatOptions }) ).toEqual('test alarm started on Sunday 13th October'); }); it('it should display the right notification for events happening in future years', () => { const fakeZonedNow = { ...testFakeZonedDate, year: 2002 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm starts on Sunday, October 13th, 2019 at 8:00 PM' ); }); it('it should display the right notification for full-day events happening in future years', () => { const fakeZonedNow = { ...testFakeZonedDate, year: 2002 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect( getAlarmMessage({ component: testFulldayComponent, start, now, tzid: tzidEurope, formatOptions }) ).toEqual('test alarm starts on Sunday, October 13th, 2019'); }); it('it should display the right notification for events happening in past years', () => { const fakeZonedNow = { ...testFakeZonedDate, year: 2022 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm started on Sunday, October 13th, 2019 at 8:00 PM' ); }); it('it should display the right notification for full-day events happening in past years', () => { const fakeZonedNow = { ...testFakeZonedDate, year: 2022 }; const now = toUTCDate(convertUTCDateTimeToZone(fakeZonedNow, tzidEurope)); expect( getAlarmMessage({ component: testFulldayComponent, start, now, tzid: tzidEurope, formatOptions }) ).toEqual('test alarm started on Sunday, October 13th, 2019'); }); it('it should display the right notification for events happening both this month and next year', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 5 }; const now = toUTCDate(convertUTCDateTimeToZone(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm starts on Sunday 13th at 8:00 PM' ); }); it('it should display the right notification for events happening both this month and next year', () => { const fakeZonedNow = { ...testFakeZonedDate, day: 5 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm starts on Sunday 13th at 8:00 PM' ); }); it('it should take into account day changes due to timezone differences', () => { const fakeZonedNow = { ...testFakeZonedDate, hours: 10 }; const now = toUTCDate(convertZonedDateTimeToUTC(fakeZonedNow, tzidEurope)); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidEurope, formatOptions })).toEqual( 'test alarm starts at 8:00 PM' ); expect(getAlarmMessage({ component: testComponent, start, now, tzid: tzidAsia, formatOptions })).toEqual( 'test alarm starts tomorrow at 3:00 AM' ); }); }); describe('filterFutureNotifications', () => { it('it should filter future part-day notifications', () => { const isAllDay = false; const atSameTimeNotifications = [ { id: '1', unit: NOTIFICATION_UNITS.MINUTE, type: NOTIFICATION_TYPE_API.EMAIL, when: NOTIFICATION_WHEN.AFTER, value: 0, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 0, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.EMAIL, when: NOTIFICATION_WHEN.AFTER, value: 0, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 0, isAllDay, }, ]; const beforeNotifications = [ { id: '1', unit: NOTIFICATION_UNITS.MINUTE, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.EMAIL, when: NOTIFICATION_WHEN.BEFORE, value: 2, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay, }, ]; const afterNotifications = [ { id: '1', unit: NOTIFICATION_UNITS.MINUTE, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.AFTER, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.MINUTE, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.AFTER, value: 1, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.EMAIL, when: NOTIFICATION_WHEN.AFTER, value: 2, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.AFTER, value: 1, isAllDay, }, ]; const notifications = [...beforeNotifications, ...atSameTimeNotifications, ...afterNotifications]; const expected = [...beforeNotifications, ...atSameTimeNotifications]; expect(filterFutureNotifications(notifications)).toEqual(expected); }); it('it should filter future all-day notifications', () => { const isAllDay = true; const onSameDayNotifications = [ { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.AFTER, value: 0, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.EMAIL, when: NOTIFICATION_WHEN.BEFORE, value: 0, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.EMAIL, when: NOTIFICATION_WHEN.AFTER, value: 0, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 0, isAllDay, }, ]; const beforeNotifications = [ { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.EMAIL, when: NOTIFICATION_WHEN.BEFORE, value: 2, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay, }, ]; const afterNotifications = [ { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.AFTER, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.AFTER, value: 1, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.EMAIL, when: NOTIFICATION_WHEN.AFTER, value: 2, isAllDay, }, { id: '1', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.AFTER, value: 1, isAllDay, }, ]; const notifications = [...beforeNotifications, ...onSameDayNotifications, ...afterNotifications]; const expected = [...beforeNotifications, ...onSameDayNotifications]; expect(filterFutureNotifications(notifications)).toEqual(expected); }); }); describe('normalizeTrigger', () => { const dtstartPartDay = { value: { year: 2020, month: 5, day: 11, hours: 12, minutes: 30, seconds: 0, isUTC: true }, }; const dtstartAllDay = { value: { year: 2020, month: 5, day: 11 }, parameters: { type: 'date' }, } as VcalDateProperty; const utcStartPartDay = propertyToUTCDate(dtstartPartDay); it('should keep just one component for part-day events with relative triggers', () => { const triggerValues = [ { weeks: 1, days: 6, hours: 0, minutes: 30, seconds: 0, isNegative: true }, { weeks: 0, days: 1, hours: 2, minutes: 1, seconds: 30, isNegative: false }, { weeks: 1, days: 3, hours: 2, minutes: 0, seconds: 0, isNegative: true }, { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 30, isNegative: false }, { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: true }, { weeks: 2, days: 7, hours: 7 * 24, minutes: 0, seconds: 0, isNegative: true }, ]; const expected = [ { weeks: 0, days: 0, hours: 0, minutes: (WEEK + 6 * DAY + 30 * MINUTE) / MINUTE, seconds: 0, isNegative: true, }, { weeks: 0, days: 0, hours: 0, minutes: (DAY + 2 * HOUR + MINUTE) / MINUTE, seconds: 0, isNegative: false }, { weeks: 0, days: 0, hours: (WEEK + 3 * DAY + 2 * HOUR) / HOUR, minutes: 0, seconds: 0, isNegative: true }, { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: false }, { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: true }, { weeks: 4, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: true }, ]; const results = triggerValues.map((trigger) => normalizeTrigger({ value: trigger }, dtstartPartDay)); expect(results).toEqual(expected); }); it('should keep just one component for part-day events with absolute triggers', () => { const triggerValues = [ { year: 2020, month: 5, day: 2, hours: 9, minutes: 0, seconds: 0, isUTC: true }, { year: 2020, month: 4, day: 12, hours: 9, minutes: 30, seconds: 0, isUTC: true }, { year: 2020, month: 5, day: 22, hours: 12, minutes: 30, seconds: 0, isUTC: true }, { year: 2020, month: 8, day: 1, hours: 0, minutes: 15, seconds: 0, isUTC: true }, { year: 2000, month: 5, day: 15, hours: 12, minutes: 30, seconds: 0, isUTC: true }, ]; const utcDates = triggerValues.map((dateTime) => propertyToUTCDate({ value: dateTime })); const expected = [ { weeks: 0, days: 0, hours: 0, minutes: differenceInMinutes(utcStartPartDay, utcDates[0]), seconds: 0, isNegative: true, }, { weeks: 0, days: 0, hours: differenceInHours(utcStartPartDay, utcDates[1]), minutes: 0, seconds: 0, isNegative: true, }, { weeks: 0, days: -differenceInDays(utcStartPartDay, utcDates[2]), hours: 0, minutes: 0, seconds: 0, isNegative: false, }, { weeks: 0, days: 0, hours: 0, minutes: -differenceInMinutes(utcStartPartDay, utcDates[3]), seconds: 0, isNegative: false, }, { weeks: differenceInWeeks(utcStartPartDay, utcDates[4]), days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: true, }, ]; const results = triggerValues.map((triggerValue) => { const trigger = { value: triggerValue, parameters: { type: 'date-time' }, } as VcalTriggerProperty; return normalizeTrigger(trigger, dtstartPartDay); }); expect(results).toEqual(expected); }); it('should keep all components for all-day events (except forbidden combinations of weeks and days) for relative triggers', () => { const triggerValues = [ { weeks: 1, days: 6, hours: 0, minutes: 30, seconds: 0, isNegative: true }, { weeks: 0, days: 1, hours: 2, minutes: 1, seconds: 30, isNegative: false }, { weeks: 1, days: 3, hours: 2, minutes: 0, seconds: 0, isNegative: true }, { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 30, isNegative: false }, { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: true }, ]; const expected = [ { weeks: 1, days: 6, hours: 0, minutes: 30, seconds: 0, isNegative: true }, { weeks: 0, days: 1, hours: 2, minutes: 1, seconds: 0, isNegative: false }, { weeks: 0, days: 10, hours: 2, minutes: 0, seconds: 0, isNegative: true }, { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: false }, { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: true }, ]; const results = triggerValues.map((trigger) => normalizeTrigger({ value: trigger }, dtstartAllDay)); expect(results).toEqual(expected); }); it('should keep all components for all-day events (except forbidden combinations of weeks and days) for absolute triggers', () => { const triggerValues = [ { year: 2020, month: 5, day: 2, hours: 9, minutes: 0, seconds: 0, isUTC: true }, { year: 2020, month: 4, day: 12, hours: 9, minutes: 30, seconds: 0, isUTC: true }, { year: 2020, month: 5, day: 22, hours: 12, minutes: 30, seconds: 0, isUTC: true }, { year: 2020, month: 8, day: 1, hours: 0, minutes: 15, seconds: 0, isUTC: true }, { year: 2000, month: 5, day: 15, hours: 12, minutes: 30, seconds: 0, isUTC: true }, ]; const expected = [ { weeks: 0, days: 8, hours: 15, minutes: 0, seconds: 0, isNegative: true }, { weeks: 0, days: 28, hours: 14, minutes: 30, seconds: 0, isNegative: true }, { weeks: 0, days: 11, hours: 12, minutes: 30, seconds: 0, isNegative: false }, { weeks: 0, days: 82, hours: 0, minutes: 15, seconds: 0, isNegative: false }, { weeks: 1042, days: 6, hours: 11, minutes: 30, seconds: 0, isNegative: true }, ]; const results = triggerValues.map((triggerValue) => { const trigger = { value: triggerValue, parameters: { type: 'date-time' }, } as VcalTriggerProperty; return normalizeTrigger(trigger, dtstartAllDay); }); expect(results).toEqual(expected); }); }); describe('dedupeNotifications', () => { it('de-duplicates alarms as expected', () => { const notifications = [ { id: 'one', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay: false, }, { id: 'two', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 7, isAllDay: false, }, { id: 'three', unit: NOTIFICATION_UNITS.HOUR, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 168, isAllDay: false, }, { id: 'four', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay: true, at: new Date(2000, 1, 1), }, { id: 'five', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 7, isAllDay: true, at: new Date(2000, 1, 1), }, { id: 'six', unit: NOTIFICATION_UNITS.HOUR, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 168, isAllDay: true, at: new Date(2000, 1, 1), }, ]; expect(dedupeNotifications(notifications)).toEqual([ { id: 'one', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay: false, }, { id: 'six', at: new Date(2000, 1, 1), isAllDay: true, type: NOTIFICATION_TYPE_API.DEVICE, unit: NOTIFICATION_UNITS.HOUR, value: 168, when: NOTIFICATION_WHEN.BEFORE, }, ]); }); it('sorts when deduping', () => { const notifications = [ { id: '14-days', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 14, isAllDay: false, }, { id: '24-hours', unit: NOTIFICATION_UNITS.HOUR, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 24, isAllDay: false, }, { id: 'two-weeks', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 2, isAllDay: false, }, { id: '1-day', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay: false, }, ]; expect(dedupeNotifications(notifications)).toEqual([ { id: '1-day', unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay: false, }, { id: 'two-weeks', unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 2, isAllDay: false, }, ]); }); }); describe('dedupeAlarmsWithNormalizedTriggers()', () => { it('dedupes alarms', () => { const alarms: VcalValarmRelativeComponent[] = [ { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 0, days: 0, hours: 24, minutes: 0, seconds: 0, isNegative: true, }, }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 0, days: 1, hours: 0, minutes: 0, seconds: 0, isNegative: false, }, }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 0, days: 0, hours: 0, minutes: 20160, // 2 weeks seconds: 0, isNegative: true, }, }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 0, days: 14, // 2 weeks hours: 0, minutes: 0, seconds: 0, isNegative: true, }, }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 0, days: 0, hours: 337, minutes: 0, seconds: 0, isNegative: true, }, }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: true, }, }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 0, days: 1, hours: 0, minutes: 0, seconds: 0, isNegative: true, }, }, }, ]; const expectedAlarms: VcalValarmRelativeComponent[] = [ { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 0, days: 1, hours: 0, minutes: 0, seconds: 0, isNegative: false, }, }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 0, days: 1, hours: 0, minutes: 0, seconds: 0, isNegative: true, }, }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 2, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative: true, }, }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { weeks: 0, days: 0, hours: 337, minutes: 0, seconds: 0, isNegative: true, }, }, }, ]; expect(dedupeAlarmsWithNormalizedTriggers(alarms)).toEqual(expectedAlarms); }); }); describe('sortNotificationsByAscendingTrigger()', () => { it('sorts case 1 correctly', () => { const a = { unit: NOTIFICATION_UNITS.MINUTE, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.AFTER, value: 0, isAllDay: false, }; const b = { unit: NOTIFICATION_UNITS.HOUR, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay: false, }; const c = { unit: NOTIFICATION_UNITS.HOUR, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 1, isAllDay: false, }; const d = { unit: NOTIFICATION_UNITS.MINUTE, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, value: 60, isAllDay: false, }; const input = [a, b, c, d] as NotificationModel[]; const expectedResult = [b, c, d, a] as NotificationModel[]; expect(sortNotificationsByAscendingTrigger(input)).toEqual(expectedResult); }); it('sorts case 2 correctly', () => { const a = { unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.AFTER, at: new Date(2000, 0, 1, 12, 30), value: 1, isAllDay: true, }; const b = { unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, at: new Date(2000, 0, 1, 1, 30), value: 1, isAllDay: true, }; const c = { unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, at: new Date(2000, 0, 1, 9, 30), value: 1, isAllDay: true, }; const d = { unit: NOTIFICATION_UNITS.DAY, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, at: new Date(2000, 0, 1, 9, 30), value: 7, isAllDay: true, }; const e = { unit: NOTIFICATION_UNITS.WEEK, type: NOTIFICATION_TYPE_API.DEVICE, when: NOTIFICATION_WHEN.BEFORE, at: new Date(2000, 0, 1, 9, 30), value: 1, isAllDay: true, }; const input = [a, b, c, d, e] as NotificationModel[]; const expectedResult = [d, e, b, c, a] as NotificationModel[]; expect(sortNotificationsByAscendingTrigger(input)).toEqual(expectedResult); }); });
8,784
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/attendees.spec.js
import { generateAttendeeToken, getAttendeeEmail } from '../../lib/calendar/attendees'; import { parse } from '../../lib/calendar/vcal'; const expectedToken = 'c2d3d0b4eb4ef80633f9cc7755991e79ca033016'; describe('generateAttendeeToken()', () => { it('should produce correct tokens', async () => { const token = await generateAttendeeToken('[email protected]', '[email protected]'); expect(token).toBe(expectedToken); }); }); describe('getAttendeeEmail()', () => { it('should prioritize the attendee value', async () => { const ics = `BEGIN:VEVENT ATTENDEE;[email protected];[email protected];PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT:mailto:[email protected] END:VEVENT`; const { attendee } = parse(ics); const email = await getAttendeeEmail(attendee[0]); expect(email).toBe('[email protected]'); }); it('should prioritize the email value if attendee value is not an email', async () => { const ics = `BEGIN:VEVENT ATTENDEE;[email protected];[email protected];PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT:IAmNotAnEmail END:VEVENT`; const { attendee } = parse(ics); const email = await getAttendeeEmail(attendee[0]); expect(email).toBe('[email protected]'); }); it('should return cn value if attendee and email values are not emails', async () => { const ics = `BEGIN:VEVENT ATTENDEE;[email protected];EMAIL=IAmNotAnEmailEither;PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT:IAmNotAnEmail END:VEVENT`; const { attendee } = parse(ics); const email = await getAttendeeEmail(attendee[0]); expect(email).toBe('[email protected]'); }); it('should fall back to the attendee value if attendee, cn and email values are not emails', async () => { const ics = `BEGIN:VEVENT ATTENDEE;CN=IAmNotAnEmailEither;EMAIL=NoEmailToBeFound;PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT:IAmNotAnEmail END:VEVENT`; const { attendee } = parse(ics); const email = await getAttendeeEmail(attendee[0]); expect(email).toBe('IAmNotAnEmail'); }); });
8,785
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/calendar.spec.ts
import { sortCalendars } from '@proton/shared/lib/calendar/calendar'; import { CALENDAR_TYPE } from '@proton/shared/lib/calendar/constants'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; describe('sortCalendars', () => { const holidaysCalendar = { Type: CALENDAR_TYPE.HOLIDAYS, Priority: 1, Members: [{ Email: '[email protected]', Priority: 1 }], } as VisualCalendar; const subscribedCalendar = { Type: CALENDAR_TYPE.SUBSCRIPTION, Owner: { Email: '[email protected]' }, Priority: 1, Members: [{ Email: '[email protected]', Priority: 1 }], } as VisualCalendar; const sharedCalendar = { Type: CALENDAR_TYPE.PERSONAL, Owner: { Email: '[email protected]' }, Priority: 1, Members: [{ Email: '[email protected]', Priority: 1 }], } as VisualCalendar; const sharedCalendarB = { Type: CALENDAR_TYPE.PERSONAL, Owner: { Email: '[email protected]' }, Priority: 2, Members: [{ Email: '[email protected]', Priority: 2 }], } as VisualCalendar; const ownedCalendar = { Type: CALENDAR_TYPE.PERSONAL, Owner: { Email: '[email protected]' }, Priority: 1, Members: [{ Email: '[email protected]', Priority: 1 }], } as VisualCalendar; const ownedCalendarB = { Type: CALENDAR_TYPE.PERSONAL, Owner: { Email: '[email protected]' }, Priority: 2, Members: [{ Email: '[email protected]', Priority: 2 }], } as VisualCalendar; it('should return calendars sorted by weight', () => { expect(sortCalendars([holidaysCalendar, subscribedCalendar, sharedCalendar, ownedCalendar])).toEqual([ ownedCalendar, subscribedCalendar, sharedCalendar, holidaysCalendar, ]); }); describe('when some calendars have same weight', () => { it('should sort them by priority', () => { expect( sortCalendars([ holidaysCalendar, sharedCalendarB, subscribedCalendar, ownedCalendarB, sharedCalendar, ownedCalendar, ]) ).toEqual([ ownedCalendar, ownedCalendarB, subscribedCalendar, sharedCalendar, sharedCalendarB, holidaysCalendar, ]); }); }); });
8,786
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/calendarLimits.spec.ts
import { generateOwnedPersonalCalendars, generateSharedCalendars, generateSubscribedCalendars, } from '@proton/testing/lib/builders'; import { getHasUserReachedCalendarsLimit, willUserReachCalendarsLimit } from '../../lib/calendar/calendarLimits'; import { MAX_CALENDARS_FREE, MAX_CALENDARS_PAID } from '../../lib/calendar/constants'; describe('getHasUserReachedCalendarLimit()', () => { describe('informs whether the calendar limits for a free user have been reached', () => { [ // owned calendars { calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_FREE - 1), isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: false, }, }, { calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_FREE), isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_FREE + 1), isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, // shared calendars { calendars: generateSharedCalendars(MAX_CALENDARS_FREE - 1), isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: generateSharedCalendars(MAX_CALENDARS_FREE), isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: generateSharedCalendars(MAX_CALENDARS_FREE + 1), isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, // subscribed calendars { calendars: generateSubscribedCalendars(MAX_CALENDARS_FREE - 1), isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: generateSubscribedCalendars(MAX_CALENDARS_FREE), isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: generateSubscribedCalendars(MAX_CALENDARS_FREE + 1), isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, // shared and owned personal { calendars: [...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(MAX_CALENDARS_FREE - 1)], isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateOwnedPersonalCalendars(2), ...generateSharedCalendars(MAX_CALENDARS_FREE - 2)], isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(MAX_CALENDARS_FREE)], isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, // subscribed and owned personal { calendars: [ ...generateOwnedPersonalCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_FREE - 1), ], isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [ ...generateOwnedPersonalCalendars(2), ...generateSubscribedCalendars(MAX_CALENDARS_FREE - 2), ], isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateOwnedPersonalCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_FREE)], isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, // subscribed and shared { calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(1)], isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_FREE - 2)], isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateSharedCalendars(MAX_CALENDARS_FREE - 2), ...generateSubscribedCalendars(1)], isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateSubscribedCalendars(2), ...generateSharedCalendars(MAX_CALENDARS_FREE - 2)], isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_FREE)], isFreeUser: true, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, // all { calendars: [ ...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(1), ...generateSubscribedCalendars(1), ], isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [ ...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(2), ...generateSubscribedCalendars(3), ], isFreeUser: true, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, ].forEach(({ calendars, isFreeUser, result }, i) => { it(`is limit reached for case ${i + 1}`, () => { expect(getHasUserReachedCalendarsLimit(calendars, isFreeUser)).toEqual(result); }); }); }); describe('informs whether the calendar limits for a paid user have been reached', () => { [ // owned calendars { calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_PAID - 1), isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: false, }, }, { calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_PAID), isFreeUser: false, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_PAID + 1), isFreeUser: false, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, // shared calendars { calendars: generateSharedCalendars(MAX_CALENDARS_PAID - 1), isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: generateSharedCalendars(MAX_CALENDARS_PAID), isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: generateSharedCalendars(MAX_CALENDARS_PAID + 1), isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, // subscribed calendars { calendars: generateSubscribedCalendars(MAX_CALENDARS_PAID - 1), isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: generateSubscribedCalendars(MAX_CALENDARS_PAID), isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: generateSubscribedCalendars(MAX_CALENDARS_PAID + 1), isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, // shared and owned personal { calendars: [...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(MAX_CALENDARS_PAID - 1)], isFreeUser: false, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateOwnedPersonalCalendars(2), ...generateSharedCalendars(MAX_CALENDARS_PAID - 2)], isFreeUser: false, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(MAX_CALENDARS_PAID)], isFreeUser: false, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, // subscribed and owned personal { calendars: [ ...generateOwnedPersonalCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID - 1), ], isFreeUser: false, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [ ...generateOwnedPersonalCalendars(2), ...generateSubscribedCalendars(MAX_CALENDARS_PAID - 2), ], isFreeUser: false, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateOwnedPersonalCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID)], isFreeUser: false, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, // subscribed and shared { calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID - 3)], isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: false, }, }, { calendars: [...generateSharedCalendars(MAX_CALENDARS_PAID - 3), ...generateSubscribedCalendars(1)], isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: false, }, }, { calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID - 2)], isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateSharedCalendars(MAX_CALENDARS_PAID - 2), ...generateSubscribedCalendars(1)], isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateSubscribedCalendars(2), ...generateSharedCalendars(MAX_CALENDARS_PAID - 2)], isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID)], isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, // all { calendars: [ ...generateOwnedPersonalCalendars(MAX_CALENDARS_PAID - 5), ...generateSharedCalendars(2), ...generateSubscribedCalendars(2), ], isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: false, }, }, { calendars: [ ...generateOwnedPersonalCalendars(MAX_CALENDARS_PAID - 5), ...generateSharedCalendars(2), ...generateSubscribedCalendars(3), ], isFreeUser: false, result: { isCalendarsLimitReached: true, isOtherCalendarsLimitReached: true, }, }, { calendars: [...generateSharedCalendars(MAX_CALENDARS_PAID - 3), ...generateSubscribedCalendars(2)], isFreeUser: false, result: { isCalendarsLimitReached: false, isOtherCalendarsLimitReached: true, }, }, ].forEach(({ calendars, isFreeUser, result }, i) => { it(`is limit reached for case ${i + 1}`, () => { expect(getHasUserReachedCalendarsLimit(calendars, isFreeUser)).toEqual(result); }); }); }); }); describe('willUserReachCalendarsLimit()', () => { describe('informs whether the calendar limits for a free user will be reached from easy switch', () => { [ // owned calendars { number: 1, calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_FREE - 2), isFreeUser: true, result: false, }, { number: 1, calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_FREE), isFreeUser: true, result: true, }, { number: 1, calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_FREE + 1), isFreeUser: true, result: true, }, { number: 1, calendars: generateSharedCalendars(MAX_CALENDARS_FREE - 1), isFreeUser: true, result: false, }, { number: 1, calendars: generateSharedCalendars(MAX_CALENDARS_FREE), isFreeUser: true, result: true, }, { number: 1, calendars: generateSharedCalendars(MAX_CALENDARS_FREE + 1), isFreeUser: true, result: true, }, // subscribed calendars { number: 1, calendars: generateSubscribedCalendars(MAX_CALENDARS_FREE - 1), isFreeUser: true, result: false, }, { number: 1, calendars: generateSubscribedCalendars(MAX_CALENDARS_FREE), isFreeUser: true, result: true, }, { number: 1, calendars: generateSubscribedCalendars(MAX_CALENDARS_FREE + 1), isFreeUser: true, result: true, }, // shared and owned personal { number: 1, calendars: [...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(MAX_CALENDARS_FREE - 1)], isFreeUser: true, result: true, }, { number: 1, calendars: [...generateOwnedPersonalCalendars(2), ...generateSharedCalendars(MAX_CALENDARS_FREE - 2)], isFreeUser: true, result: true, }, { number: 1, calendars: [...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(MAX_CALENDARS_FREE)], isFreeUser: true, result: true, }, // subscribed and owned personal { number: 1, calendars: [ ...generateOwnedPersonalCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_FREE - 1), ], isFreeUser: true, result: true, }, { number: 1, calendars: [ ...generateOwnedPersonalCalendars(2), ...generateSubscribedCalendars(MAX_CALENDARS_FREE - 2), ], isFreeUser: true, result: true, }, { number: 1, calendars: [...generateOwnedPersonalCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_FREE)], isFreeUser: true, result: true, }, // subscribed and shared { number: 1, calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(1)], isFreeUser: true, result: false, }, { number: 1, calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_FREE - 2)], isFreeUser: true, result: false, }, { number: 1, calendars: [...generateSharedCalendars(MAX_CALENDARS_FREE - 2), ...generateSubscribedCalendars(1)], isFreeUser: true, result: false, }, { number: 1, calendars: [...generateSubscribedCalendars(2), ...generateSharedCalendars(MAX_CALENDARS_FREE - 2)], isFreeUser: true, result: true, }, { number: 1, calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_FREE)], isFreeUser: true, result: true, }, // all { number: 1, calendars: [ ...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(1), ...generateSubscribedCalendars(1), ], isFreeUser: true, result: true, }, { number: 1, calendars: [ ...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(2), ...generateSubscribedCalendars(3), ], isFreeUser: true, result: true, }, ].forEach(({ calendars, number, isFreeUser, result }, i) => { it(`is limit reached for case ${i + 1}`, () => { expect(willUserReachCalendarsLimit(calendars, number, isFreeUser)).toEqual(result); }); }); }); describe('informs whether the calendar limits for a paid user was reach from easy switch', () => { [ // owned calendars { number: 1, calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_PAID - 2), isFreeUser: false, result: false, }, { number: 1, calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_PAID), isFreeUser: false, result: true, }, { number: 1, calendars: generateOwnedPersonalCalendars(MAX_CALENDARS_PAID + 1), isFreeUser: false, result: true, }, // shared calendars { number: 1, calendars: generateSharedCalendars(MAX_CALENDARS_PAID - 1), isFreeUser: false, result: false, }, { number: 1, calendars: generateSharedCalendars(MAX_CALENDARS_PAID), isFreeUser: false, result: true, }, { number: 1, calendars: generateSharedCalendars(MAX_CALENDARS_PAID + 1), isFreeUser: false, result: true, }, // subscribed calendars { number: 1, calendars: generateSubscribedCalendars(MAX_CALENDARS_PAID - 1), isFreeUser: false, result: false, }, { number: 1, calendars: generateSubscribedCalendars(MAX_CALENDARS_PAID), isFreeUser: false, result: true, }, { number: 1, calendars: generateSubscribedCalendars(MAX_CALENDARS_PAID + 1), isFreeUser: false, result: true, }, // shared and owned personal { number: 1, calendars: [...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(MAX_CALENDARS_PAID - 1)], isFreeUser: false, result: true, }, { number: 1, calendars: [...generateOwnedPersonalCalendars(2), ...generateSharedCalendars(MAX_CALENDARS_PAID - 2)], isFreeUser: false, result: true, }, { number: 1, calendars: [...generateOwnedPersonalCalendars(1), ...generateSharedCalendars(MAX_CALENDARS_PAID)], isFreeUser: false, result: true, }, // subscribed and owned personal { calendars: [ ...generateOwnedPersonalCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID - 1), ], number: 1, isFreeUser: false, result: true, }, { calendars: [ ...generateOwnedPersonalCalendars(2), ...generateSubscribedCalendars(MAX_CALENDARS_PAID - 2), ], number: 1, isFreeUser: false, result: true, }, { number: 1, calendars: [...generateOwnedPersonalCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID)], isFreeUser: false, result: true, }, // subscribed and shared { number: 1, calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID - 3)], isFreeUser: false, result: false, }, { number: 1, calendars: [...generateSharedCalendars(MAX_CALENDARS_PAID - 3), ...generateSubscribedCalendars(1)], isFreeUser: false, result: false, }, { number: 1, calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID - 2)], isFreeUser: false, result: false, }, { number: 1, calendars: [...generateSharedCalendars(MAX_CALENDARS_PAID - 2), ...generateSubscribedCalendars(1)], isFreeUser: false, result: false, }, { number: 1, calendars: [...generateSubscribedCalendars(2), ...generateSharedCalendars(MAX_CALENDARS_PAID - 2)], isFreeUser: false, result: true, }, { number: 1, calendars: [...generateSharedCalendars(1), ...generateSubscribedCalendars(MAX_CALENDARS_PAID)], isFreeUser: false, result: true, }, // all { calendars: [ ...generateOwnedPersonalCalendars(MAX_CALENDARS_PAID - 6), ...generateSharedCalendars(2), ...generateSubscribedCalendars(2), ], number: 1, isFreeUser: false, result: false, }, { calendars: [ ...generateOwnedPersonalCalendars(MAX_CALENDARS_PAID - 5), ...generateSharedCalendars(2), ...generateSubscribedCalendars(3), ], number: 1, isFreeUser: false, result: true, }, { number: 1, calendars: [...generateSharedCalendars(MAX_CALENDARS_PAID - 3), ...generateSubscribedCalendars(2)], isFreeUser: false, result: false, }, ].forEach(({ calendars, number, isFreeUser, result }, i) => { it(`is limit reached for case ${i + 1}`, () => { expect(willUserReachCalendarsLimit(calendars, number, isFreeUser)).toEqual(result); }); }); }); });
8,787
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/decrypt.spec.ts
import { CryptoProxy, PublicKeyReference, SessionKey, VERIFICATION_STATUS } from '@proton/crypto'; import { stringToUtf8Array, utf8ArrayToString } from '@proton/crypto/lib/utils'; import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding'; import { EVENT_VERIFICATION_STATUS } from '../../lib/calendar/constants'; import { decryptCard, getAggregatedEventVerificationStatus, getNeedsLegacyVerification, verifySignedCard, } from '../../lib/calendar/crypto/decrypt'; const { SIGNED_AND_VALID, SIGNED_AND_INVALID, NOT_SIGNED } = VERIFICATION_STATUS; const { SUCCESSFUL, NOT_VERIFIED, FAILED } = EVENT_VERIFICATION_STATUS; describe('reduceBooleaArray()', () => { it('should return undefined for the empty array', () => { expect(getAggregatedEventVerificationStatus([])).toEqual(NOT_VERIFIED); }); it('should return SUCCESSFUL when all array entries are SUCCESSFUL', () => { expect(getAggregatedEventVerificationStatus([SUCCESSFUL, SUCCESSFUL, SUCCESSFUL])).toEqual(SUCCESSFUL); }); it('should return FAILED if some array entry is FAILED', () => { expect(getAggregatedEventVerificationStatus([SUCCESSFUL, NOT_VERIFIED, FAILED])).toEqual(FAILED); expect(getAggregatedEventVerificationStatus([FAILED, SUCCESSFUL, SUCCESSFUL])).toEqual(FAILED); expect(getAggregatedEventVerificationStatus([undefined, FAILED, SUCCESSFUL])).toEqual(FAILED); }); it('should return undefined for any other case', () => { expect(getAggregatedEventVerificationStatus([SUCCESSFUL, undefined, SUCCESSFUL])).toEqual(NOT_VERIFIED); expect(getAggregatedEventVerificationStatus([NOT_VERIFIED, SUCCESSFUL, SUCCESSFUL])).toEqual(NOT_VERIFIED); expect(getAggregatedEventVerificationStatus([SUCCESSFUL, undefined, NOT_VERIFIED])).toEqual(NOT_VERIFIED); }); }); describe('getNeedsLegacyVerification()', () => { it('should return false if verification as binary succeeded', () => { expect(getNeedsLegacyVerification(SIGNED_AND_VALID, 'test')).toEqual(false); }); it('should return false if verification as binary returned that the card is not signed', () => { expect(getNeedsLegacyVerification(NOT_SIGNED, 'test')).toEqual(false); }); it('should return false if the card does not contain neither trailing spaces nor "\n" end of lines', () => { const card = `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nDTSTAMP:20230310T154953Z\r\nSUMMARY:test\r\nDESCRIPTION:no line jumps\r\nEND:VEVENT\r\nEND:VCALENDAR`; expect(getNeedsLegacyVerification(SIGNED_AND_INVALID, card)).toEqual(false); }); it('should return false if the card does not contain neither trailing spaces nor "\n" end of lines, but has escaped "\n" characters', () => { const card = `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nDTSTAMP:20230310T154953Z\r\nSUMMARY:test\r\nDESCRIPTION:some \\nescaped \\nline\\n jumps\r\nEND:VEVENT\r\nEND:VCALENDAR`; expect(getNeedsLegacyVerification(SIGNED_AND_INVALID, card)).toEqual(false); }); it('should return true if the card has trailing spaces', () => { const card = `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nDTSTAMP:20230310T154953Z\r\nSUMMARY:test\r\nDESCRIPTION:A long description with an RFC-compliant \r\n line jump\r\nEND:VEVENT\r\nEND:VCALENDAR`; expect(getNeedsLegacyVerification(SIGNED_AND_INVALID, card)).toEqual(true); }); it('should return true if the card uses "\n" as end of line character', () => { const card = `BEGIN:VCALENDAR\nVERSION:2.0\nBEGIN:VEVENT\nUID:[email protected]\nDTSTAMP:20230310T154953Z\nSUMMARY:test\nDESCRIPTION:no line jumps\nEND:VEVENT\nEND:VCALENDAR`; expect(getNeedsLegacyVerification(SIGNED_AND_INVALID, card)).toEqual(true); }); it('should return true if the card mixes "\r\n" and "\n" as end of line characters', () => { const card = `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\nUID:[email protected]\r\nDTSTAMP:20230310T154953Z\nSUMMARY:test\nDESCRIPTION:no line jumps\nEND:VEVENT\nEND:VCALENDAR`; expect(getNeedsLegacyVerification(SIGNED_AND_INVALID, card)).toEqual(true); }); it('should return true if the card has unescaped "\n" characters', () => { const card = `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nDTSTAMP:20230310T154953Z\r\nSUMMARY:test\r\nDESCRIPTION:some \nunescaped \nline jumps\r\nEND:VEVENT\r\nEND:VCALENDAR`; expect(getNeedsLegacyVerification(SIGNED_AND_INVALID, card)).toEqual(true); }); }); describe('signature verification', () => { // async not supported in describe let verifyingKey: PublicKeyReference; beforeAll(async () => { verifyingKey = await CryptoProxy.importPublicKey({ armoredKey: `-----BEGIN PGP PUBLIC KEY BLOCK----- xsFNBGQUNeUBEADg4jzbHQuuSN3DBIpr9+BchSpW7lKuyC1A5SWoVfoXp8Kh ExDpJW0uIxYBkFxf1M+HrwFQ60Z5HCh2tn9j/fVT7N+cYoJ9b4Ux6vb4XPgn fczhGZBQu+RuGnP1pk+BThdQmL4qmbz4Lhs6TmsrC+j8nZmETmlpjnzenZnr HDPt+7dXDAwSLgYtoF/ai/4BGRKJSNZqQGCJHAczyDcruyTGboQwYTgY6DCQ uDDpfvQyipfi2YrPSXfMMiq58/oN5xJVF8KBDjEGRsGAnjjLzD9ESS23lEFc yBFq8ZnQ1zEAvsi2pM2t4d1WN4j+XHl15OtF320IZwhFpWbWwF5BensF9C7q QGv53S/yxtynhxFe5LLIX6xCoPAx9ztEpQ7vCNWAxfuEuD2h6YH7uto4SEdG yFFjqhTGfoMGf8e6vHDqG0lhQ64ihrkChHuoFoNOKctd+AzAf+jwBYFcLfaR DTzXGhLSU2htY1y0eMCCX3FKxs2aED4mKP9/33wboFaJsXDfzBwuirUaOeGu ypbe59SWSweSd3xMk4hs6g0rujgK43zqhHwbfANOYKxMO/DaNAQ1CejdTQFF WjKB5c3i4do53bDPvSuInKg47hJebusgtQ35tAMQ8sW5u/w6MdKYnToO5drI nh1Rh+f1hg901LgGju5cjWQK+AGrdNFh/sz15wARAQABzSttYXJpbi50ZXN0 QHByb3Rvbi5tZSA8bWFyaW4udGVzdEBwcm90b24ubWU+wsGKBBABCAA+BYJk FDXlBAsJBwgJkDdgL12b05omAxUICgQWAAIBAhkBApsDAh4BFiEEnvjO48DO r/B5ikD/N2AvXZvTmiYAAB2eEACZbAVMTop1HWLmO/2Yxfn1yBFeUQ9mnni6 GrxTXLwuOA1pZTApaI25pncSwlx3fGJk8/gaIr9flITWSZlmfOF2LWNdSMDc UMa86XTJtt6OO8jX+Kc8DJgDHAzyC0CzaY/hMI0ptg5kOmOF8OuCTTZYDSbP bbw+t59krKHM4Tv7M2zeaejt2nlgaUqxmxy9my3inf5dp0nDRPr/G7pUXqYL WMrmwmrVCaFf9YVjUDxanu4OxjdSbpdaY0XB8zmWOqItQME25wnQRn1r4T3e d4uo8AkiHR/edp3wAjKPP0dPacKnoWhYk5ExoETacUWRbdgEQscEeb5nOYTm 3dXWP/ZrlW1+amJ/BV6pgD7llVUEQbk9k3MS3kL8hQ4C2XhXsXSTrkHI8K52 2ITIjuNcRQcCza6XModHxY4Z0rSajPKU8Rii1caFm+q9w+IpvbcG6Ews5WCC /L+3ypXlKo8R8IJSaHO/O4pz48+UL3shNouXnzULZPZTjCYaartRTioU9WZ8 lVcKWSRuI4fVGItRaQg7VB+BxcDihhEAl/XrYVS6SV+vQG65M7qyj5vqzkBj CLoeQnCCHe0mgttrVGqcmIfDXZ+S0NSPM23jcOTMof1/FVKQPs9ARO1QDx2s 00o5F1s5FX16AQaFPzwTMJQndH/9wTFbXaCDIRefrWM3kCUMgc7BTQRkFDXl ARAAlFWpetM2HgUA2JjJFtzNuaCII4RxULgG7qx5DLB2mNlLNS3EmSzAkDpQ kOTzebMjEX2Cqs/d3L0CNH/xdGElirt6q4YH+QNcCbzLpTGSlEfaE1oljEp4 MlfB312cFahDl7Z4ScDaunPFRtbk0FBe0gpsRZE6z1ax2V5vEP66q0nJlYuB iOIkPwWKjp1y/l2afSxmUM7gtCZdHdQkwMA9KNK5NYlkPyZWMCNgcGARyQWW F/kOhBFHUZBlotrk83JLOGNy++DNH490LdBhwwFbbzpp6BiprphcdGbddrCJ uNVaX+Kr4R5+Rysf5ilGOBW7+A+Tn3b2rJnE4iyeO6zCJUwTn087o2hYC9bw +AhMx2Q9RozNQn3o0aECD+AehiZpK20PXkaK2tJe9j48HLp9dgfrpCY8uKrH PrijUWU7LFdx6Y1b7MbgBcwveybeM3MdofKyfFXiXdTf3tU/UCYBBSw2ez2y YjiocMovVxfl1RLb9BoTlcaCYFv2gImjKtb2/aak8fVI7F41pdVZaUY1ptiW V+bJnRlyGehvRxWIYkAhWeuHeIzQH03fRlFlEGam1k4CFdcvR2WR3fLtt7CE ugJYMnEpuXSk3XRZ8DofW4hMiKz195TjvtA9JCiYtA+Avxxkz/oBrDcqBabM NLa4fjEj4fvFqFMjvBekSG86PMsAEQEAAcLBdgQYAQgAKgWCZBQ15QmQN2Av XZvTmiYCmwwWIQSe+M7jwM6v8HmKQP83YC9dm9OaJgAAZjUQANLVg/Oy3rjE A+jAZQPHgB6Vuz+1E6gQb05PrT0TWsy+mxWX0Fgl37y4F5aHkOjmU3Wjwv0T bJuPnKHDDBdeiwDkmGizu/dF1oU22kvQxsLSya/JQ2MKuFukS2q5C4ynJxBK 3zWvIi9+u7zF+qrnqRRPQkt8lzrVMn8fwBdpLAY6BkCjq08Nb7rhOPgR1IHy oRtbrN0/oow4xXPopNmURuDTPCDNzQffqVdlk+Y3IYWCacyLqKHr+N69Zmd8 rmN3TuBsdhAclak4UAdZpvatopn6xmmjRP4ASrLcibD1uEfQtu8K23c6w5Mh /gu9BgSWi2XTIKl8RAjDT4RIDedBwDEEW28/VSNctq3/cTnzF8agirWGbi+J QCMu5XiXxlpaVTJqYP8i9rBiInEWVi6awniBGlc1KvXkWnHS9anq3YpVEn5z 6GEqOvKbQkocRUC+PWPh8cn/59DeCU0z+ZRPh1JwbcczlNOh/Q4bEPpNX1CC I82ZxY1uW1RzVPaivVmcmLTdJwQisk7Ly8UIuWPFZgpPqukkX4EkRr80pCyD 5ftJ3/q73HLgwUBlouFJYtRpedpED+GnrLmwwMocE/abtfFQOAEeOF+36PQH rVrK/CBryY6A1Ofspib3HcxfpFrGB4EQ9uLGKGfHtVC2ffrb+vKBiFXjb0Hx 4inhR0I+BumP =QACS -----END PGP PUBLIC KEY BLOCK-----`, }); }); it('should verify RFC-compliant events with trailing spaces signed in binary', async () => { const signedCard = 'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Proton AG//web-calendar 5.0.9.0//EN\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nDTSTAMP:20230317T094504Z\r\nDTSTART;TZID=Europe/Zurich:20230316T110000\r\nDTEND;TZID=Europe/Zurich:20230316T163000\r\nSEQUENCE:1\r\nEND:VEVENT\r\nEND:VCALENDAR'; const signatureSignedCard = `-----BEGIN PGP SIGNATURE----- wsFzBAABCAAnBYJkFDagCZA3YC9dm9OaJhYhBJ74zuPAzq/weYpA/zdgL12b 05omAAAv3RAAylxnTDoGhwPVWIeQ8YawgriM7PTzti7VOSiZoa5qZA2AUNdN U5yzwMPKjS6lqPqMjt3K3qHDKwLP3x+zXUJltmLhf5O8AP6HX3z21iyrCz0d fs4PwoWWhhL42/JGz7pSkXd7UCBf5CdtEnEJndjVdmTNtqATLdSMA2acHSvp F4j6qwDz/IUccVMBPdCNr7aUdhvrgmRLEeux670vuYXoCOYp7FP4+nqFiZyj uNOVKyr7pLNoExr/Mr7oeO+vWtQQmCqFv0l0eB15iJvoqxADaubhxlyH66Mg IDKvJ0dgDYkXpp792FAFS5KQmYu3fWvaKI9JDcP7GlxhK8PctxArEHb0Yw4Z tznIdv4fpBMij7tKZUPaXa44E1eaLAh0cLmE43pEe72su3ApIXOFNwCoG2wY 2oFlqzveqSAxUO7KFjHHKfQsLP87W2LN9SJIirS79oczc44I7JLCTiZK0QBE L5mlVWhx64WrO3IuG3zLo1zHVJr0b8bbomXc7QpzBZeSWu6gk8TzXbuq+cXM WVzSaiIYkiAIJ+3Il0eVXRDByHSlbiARUXwTbYTInGJTZlojiYGRKLg3RZVh rYPisW+K5qDtxDwtSzh7enrioaYjmNkxAl9ITrW3KIWpj6T9T8Y6nF1XZjoW Os/jRyUaMIniPF2OLQ3H8twvnNLYQiikaPY= =3DyY -----END PGP SIGNATURE-----`; const { verificationStatus: verificationStatusSignedCard } = await verifySignedCard( signedCard, signatureSignedCard, verifyingKey ); expect(verificationStatusSignedCard).toEqual(EVENT_VERIFICATION_STATUS.SUCCESSFUL); const encryptedAndSignedCard = '0sCOAYco/2YnDOqysm4O2mcSAfTogGJw5YjQEz+pcS7tWUjXiNyVWJfrClgdTdW13kwb/CKrMmj0W2gQp4Sg6AwCTrxpgL1MFPU5yNv1Dy/oRX9wLP62AMCvlLfEvbncEVEiArt13RMtge9TH87t6FAYunCGS/tY8rBZN1rm4jvgn9WPeOzuVDAAtTvo0QG3FO2gtHr5MIdXekc1JzNwVY4YqxYxpHgAjTVa+L2EKSS66a5UcE//DvSAGsGOhJs0oncK1fWKxBbT/a3tbolh6Ay7LwXjJBLU+koJfDUOX1lwOuS+93ES3EiD8uYstFIjutFgOEXO91ZnsxEeswQGZWzhoC0A72mFrC+CSw41Z4hZ5wfEwZEG0SfHVnlVoSB0veKkDBPjFWFLKloX+H4YwM0ueX+hgCCKMihlvsb+wC/gLH00jakaeWkZM4cw9wl1Vw=='; const sessionKey: SessionKey = { data: base64StringToUint8Array('Rxpha2U2xhoE1iP7W9l/EmfTTYEv8ZLHKDYuzQU86nQ='), algorithm: 'aes256', }; const signatureEncryptedAndSignedCard = `-----BEGIN PGP SIGNATURE----- wsFzBAABCAAnBYJkFDagCZA3YC9dm9OaJhYhBJ74zuPAzq/weYpA/zdgL12b 05omAAA2qA/+KOmoAYaPvQnWvKarS9kso1CUQKtz2L43fGE4kgTXjvX6/gGV 5S8QU4R6/sWwqEFSncHVnglmV8qovIinNzoIcNDSr31zCxg8+ZsUUROSPeW9 k/LZR/VP4ksYioGuH/7chZyATmflq4vPQtvzmAXxX+P0UnAHBbNZ1Dba6xq+ apeocgcp8SlVVU4PRvgXY1T8YlyoplGEvsfp3dlDNi4QRd3reisZJbaMAYpr ZhjNdwT5Mv22wckshkbu+BvKscyW1rNjfkJaBy5f3Wr/+hsHV8+0tPZPVRz2 UE7xVImDyWMLaof43qK5Q4IdPm1xG535ntJ5mbJPCmzObu3izbq71rv9LLH4 w8f18XN9H6MxKVvY9+uinKIpSVpiKVhKEbVcCrtTAl+B/5qpmz2dcikZ0Ump cB/vS7v2RgaSaxuu1SK+Sk4JZYcZ/9Xbjaegf26d+cxpoJLxrrQNuozWA1eb LG9QkIsX5b0VepUBvrln1AA4bXUM0nAoUzrhz4vH5yGM55sbW9rnf0GxOihx 49NAfi0SOLmuzn8HAiLwbfpV4R9CBKu6DMNb6pBloyaBBKLMNDjttP59MEdt rHe09o7AZP4WmjAhwFP5piIU91IRSI8ZLKaogcb1UmEWvdstnyJKM7R3zFkX TIurHadAqGSqqTU7bb+jQCWD1RLDbwhIgkg= =FPS1 -----END PGP SIGNATURE-----`; const { data, verificationStatus: verificationStatusEncryptedAndSignedCard } = await decryptCard( base64StringToUint8Array(encryptedAndSignedCard), signatureEncryptedAndSignedCard, verifyingKey, sessionKey ); expect(data).toEqual( 'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Proton AG//web-calendar 5.0.9.0//EN\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nDTSTAMP:20230317T094504Z\r\nSUMMARY:Australian Brandenburg Orchestra concert: Ottoman Baroque with the \r\n Whirling Dervishes\r\nEND:VEVENT\r\nEND:VCALENDAR' ); expect(verificationStatusEncryptedAndSignedCard).toEqual(EVENT_VERIFICATION_STATUS.SUCCESSFUL); }); it('should verify non-RFC-compliant events with trailing spaces signed as text (legacy Web, tweaked to use "\n" as EOL in signed cards; without tweak it would use "\r\n")', async () => { const signedCard = `BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Proton AG//web-calendar 5.0.9.0//EN BEGIN:VEVENT UID:[email protected] DTSTAMP:20230317T124114Z DTSTART;TZID=Europe/Zurich:20230315T110000 DTEND;TZID=Europe/Zurich:20230315T163000 SEQUENCE:1 END:VEVENT END:VCALENDAR`; const signatureSignedCard = `-----BEGIN PGP SIGNATURE----- wsFzBAEBCAAnBYJkFGJSCZA3YC9dm9OaJhYhBJ74zuPAzq/weYpA/zdgL12b 05omAACwaQ//eQ75ZFW1QOFZDpR4wB0GAMgCmsINrgGo47qZ89l/DnYitLc5 eg6hSttPpdED146m0E8IR7l5fupkcLqVRFUitn7HBipfyFhuzSbsisDPPppV /4OIojOXtLdg91w6juhxuornhwV0+3FjMvukd9yVaa6dzOcBnj6KwKqQCk0I K9OLutqUmLfNKjoqxzo4zN2LA+EVi0RKui+QaSkyUSLoYHiZMIiOq403BrVu hoiznENXGufBWwbZWVzLkHEIq4K4U22lxbnoue2dmnlmw8pKWSiqKE+QU+vh 0MRq3zqI1fV8MMYGNHpKC+GcDBgMBQ/7uhTTSKn3QjeYMjo6ixVOdp7vNKDY +g2kyf1mteVfwbGFCoawU3sZ885EIqLbuY6sY3cAjb7Dx0RBoCU/O93WAwk3 9keuZUAhEnhu7QwqYyp3UyILXNf4oF5UTwQ8Ld30RYXnwZGDscSB7DoDArFb tSdwsKL1X3UXMOBV9gB5k0L/iulr2itzL0OkBKiURXLjwjqjLxFj4HslJFco wrZ9v8FZrPQ5TkZjXoZ5tsq3PXL+VFul4QzMR7TrRGQIVcn9Ty0LlakI+bdL hI7nxX+JKdhaPp/aXnV2MGsRBCsGV8M1vrzO5r13Q+Hxsl5rd693REWGEB8Y Y3X/iRfq/cJoDMJYtiKGdUFF6yH96xE5vSs= =t9s9 -----END PGP SIGNATURE-----`; const { verificationStatus: verificationStatusSignedCard } = await verifySignedCard( signedCard, signatureSignedCard, verifyingKey ); expect(verificationStatusSignedCard).toEqual(EVENT_VERIFICATION_STATUS.SUCCESSFUL); /** * This legacy signature is verified in binary (despite the "\n" EOLs) because legacy Web would produce text signatures, * and verifyMessage is going to check the signature type and normalize the EOLs in the text before verifying. * So no fallback verification is needed in this case. */ const { verified: verifiedBinarySigned } = await CryptoProxy.verifyMessage({ binaryData: stringToUtf8Array(signedCard), verificationKeys: verifyingKey, armoredSignature: signatureSignedCard, }); expect(verifiedBinarySigned).toEqual(VERIFICATION_STATUS.SIGNED_AND_VALID); const encryptedAndSignedCard = '0sC0AVhc/TD0qVsq3nUgOiPnU4BGfbSI7U2RzjnxjUhokCEuq+Sn+XQKdR+F71keN6zUvgImIImJK8lngOiTqCW810VmLPwokvH3f7CiPsYT3v99HEgoskhv38nsxDmI1hQFAzEqanGSWkRWotwsW8gPdgK7v5Ps8Eb9qmhjnGoT4WVVahexiA5S3wHvmZczENJA3Mas419P+ff6XVt7Cx4lr24FSphjl/7U90eAePFbTEkjMKtMn2km4a2CP3nI1seaL9pWOPCca4Inn221nxFAugmvILxSn01ZQsM5OX38ZcAyeAsIi+UGDxHKqg9BBMtsLL1PVq79ayf9kQcXuZACrlVHcQ4rkz++1pRx8UbNBdN+B4OJPVNM2hRDSSo/8nkh8ztwcop4BEz+bmeupk6/YJnUbo+cO9Df4fi1DytjSQIaC7bQPuDBSCRtKYCfxlHyrhDoPS+T8dZmYfOUru1X5WCSMScXkreSTviF8VkBePJqRmrE'; const sessionKey: SessionKey = { data: base64StringToUint8Array('5e08Opb7TvQL5adOSULm0OKlt/bOeCDQSxlw1fWnnxc='), algorithm: 'aes256', }; const signatureEncryptedAndSignedCard = `-----BEGIN PGP SIGNATURE----- wsFzBAABCAAnBYJkFGJSCZA3YC9dm9OaJhYhBJ74zuPAzq/weYpA/zdgL12b 05omAAA7AQ/7BMju7e4BCePMeCxz2Sa3C2QMUjA686E3u3NAlO7uLdcQXGGX j4028qwQthcjE7Hm3gInA7rN3nbjxiXa55GLQI1yv4lyAWJQ3HzNSvz2Q/Vw xLcT1KlZBcWg0HtXIz1PdS7cNMGk7RTG5DVLi5b5bfVmN4ES5nzBtAfTCrN4 IIdQZ0bCVLy6tBzdGkgwRiLs8IZ+iAYckCEYZdJUssfiNTpxvg3u0qIA4LMT LrSBkRQTlx5XCcg9QK9aFDw2Conirda1+FqQyD9ftfU9zAqP6a3BVrGSkvpy 31lUlm7AEA4fw4sj8D00EOxVAQoINMsI7zpdmU9+LRYsmPJmaJk4x+4K1B2e Y1/Wg/9isYkpnG4uHB3oZ1LWrPiqkPjAB7d7IARmgixbPyMGefrG2haL+LLF 5+TskldrGRFDdhvd8FZ2joddV0vkYUN2KRud/76EfGGbEacAczTKGw/hW+Na adCXh6FC9A89sB+/5TJ6EvnsyZWDDArJiyidSc3DEfOWzxBaRxaCizeHgxPR hLeAuC5ZJObnSLiYryactwNnR2iOS2Dk/Ej2B2swdC8/vD/NTEdSWVUxWWOn +EiTdkNpeBbA23C0cHfBOA5kr4W4whVZYa+mfcV+dVc61Ea0fpXfmzWFut2E uS98JFYRm7dxVWDkdLoOtCk6IC5vuDvapZ4= =/dKU -----END PGP SIGNATURE-----`; const { data, verificationStatus: verificationStatusEncryptedAndSignedCard } = await decryptCard( base64StringToUint8Array(encryptedAndSignedCard), signatureEncryptedAndSignedCard, verifyingKey, sessionKey ); expect(data).toEqual( 'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Proton AG//web-calendar 5.0.9.0//EN\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nDTSTAMP:20230317T124114Z\r\nDESCRIPTION:Line\\njumps\\n\\nAnd a \\\\n\r\nSUMMARY:Australian Brandenburg Orchestra concert: Ottoman Baroque with the \r\n Whirling Dervishes\r\nEND:VEVENT\r\nEND:VCALENDAR' ); expect(verificationStatusEncryptedAndSignedCard).toEqual(EVENT_VERIFICATION_STATUS.SUCCESSFUL); // this legacy signature is verified in binary as expected since legacy Web signed encrypted cards in binary already. No need of fallback const { verified: verifiedBinaryEncrypted } = await CryptoProxy.decryptMessage({ binaryMessage: base64StringToUint8Array(encryptedAndSignedCard), verificationKeys: verifyingKey, armoredSignature: signatureEncryptedAndSignedCard, sessionKeys: sessionKey, }); expect(verifiedBinaryEncrypted).toEqual(VERIFICATION_STATUS.SIGNED_AND_VALID); }); it('should verify RFC-compliant events with trailing spaces signed as text (legacy Android)', async () => { const signedCard = 'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Proton AG//AndroidCalendar 2.7.1//EN\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nDTSTAMP:20230317T104052Z\r\nDTSTART;TZID=Europe/Zurich:20230317T120000\r\nDTEND;TZID=Europe/Zurich:20230317T123000\r\nSEQUENCE:0\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n'; const signatureSignedCard = `-----BEGIN PGP SIGNATURE----- Comment: https://gopenpgp.org Version: GopenPGP 2.5.0 wsFzBAEBCgAnBQJkFEOkCZA3YC9dm9OaJhYhBJ74zuPAzq/weYpA/zdgL12b05om AADq+w/+PrFHkLzgOUTdNvkDVEMT2N4Y3xxG//zuFiYNf8Zs7WPpR+4e+z9TFPZW LD+zajPx5/CKwzozFZ02LGw3OeQUM9cnhxPdG7zA8JuqpxGnRt0ubzlLtnrmduj6 4yZvYZJa9zMattk8XtP8+TqRHyp4yheK+Ju+2jYNjtCQhPFydcMF1Ba5WBdYQJVl sKOl4WkAmEjJJdD86vD2STqamjbe4E6TcNmusBjYJOrU3zQES5AxqNRLFjcmDA2o 9JcGomFIg+KBidWqYXy6TefgKllmWsfduDIyZxxmn8o22KA3oY0yVaFPybBwwsxI z4SIZBwL4/vSwdhBW2nWHpXCcRt+HB1ncANpajiMQQCg8kWmRgFWrtz1ONordXih T4y9DTbDiU2lQhXKOyuoIqhAyIe67xQNCz3KtSP0TAkjm3+ApNGY+PCnJZzrgmAX gvrXnRdRPi7LBUEH22rSXMqMPuOX8Af4qshrpcOYQCLos4W6yXZkp5/tBXdf/csW 7kUBaxOxkB1IZwHF1wkerQa/OrSAjk75AwlFwkL3MVsGUXTKXYvJ5jw33KvMdzmr koyFAGsS/RHa4+ZiqbCM+AikATf9iT7akYzTefQUGU3U5FhLj7FGLmQUhe8lPCNC kUoztkcHA+E9tez5X7KdhUMMHPr7gnAlf10XGVGT/s8DaJ96lg0= =SEFg -----END PGP SIGNATURE-----`; const { verificationStatus: verificationStatusSignedCard } = await verifySignedCard( signedCard, signatureSignedCard, verifyingKey ); expect(verificationStatusSignedCard).toEqual(EVENT_VERIFICATION_STATUS.SUCCESSFUL); // this legacy signature is verified in binary without need of fallback const { verified: verifiedBinarySigned } = await CryptoProxy.verifyMessage({ binaryData: stringToUtf8Array(signedCard), verificationKeys: verifyingKey, armoredSignature: signatureSignedCard, }); expect(verifiedBinarySigned).toEqual(VERIFICATION_STATUS.SIGNED_AND_VALID); expect(getNeedsLegacyVerification(verifiedBinarySigned, signatureSignedCard)).toEqual(false); const encryptedAndSignedCard = '0sC2AePHfQWired3Wj7qHXXSU/x4K1Det1Wtd57YiGK+H8Ed6t5NSPvjx9AOGHLRUuv93KPj1e2G/aZyPGzEEmT6HkXxR9q9PxBvwhWwu0mev5buiMpLqWPVC5ryNrnyLjqJjB+NwcUAs43uZsuYvR4xGNEVcu9UvWUKOoiYt5CWnOFnXnOZx//5/ZG+Xd8e2zwJOriJfu5eDkosIwFvr9hmI3mQahNGb64yqd7KQsIHJv29RhG5v7DluOK3rQMxdKZ3RxGpbbjIOjMLdB7Vuiku7snwmCHHVpaXKmNZOMv6VFdsHIKwtBf712++7o6tMzyGgBGc2rNgdGPCXEzSc892ZDxcrhX3JjcZhUOMGsCs7svr7RtETOXZXQFUnFWD58CpiGct5c0LN/5vcNYrMULqjGShtDHYTK3u4mDU6BFMrtT7gTHqYTEW7gpwNeM+d7GDMt2kHfTLgZQxOpRRsdgq3+2Bh4yGd8OskmwP81Y6p9twWDOZkrc='; const sessionKey: SessionKey = { data: base64StringToUint8Array('v0tbmWKoALXNhkphFy7lje3amf9WP8vSf8aUsSF9Wvs='), algorithm: 'aes256', }; const signatureEncryptedAndSignedCard = `-----BEGIN PGP SIGNATURE----- Version: GopenPGP 2.5.0 Comment: https://gopenpgp.org wsFzBAEBCgAnBQJkFEpPCZA3YC9dm9OaJhYhBJ74zuPAzq/weYpA/zdgL12b05om AADVsxAA4CtMT70V3z84yHhufsPh3HN4jonUk7riNtvwNdOlz6zmDlMoj6bf6vsz GdVUHHXY/XnDD7zEI5W+SeTIkcA8/xl1YhIuZnr75SvZQ5f9TINUZj136NnfhCnc E1/OcNgtBHvIaPYmFXGV7xKm3NZP1mS34DrOvDPetYoBo8haBTo2CXoMBAEnJRTH mhcx2d3sXAY9ChWnZYdaG4bCh1riMM3aiu0WLFF2A1wegWz2webtsLsPSkt5SkhU egm4e2j7mwmr3ZuinZcPOaca7v0Rw9UOfiV7e6Xsz0xL8tD9DdE6nv3RpARt74qT UNpMwdG8bZCQKPtFT2kbzYWWph2wo+yKA5W4+HvJ3OeOJvZl0r8E+MGDf6iuvuzy wyLZwltsP90OUHLCXP6IhgiVkOW6yRCDYyjLsp0DXYf+t/P465pGr/o6fgiJyf6O 3kFSh1RBptgsQOqX+XiP6v6H1NTr/z0W1C09IgHCvgVtPKxYTTcUCASkz0/9zrpc TeEGwhP3Oc52onC9vYGiITjL7nY4OhEH7vO2gJudb9U6TuNlRgCfrFlATTAdE6GM iPVLMhEAafXEHsXOYoiX3YbgHrPBBHBydcyRHQs8rv8RTCWHmvF7m2PNSVAEJrr6 p6UwLlBEdbtqT8YixITK1QU+Owmk/GmWADOyVzN/hXKg0zJVTc0= =Jg7J -----END PGP SIGNATURE-----`; const { data, verificationStatus: verificationStatusEncryptedAndSignedCard } = await decryptCard( base64StringToUint8Array(encryptedAndSignedCard), signatureEncryptedAndSignedCard, verifyingKey, sessionKey ); expect(data).toEqual( 'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Proton AG//AndroidCalendar 2.7.1//EN\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nDTSTAMP:20230317T104052Z\r\nDESCRIPTION:Line\\nJump\\n\\nAnd a \\\\n\r\nSUMMARY:Australian Brandenburg Orchestra concert: Ottoman Baroque with the \r\n Whirling Dervishes\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n' ); expect(verificationStatusEncryptedAndSignedCard).toEqual(EVENT_VERIFICATION_STATUS.SUCCESSFUL); // this legacy signature is NOT verified in binary. It needs the fallback const { data: decryptedData, verified: verifiedBinaryEncrypted } = await CryptoProxy.decryptMessage({ binaryMessage: base64StringToUint8Array(encryptedAndSignedCard), format: 'binary', verificationKeys: verifyingKey, armoredSignature: signatureEncryptedAndSignedCard, sessionKeys: sessionKey, }); expect(verifiedBinaryEncrypted).toEqual(VERIFICATION_STATUS.SIGNED_AND_INVALID); expect(getNeedsLegacyVerification(verifiedBinaryEncrypted, utf8ArrayToString(decryptedData))).toEqual(true); }); });
8,788
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/deserialize.spec.ts
import { ICAL_ATTENDEE_STATUS } from '@proton/shared/lib/calendar/constants'; import { getSelfAddressData } from '@proton/shared/lib/calendar/deserialize'; import { buildVcalOrganizer } from '@proton/shared/lib/calendar/vcalConverter'; import { ADDRESS_RECEIVE, ADDRESS_SEND, ADDRESS_STATUS, ADDRESS_TYPE } from '@proton/shared/lib/constants'; import { buildMailTo } from '@proton/shared/lib/helpers/email'; import { Address } from '@proton/shared/lib/interfaces'; const buildVcalAttendee = ({ email, cn, partstat, }: { email: string; cn?: string; partstat?: ICAL_ATTENDEE_STATUS; }) => { return { value: buildMailTo(email), parameters: { cn: cn || email, partstat: partstat || ICAL_ATTENDEE_STATUS.NEEDS_ACTION, }, }; }; describe('getSelfAddressData()', () => { const originalAddress = { DisplayName: 'I', Email: '[email protected]', ID: '1', Status: ADDRESS_STATUS.STATUS_ENABLED, Receive: ADDRESS_RECEIVE.RECEIVE_YES, Send: ADDRESS_SEND.SEND_YES, Type: ADDRESS_TYPE.TYPE_ORIGINAL, } as Address; const freePmMeAddress = { DisplayName: "It's me", Email: '[email protected]', ID: '2', Status: ADDRESS_STATUS.STATUS_ENABLED, Receive: ADDRESS_RECEIVE.RECEIVE_YES, Send: ADDRESS_SEND.SEND_NO, Type: ADDRESS_TYPE.TYPE_PREMIUM, } as Address; const protonMailAddress = { DisplayName: "It's still me", Email: '[email protected]', ID: '3', Status: ADDRESS_STATUS.STATUS_ENABLED, Receive: ADDRESS_RECEIVE.RECEIVE_YES, Send: ADDRESS_SEND.SEND_YES, Type: ADDRESS_TYPE.TYPE_ALIAS, } as Address; const protonMailChAddress = { DisplayName: "It's me in CH", Email: '[email protected]', ID: '4', Status: ADDRESS_STATUS.STATUS_ENABLED, Receive: ADDRESS_RECEIVE.RECEIVE_YES, Send: ADDRESS_SEND.SEND_YES, Type: ADDRESS_TYPE.TYPE_ALIAS, } as Address; const aliasDisabledAddress = { DisplayName: 'Disabled me', Email: '[email protected]', ID: '5', Status: ADDRESS_STATUS.STATUS_DISABLED, Receive: ADDRESS_RECEIVE.RECEIVE_NO, Send: ADDRESS_SEND.SEND_NO, Type: ADDRESS_TYPE.TYPE_ALIAS, } as Address; const customDomainAddress = { DisplayName: 'Never gonna give you up', Email: '[email protected]', ID: '6', Status: ADDRESS_STATUS.STATUS_ENABLED, Receive: ADDRESS_RECEIVE.RECEIVE_YES, Send: ADDRESS_SEND.SEND_YES, Type: ADDRESS_TYPE.TYPE_CUSTOM_DOMAIN, } as Address; const externalAddress = { DisplayName: 'Much crypto', Email: '[email protected]', ID: '7', Status: ADDRESS_STATUS.STATUS_ENABLED, Receive: ADDRESS_RECEIVE.RECEIVE_NO, Send: ADDRESS_SEND.SEND_NO, Type: ADDRESS_TYPE.TYPE_EXTERNAL, } as Address; const addresses = [ originalAddress, freePmMeAddress, protonMailAddress, protonMailChAddress, aliasDisabledAddress, customDomainAddress, externalAddress, ]; it('identifies me as an organizer when organizing an event', () => { const organizer = buildVcalOrganizer('[email protected]'); const protonAttendee = buildVcalAttendee({ email: '[email protected]', cn: 'proton', partstat: ICAL_ATTENDEE_STATUS.DECLINED, }); const externalAttendee = buildVcalAttendee({ email: '[email protected]', cn: 'BTC', partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); const attendees = [protonAttendee, externalAttendee]; expect(getSelfAddressData({ organizer, attendees, addresses })).toEqual({ isOrganizer: true, isAttendee: false, selfAddress: originalAddress, }); }); it('does not identify me as an organizer when organizing an event with an external address', () => { const organizer = buildVcalOrganizer(externalAddress.Email); const protonAttendee = buildVcalAttendee({ email: '[email protected]', cn: 'proton', partstat: ICAL_ATTENDEE_STATUS.DECLINED, }); const otherAttendee = buildVcalAttendee({ email: 'other@888', cn: 'The others', partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); const attendees = [protonAttendee, otherAttendee]; expect(getSelfAddressData({ organizer, attendees, addresses })).toEqual({ isOrganizer: false, isAttendee: false, selfAddress: undefined, selfAttendee: undefined, selfAttendeeIndex: undefined, }); }); it('does not identify me as an attendee when attending an event with an external address', () => { const organizer = buildVcalOrganizer('[email protected]'); const externalAddressAttendee = buildVcalAttendee({ email: externalAddress.Email, cn: 'proton', partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); const otherAttendee = buildVcalAttendee({ email: 'other@888', cn: 'The others', partstat: ICAL_ATTENDEE_STATUS.TENTATIVE, }); const attendees = [externalAddressAttendee, otherAttendee]; expect(getSelfAddressData({ organizer, attendees, addresses })).toEqual({ isOrganizer: false, isAttendee: false, selfAddress: undefined, selfAttendee: undefined, selfAttendeeIndex: undefined, }); }); describe('identifies me as an attendee when attending an event', () => { const organizer = buildVcalOrganizer('[email protected]'); it('picks first active answered attendee', () => { const originalAttendee = buildVcalAttendee({ email: originalAddress.Email, partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION, }); const freePmMeAttendee = buildVcalAttendee({ email: freePmMeAddress.Email, partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); const protonMailAttendee = buildVcalAttendee({ email: protonMailAddress.Email, partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION, }); const protonMailChAttendee = buildVcalAttendee({ email: protonMailChAddress.Email, partstat: ICAL_ATTENDEE_STATUS.TENTATIVE, }); const aliasDisabledAttendee = buildVcalAttendee({ email: aliasDisabledAddress.Email, partstat: ICAL_ATTENDEE_STATUS.DECLINED, }); const customDomainAttendee = buildVcalAttendee({ email: customDomainAddress.Email, partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); const externalAttendee = buildVcalAttendee({ email: externalAddress.Email, partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); expect( getSelfAddressData({ organizer, attendees: [ externalAttendee, customDomainAttendee, freePmMeAttendee, aliasDisabledAttendee, originalAttendee, protonMailAttendee, protonMailChAttendee, ], addresses, }) ).toEqual({ isOrganizer: false, isAttendee: true, selfAddress: protonMailChAddress, selfAttendee: protonMailChAttendee, selfAttendeeIndex: 6, }); }); it('picks first active unanswered attendee if only inactive answered', () => { const originalAttendee = buildVcalAttendee({ email: originalAddress.Email, partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION, }); const freePmMeAttendee = buildVcalAttendee({ email: freePmMeAddress.Email, partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); const protonMailAttendee = buildVcalAttendee({ email: protonMailAddress.Email, partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION, }); const protonMailChAttendee = buildVcalAttendee({ email: protonMailChAddress.Email, partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION, }); const aliasDisabledAttendee = buildVcalAttendee({ email: aliasDisabledAddress.Email, partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); const customDomainAttendee = buildVcalAttendee({ email: customDomainAddress.Email, partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION, }); const externalAttendee = buildVcalAttendee({ email: externalAddress.Email, partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); expect( getSelfAddressData({ organizer, attendees: [ externalAttendee, customDomainAttendee, freePmMeAttendee, aliasDisabledAttendee, originalAttendee, protonMailAttendee, protonMailChAttendee, ], addresses, }) ).toEqual({ isOrganizer: false, isAttendee: true, selfAddress: originalAddress, selfAttendee: originalAttendee, selfAttendeeIndex: 4, }); }); it('picks first inactive answered attendee if all inactive', () => { const freePmMeAttendee = buildVcalAttendee({ email: freePmMeAddress.Email, partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION, }); const aliasDisabledAttendee = buildVcalAttendee({ email: aliasDisabledAddress.Email, partstat: ICAL_ATTENDEE_STATUS.DECLINED, }); const externalAttendee = buildVcalAttendee({ email: externalAddress.Email, partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); expect( getSelfAddressData({ organizer, attendees: [externalAttendee, freePmMeAttendee, aliasDisabledAttendee], addresses, }) ).toEqual({ isOrganizer: false, isAttendee: true, selfAddress: aliasDisabledAddress, selfAttendee: aliasDisabledAttendee, selfAttendeeIndex: 2, }); }); }); it('identifies me as an attendee when using a pm.me address', () => { const organizer = buildVcalOrganizer('[email protected]'); const anotherAttendee = buildVcalAttendee({ email: 'another@not_proton.me', cn: 'external' }); const pmMeAttendee = buildVcalAttendee({ email: '[email protected]', cn: 'MEEE', partstat: ICAL_ATTENDEE_STATUS.ACCEPTED, }); const attendees = [anotherAttendee, pmMeAttendee]; const originalAddress = { DisplayName: 'I', Email: '[email protected]', ID: '1', Receive: ADDRESS_RECEIVE.RECEIVE_YES, Send: ADDRESS_SEND.SEND_YES, Type: ADDRESS_TYPE.TYPE_ORIGINAL, } as Address; const pmMeAddress = { DisplayName: "It's me", Email: '[email protected]', ID: '2', Receive: ADDRESS_RECEIVE.RECEIVE_YES, Send: ADDRESS_SEND.SEND_NO, Type: ADDRESS_TYPE.TYPE_PREMIUM, } as Address; const addresses = [originalAddress, pmMeAddress]; expect(getSelfAddressData({ organizer, attendees, addresses })).toEqual({ isOrganizer: false, isAttendee: true, selfAttendee: pmMeAttendee, selfAddress: pmMeAddress, selfAttendeeIndex: 1, }); }); });
8,789
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/getFrequencyString.spec.js
import { enUS } from 'date-fns/locale'; import { FREQUENCY } from '../../lib/calendar/constants'; import { getTimezonedFrequencyString } from '../../lib/calendar/recurrence/getFrequencyString'; import { getDateTimeProperty, getUntilProperty } from '../../lib/calendar/vcalConverter'; import { getFormattedWeekdays } from '../../lib/date/date'; const weekdays = getFormattedWeekdays('cccc', { locale: enUS }); const dummyTzid = 'Europe/Athens'; const options = { currentTzid: dummyTzid, weekdays, locale: enUS }; const dummyStart = getDateTimeProperty({ year: 2020, month: 1, day: 20 }, dummyTzid); const dummyUntil = getUntilProperty({ year: 2020, month: 2, day: 20 }, false, dummyTzid); const dummyRruleValue = { freq: FREQUENCY.DAILY, }; const getRrule = (value) => ({ value: { ...dummyRruleValue, ...value } }); const otherTzOptions = { ...options, currentTzid: 'Pacific/Tahiti' }; describe('getTimezonedFrequencyString should produce the expected string for daily recurring events', () => { it('should get a standard daily recurring event', () => { expect(getTimezonedFrequencyString(getRrule(dummyRruleValue), dummyStart, options)).toEqual('Daily'); }); it('should get a custom daily recurring event that is actually standard', () => { const rrule = getRrule(); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Daily'); }); it('should get a custom daily recurring event happening every 2 days', () => { const rrule = getRrule({ interval: 2, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Every 2 days'); }); it('should get a custom daily recurring event happening every three days, lasting 5 times', () => { const rrule = getRrule({ interval: 3, count: 5, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Every 3 days, 5 times'); }); it('should get a custom daily recurring event, until 20th February 2020', () => { const rrule = getRrule({ until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Daily, until Feb 20, 2020'); }); it('should get a custom daily recurring event happening every two days, lasting 1 time on a different timezone', () => { const rrule = getRrule({ interval: 2, count: 1, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Every 2 days, 1 time'); }); it('should get a custom daily event, until 20th February 2020 on a different timezone', () => { const rrule = getRrule({ until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, otherTzOptions)).toEqual( 'Daily, until Feb 20, 2020 (Europe/Athens)' ); }); it('should get a custom daily event happening every two days, until 20th February 2020 on a different timezone', () => { const rrule = getRrule({ interval: 2, until: dummyUntil, }); const extendedOptions = otherTzOptions; expect(getTimezonedFrequencyString(rrule, dummyStart, extendedOptions)).toEqual( 'Every 2 days, until Feb 20, 2020 (Europe/Athens)' ); }); }); describe('getTimezonedFrequencyString should produce the expected string for weekly recurring events', () => { const getWeeklyRrule = (rrule) => getRrule({ ...rrule, freq: FREQUENCY.WEEKLY }); it('should get a standard weekly recurring event', () => { const rrule = getWeeklyRrule(); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Weekly on Monday'); }); it('should get a standard weekly recurring event, on a different timezone', () => { const rrule = getWeeklyRrule(); expect(getTimezonedFrequencyString(rrule, dummyStart, otherTzOptions)).toEqual( 'Weekly on Monday (Europe/Athens)' ); }); it('should get a custom weekly recurring event that is actually standard', () => { const rrule = getWeeklyRrule({ byday: ['MO'], }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Weekly on Monday'); }); it('should get a custom weekly recurring event happening every 2 weeks', () => { const rrule = getWeeklyRrule({ interval: 2, byday: ['MO'], }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Every 2 weeks on Monday'); }); it('should get a custom weekly recurring event happening every 2 weeks, on Monday and Tuesday, lasting 1 time', () => { const rrule = getWeeklyRrule({ interval: 2, byday: ['MO', 'TU'], count: 1, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual( 'Every 2 weeks on Monday, Tuesday, 1 time' ); }); it('should get a custom weekly recurring event happening on all days of the week', () => { const rrule = getWeeklyRrule({ interval: 1, byday: ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'], }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Weekly on all days'); }); it('should get a custom weekly recurring event happening every three weeks, on all days of the week, lasting 5 times', () => { const rrule = getWeeklyRrule({ interval: 3, byday: ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'], count: 5, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Every 3 weeks on all days, 5 times'); }); it('should get a weekly rrule with an until date in a different timezone', () => { const tzid = 'America/Kentucky/Louisville'; const rrule = getWeeklyRrule({ interval: 1, byday: ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'], until: getUntilProperty({ year: 2020, month: 10, day: 17 }, false, tzid), }); const start = getDateTimeProperty({ year: 2020, month: 1, day: 20 }, tzid); expect(getTimezonedFrequencyString(rrule, start, options)).toEqual( 'Weekly on all days, until Oct 17, 2020 (America/Kentucky/Louisville)' ); }); it('should get a custom weekly recurring event happening every three weeks, on all days of the week, until 20th February 2020', () => { const rrule = getWeeklyRrule({ interval: 3, byday: ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'], until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual( 'Every 3 weeks on all days, until Feb 20, 2020' ); }); it('should get a custom weekly recurring event happening on Monday and Wednesday, until 20th February 2020', () => { const rrule = getWeeklyRrule({ byday: ['MO', 'WE'], until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual( 'Weekly on Monday, Wednesday, until Feb 20, 2020' ); }); it('should get a custom weekly recurring event happening every 2 weeks on Monday and Wednesday, until 20th February 2020', () => { const rrule = getWeeklyRrule({ interval: 2, byday: ['MO', 'WE'], until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual( 'Every 2 weeks on Monday, Wednesday, until Feb 20, 2020' ); }); it('should get a custom weekly recurring event happening weekly on Monday, on a different timezone', () => { const rrule = getWeeklyRrule({ interval: 1, byday: ['MO'], until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, { ...options, currentTzid: 'Pacific/Tahiti ' })).toEqual( 'Weekly on Monday, until Feb 20, 2020 (Europe/Athens)' ); }); it('should get a custom weekly recurring event happening every 2 weeks on all days, until 20th February 2020 on a different timezone', () => { const rrule = getWeeklyRrule({ interval: 2, byday: ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'], until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, otherTzOptions)).toEqual( 'Every 2 weeks on all days, until Feb 20, 2020 (Europe/Athens)' ); }); it('should get a custom weekly recurring event happening every 2 weeks on all days, 2 times on a different timezone', () => { const rrule = getWeeklyRrule({ interval: 2, byday: ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'], count: 2, }); expect(getTimezonedFrequencyString(rrule, dummyStart, otherTzOptions)).toEqual( 'Every 2 weeks on all days, 2 times' ); }); }); describe('getTimezonedFrequencyString should produce the expected string for monthly recurring events', () => { const getMonthlyRrule = (rrule = {}) => getRrule({ ...rrule, freq: FREQUENCY.MONTHLY }); it('should get a standard monthly recurring event', () => { expect(getTimezonedFrequencyString(getMonthlyRrule(), dummyStart, options)).toEqual('Monthly on day 20'); }); it('should get a standard monthly recurring event, on a different timezone', () => { expect(getTimezonedFrequencyString(getMonthlyRrule(), dummyStart, otherTzOptions)).toEqual( 'Monthly on day 20 (Europe/Athens)' ); }); it('should get a custom monthly recurring event happening every 2 months', () => { const rrule = getMonthlyRrule({ interval: 2, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Every 2 months on day 20'); }); it('should get a custom monthly recurring event happening every 2 months, on the third Monday', () => { const rrule = getMonthlyRrule({ interval: 2, bysetpos: 4, byday: 'MO', }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Every 2 months on the third Monday'); }); it('should get a custom monthly recurring event, on the first Monday, different timezone', () => { const rrule = getMonthlyRrule({ bysetpos: 1, byday: 'MO', }); const start = getDateTimeProperty({ year: 2020, month: 1, day: 6 }, dummyTzid); expect(getTimezonedFrequencyString(rrule, start, otherTzOptions)).toEqual( 'Monthly on the first Monday (Europe/Athens)' ); }); it('should get a custom monthly recurring event happening every 2 months, on the last Wednesday, lasting 3 times', () => { const start = getDateTimeProperty({ year: 2020, month: 1, day: 29 }, dummyTzid); const rrule = getMonthlyRrule({ interval: 2, bysetpos: -1, byday: 'WE', count: 3, }); expect(getTimezonedFrequencyString(rrule, start, options)).toEqual( 'Every 2 months on the last Wednesday, 3 times' ); }); it('should get a custom monthly recurring event happening every 2 months, on the last Wednesday, lasting 1 time', () => { const start = getDateTimeProperty({ year: 2020, month: 1, day: 29 }, dummyTzid); const rrule = getMonthlyRrule({ interval: 2, bysetpos: -1, byday: 'WE', count: 1, }); expect(getTimezonedFrequencyString(rrule, start, options)).toEqual( 'Every 2 months on the last Wednesday, 1 time' ); }); it('should get a custom monthly recurring event happening on a fifth and last Thursday, until 20th February 2020', () => { const start = getDateTimeProperty({ year: 2020, month: 1, day: 30 }, dummyTzid); const rrule = getMonthlyRrule({ bysetpos: -1, byday: 'TH', until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, start, options)).toEqual( 'Monthly on the last Thursday, until Feb 20, 2020' ); }); it('should get a custom monthly recurring event happening every three months on a fifth and last Thursday, until 20th February 2020', () => { const start = getDateTimeProperty({ year: 2020, month: 1, day: 30 }, dummyTzid); const rrule = getMonthlyRrule({ freq: FREQUENCY.MONTHLY, interval: 3, bysetpos: -1, byday: 'TH', until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, start, options)).toEqual( 'Every 3 months on the last Thursday, until Feb 20, 2020' ); }); it('should get a custom monthly recurring event happening on a fifth and last Thursday, until 20th February 2020 on a different timezone', () => { const start = getDateTimeProperty({ year: 2020, month: 1, day: 30 }, dummyTzid); const rrule = getMonthlyRrule({ bysetpos: -1, byday: 'TH', until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, start, otherTzOptions)).toEqual( 'Monthly on the last Thursday, until Feb 20, 2020 (Europe/Athens)' ); }); }); describe('getTimezonedFrequencyString should produce the expected string for yearly recurring events', () => { const getYearlyRrule = (rrule = {}) => getRrule({ ...rrule, freq: FREQUENCY.YEARLY }); it('should get a standard yearly recurring event', () => { expect(getTimezonedFrequencyString(getYearlyRrule(), dummyStart, options)).toEqual('Yearly'); }); it('should get a custom yearly recurring event happening every 2 years, lasting 1 time', () => { const rrule = getYearlyRrule({ interval: 2, count: 1, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Every 2 years, 1 time'); }); it('should get a custom yearly recurring event happening every three years, lasting 5 times', () => { const rrule = getYearlyRrule({ interval: 3, count: 5, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Every 3 years, 5 times'); }); it('should get a custom yearly recurring event, until 20th February 2020', () => { const rrule = getYearlyRrule({ interval: 1, until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Yearly, until Feb 20, 2020'); }); it('should get a custom weekly recurring event happening every year, lasting 8 times on a different timezone', () => { const rrule = getYearlyRrule({ count: 8, }); expect(getTimezonedFrequencyString(rrule, dummyStart, otherTzOptions)).toEqual('Yearly, 8 times'); }); it('should get a custom weekly recurring event happening every two years, lasting 2 times on a different timezone', () => { const rrule = getYearlyRrule({ interval: 2, count: 2, }); expect(getTimezonedFrequencyString(rrule, dummyStart, otherTzOptions)).toEqual('Every 2 years, 2 times'); }); it('should get a custom yearly event, until 20th February 2020 on a different timezone', () => { const rrule = getYearlyRrule({ until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, otherTzOptions)).toEqual( 'Yearly, until Feb 20, 2020 (Europe/Athens)' ); }); it('should get a custom yearly event happening every ten years until 20th February 2020 on a different timezone', () => { const rrule = getYearlyRrule({ interval: 10, until: dummyUntil, }); expect(getTimezonedFrequencyString(rrule, dummyStart, otherTzOptions)).toEqual( 'Every 10 years, until Feb 20, 2020 (Europe/Athens)' ); }); }); describe('getTimezonedFrequencyString should produce the expected string for unsupported recurring rules', () => { const getCustomRrule = (rrule) => getRrule({ ...rrule, x: 'test' }); it('should get a non-supported daily recurring event', () => { const rrule = getCustomRrule({ freq: FREQUENCY.DAILY, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Custom daily'); }); it('shold get a non-supported weekly recurring event', () => { const rrule = getCustomRrule({ freq: FREQUENCY.WEEKLY, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Custom weekly'); }); it('should get a non-supported monthly recurring event', () => { const rrule = getCustomRrule({ freq: FREQUENCY.MONTHLY, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Custom monthly'); }); it('should geta non-supported yearly recurring event', () => { const rrule = getCustomRrule({ freq: FREQUENCY.YEARLY, }); expect(getTimezonedFrequencyString(rrule, dummyStart, options)).toEqual('Custom yearly'); }); });
8,790
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/helper.spec.ts
import { MAX_CHARS_API } from '../../lib/calendar/constants'; import { generateVeventHashUID, getHasLegacyHashUID, getOriginalUID, getSupportedUID } from '../../lib/calendar/helper'; describe('getSupportedUID', () => { it('should retain short UIDs', () => { const uid = '[email protected]'; expect(getSupportedUID(uid)).toEqual(uid); }); it('should crop long UIDs', () => { const uid = '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890@domaine.com'; expect(getSupportedUID(uid)).toEqual( '23456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890@domaine.com' ); }); }); describe('getVeventHashUID', () => { const binaryString = 'some random words for the test'; const shortUid = '[email protected]'; const longUid = 'Cm5XpErjCp4syBD1zI0whscVHuQklN3tvXxxXpaewdBGEpOFTcMCqM8WDLLYDM6kuXAqdTqL1y98SRrf5thkyceT01boWtEeCkrep75kRiKnHE5YnBKYvEFmcWKJ0q0eeNWIN4OLZ8yJnSDdC8DT9CndSxOnnPC47VWjQHu0psXB25lZuCt4EWsWAtgmCPWe1Wa0AIL0y8rlPn0qbB05u3WuyOst8XYkJNWz6gYx@domaine.com'; it('should generate new UIDs', async () => { expect(await generateVeventHashUID(binaryString)).toEqual('sha1-uid-b8ae0238d0011a4961a2d259e33bd383672b9229'); }); it('should generate the same UID with or without legacy format', async () => { expect(await generateVeventHashUID(binaryString)).toEqual(await generateVeventHashUID(binaryString, '', true)); }); it('should keep short UIDs before the hash', async () => { expect(await generateVeventHashUID(binaryString, shortUid)).toEqual( 'original-uid-stmyce9lb3ef@domain.com-sha1-uid-b8ae0238d0011a4961a2d259e33bd383672b9229' ); }); it('should crop long UIDs before the hash', async () => { const hashUID = await generateVeventHashUID(binaryString, longUid); expect(hashUID.length).toEqual(MAX_CHARS_API.UID); expect(hashUID).toEqual( 'original-uid-vEFmcWKJ0q0eeNWIN4OLZ8yJnSDdC8DT9CndSxOnnPC47VWjQHu0psXB25lZuCt4EWsWAtgmCPWe1Wa0AIL0y8rlPn0qbB05u3WuyOst8XYkJNWz6gYx@domaine.com-sha1-uid-b8ae0238d0011a4961a2d259e33bd383672b9229' ); }); it('should keep short UIDs after the hash when using legacy format', async () => { expect(await generateVeventHashUID(binaryString, shortUid, true)).toEqual( 'sha1-uid-b8ae0238d0011a4961a2d259e33bd383672b9229-original-uid-stmyce9lb3ef@domain.com' ); }); it('should crop long UIDs after the hash when using legacy format', async () => { const hashUID = await generateVeventHashUID(binaryString, longUid, true); expect(hashUID.length).toEqual(MAX_CHARS_API.UID); expect(hashUID).toEqual( 'sha1-uid-b8ae0238d0011a4961a2d259e33bd383672b9229-original-uid-vEFmcWKJ0q0eeNWIN4OLZ8yJnSDdC8DT9CndSxOnnPC47VWjQHu0psXB25lZuCt4EWsWAtgmCPWe1Wa0AIL0y8rlPn0qbB05u3WuyOst8XYkJNWz6gYx@domaine.com' ); }); }); describe('getOriginalUID', () => { const binaryString = 'some random words for the test'; const shortUid = '[email protected]'; const longUid = 'Cm5XpErjCp4syBD1zI0whscVHuQklN3tvXxxXpaewdBGEpOFTcMCqM8WDLLYDM6kuXAqdTqL1y98SRrf5thkyceT01boWtEeCkrep75kRiKnHE5YnBKYvEFmcWKJ0q0eeNWIN4OLZ8yJnSDdC8DT9CndSxOnnPC47VWjQHu0psXB25lZuCt4EWsWAtgmCPWe1Wa0AIL0y8rlPn0qbB05u3WuyOst8XYkJNWz6gYx@domaine.com'; const longUidLength = longUid.length; it('should return the empty string if passed nothing', () => { expect(getOriginalUID()).toEqual(''); }); it('should retrieve the original short UIDs after the hash operation (legacy or not)', async () => { expect(getOriginalUID(await generateVeventHashUID(binaryString, shortUid))).toEqual(shortUid); expect(getOriginalUID(await generateVeventHashUID(binaryString, shortUid, true))).toEqual(shortUid); }); it('should retrieve no UID after the hash operation if there was none before', async () => { expect(getOriginalUID(await generateVeventHashUID(binaryString))).toEqual(''); }); it('should retrieve a cropped version of long UIDs after the hash operation (legacy or not)', async () => { expect(getOriginalUID(await generateVeventHashUID(binaryString, longUid))).toEqual( longUid.substring(longUidLength - 128, longUidLength) ); expect(getOriginalUID(await generateVeventHashUID(binaryString, longUid, true))).toEqual( longUid.substring(longUidLength - 128, longUidLength) ); }); it('should return the uid if it is not a hash', async () => { expect(getOriginalUID('random-uid')).toEqual('random-uid'); }); }); describe('getHasLegacyHashUID', () => { const binaryString = 'some random words for the test'; const shortUid = '[email protected]'; const longUid = 'Cm5XpErjCp4syBD1zI0whscVHuQklN3tvXxxXpaewdBGEpOFTcMCqM8WDLLYDM6kuXAqdTqL1y98SRrf5thkyceT01boWtEeCkrep75kRiKnHE5YnBKYvEFmcWKJ0q0eeNWIN4OLZ8yJnSDdC8DT9CndSxOnnPC47VWjQHu0psXB25lZuCt4EWsWAtgmCPWe1Wa0AIL0y8rlPn0qbB05u3WuyOst8XYkJNWz6gYx@domaine.com'; it('should return false if the empty string is passed', () => { expect(getHasLegacyHashUID('')).toEqual(false); }); it('should return false if a new hash uid is passed', async () => { expect(getHasLegacyHashUID(await generateVeventHashUID(binaryString, shortUid))).toEqual(false); expect(getHasLegacyHashUID(await generateVeventHashUID(binaryString, longUid))).toEqual(false); }); it('should return true if a legacy uid is passed', async () => { expect(getHasLegacyHashUID(await generateVeventHashUID(binaryString, shortUid, true))).toEqual(true); expect(getHasLegacyHashUID(await generateVeventHashUID(binaryString, longUid, true))).toEqual(true); }); });
8,791
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/ics.spec.ts
import { parseWithRecovery, reformatDateTimes, reformatLineBreaks, unfoldLines, } from '../../lib/calendar/icsSurgery/ics'; describe('reformatLineBreaks()', () => { it('should reformat line breaks with RFC 7896 properties', () => { const vcal = `BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Office Holidays Ltd.//EN X-WR-CALNAME:United Kingdom Holidays X-WR-CALDESC:Public Holidays in United Kingdom. Provided by http://www.officeholidays.com REFRESH-INTERVAL;VALUE=DURATION:PT48H X-PUBLISHED-TTL:PT48H CALSCALE:GREGORIAN METHOD:PUBLISH X-MS-OLK-FORCEINSPECTOROPEN:TRUE BEGIN:VEVENT CLASS:PUBLIC UID:[email protected] CREATED:20220109T153551Z DESCRIPTION: This additional days holiday for New Year in the UK is observed only in Scotland \\n\\nScotland\\n\\nInformation provided by www.officeholidays.com URL:https://www.officeholidays.com/holidays/united-kingdom/scotland/day-after-new-years-day DTSTART;VALUE=DATE:20220104 DTEND;VALUE=DATE:20220105 DTSTAMP:20080101T000000Z LOCATION:Scotland PRIORITY:5 LAST-MODIFIED:20191229T000000Z SEQUENCE:1 SUMMARY;LANGUAGE=en-us:Day after New Year's Day (in lieu) (Regional Holiday) TRANSP:OPAQUE X-MICROSOFT-CDO-BUSYSTATUS:BUSY X-MICROSOFT-CDO-IMPORTANCE:1 X-MICROSOFT-DISALLOW-COUNTER:FALSE X-MS-OLK-ALLOWEXTERNCHECK:TRUE X-MS-OLK-AUTOFILLLOCATION:FALSE X-MICROSOFT-CDO-ALLDAYEVENT:TRUE X-MICROSOFT-MSNCALENDAR-ALLDAYEVENT:TRUE X-MS-OLK-CONFTYPE:0 END:VEVENT END:VCALENDAR`; expect(reformatLineBreaks(vcal)).toEqual(`BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Office Holidays Ltd.//EN X-WR-CALNAME:United Kingdom Holidays X-WR-CALDESC:Public Holidays in United Kingdom. Provided by http://www.officeholidays.com REFRESH-INTERVAL;VALUE=DURATION:PT48H X-PUBLISHED-TTL:PT48H CALSCALE:GREGORIAN METHOD:PUBLISH X-MS-OLK-FORCEINSPECTOROPEN:TRUE BEGIN:VEVENT CLASS:PUBLIC UID:[email protected] CREATED:20220109T153551Z DESCRIPTION: This additional days holiday for New Year in the UK is observed only in Scotland \\n\\nScotland\\n\\nInformation provided by www.officeholidays.com URL:https://www.officeholidays.com/holidays/united-kingdom/scotland/day-after-new-years-day DTSTART;VALUE=DATE:20220104 DTEND;VALUE=DATE:20220105 DTSTAMP:20080101T000000Z LOCATION:Scotland PRIORITY:5 LAST-MODIFIED:20191229T000000Z SEQUENCE:1 SUMMARY;LANGUAGE=en-us:Day after New Year's Day (in lieu) (Regional Holiday) TRANSP:OPAQUE X-MICROSOFT-CDO-BUSYSTATUS:BUSY X-MICROSOFT-CDO-IMPORTANCE:1 X-MICROSOFT-DISALLOW-COUNTER:FALSE X-MS-OLK-ALLOWEXTERNCHECK:TRUE X-MS-OLK-AUTOFILLLOCATION:FALSE X-MICROSOFT-CDO-ALLDAYEVENT:TRUE X-MICROSOFT-MSNCALENDAR-ALLDAYEVENT:TRUE X-MS-OLK-CONFTYPE:0 END:VEVENT END:VCALENDAR`); }); }); describe('unfoldLines()', () => { it('unfolds a properly folded ICS', () => { expect( unfoldLines( `BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT CLASS:PUBLIC DESCRIPTION:Join us for a look at new product updates so you ca n do more with your content and accelerate your workflows. Hooray! LOCATION:Multiple lines SUMMARY:The Drop: Fall Launch TRANSP:TRANSPARENT DTSTART:20221025T130000Z DTEND:20221026T070000Z URL:https://experience.dropbox.com/events-webinars/thedigitaldr op-fall2022 END:VEVENT END:VCALENDAR`, '\n' ) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT CLASS:PUBLIC DESCRIPTION:Join us for a look at new product updates so you can do more with your content and accelerate your workflows.\nHooray! LOCATION:Multiple lines SUMMARY:The Drop: Fall Launch TRANSP:TRANSPARENT DTSTART:20221025T130000Z DTEND:20221026T070000Z URL:https://experience.dropbox.com/events-webinars/thedigitaldrop-fall2022 END:VEVENT END:VCALENDAR`); }); }); describe('reformatDateTimes()', () => { it('reformats too short or too long DTSTAMP, DTSTART, DTEND, LAST-MODIFIED', () => { expect( reformatDateTimes(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP:20221010T1200 DTSTART:20221111T13 DTEND:20221111T1430 LAST-MODIFIED:20221010T120049375Z END:VEVENT END:VCALENDAR`) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP:20221010T120000 DTSTART:20221111T130000 DTEND:20221111T143000 LAST-MODIFIED:20221010T120049Z END:VEVENT END:VCALENDAR`); }); it('reformats date-time properties with a time zone', () => { expect( reformatDateTimes(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP;TZID=America/Guatemala:20221010T1200 END:VEVENT END:VCALENDAR`) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP;TZID=America/Guatemala:20221010T120000 END:VEVENT END:VCALENDAR`); }); it('reformats folded date-time properties', () => { expect( reformatDateTimes(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTEND;TZID==/mozilla.org/20050126_1/America/Guatemala:2022 1010T1200 END:VEVENT END:VCALENDAR`) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTEND;TZID==/mozilla.org/20050126_1/America/Guatemala:20221010T120000 END:VEVENT END:VCALENDAR`); }); it('reformats untrimmed date-time properties', () => { expect( reformatDateTimes(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART:20221010T1200 DTEND: 20221004T103000 END:VEVENT END:VCALENDAR`) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART:20221010T120000 DTEND:20221004T103000 END:VEVENT END:VCALENDAR`); }); it('reformats date-time properties with ISO format', () => { expect( reformatDateTimes(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP:2022-09-02T23:59:59.999 DTSTART:2022-10-04T09:30:00.000Z DTEND:2022-10-05T12:30:00.000ZZ END:VEVENT END:VCALENDAR`) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP:20220902T235959 DTSTART:20221004T093000Z DTEND:20221005T123000Z END:VEVENT END:VCALENDAR`); }); it('reformats date-time properties with "Deutsche Bahn format"', () => { expect( reformatDateTimes(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;TZID=Europe/Berlin:2023-06-21T082400 DTEND;TZID=Europe/Berlin:2023-06-21T165400 DTSTAMP:2023-06-13T212500Z END:VEVENT END:VCALENDAR`) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;TZID=Europe/Berlin:20230621T082400 DTEND;TZID=Europe/Berlin:20230621T165400 DTSTAMP:20230613T212500Z END:VEVENT END:VCALENDAR`); }); it('reformats date properties with "Deutsche Bahn format"', () => { expect( reformatDateTimes(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:2023-06-21 DTEND;VALUE=DATE:2023-06-22 DTSTAMP:2023-06-13T212500Z END:VEVENT END:VCALENDAR`) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:20230621 DTEND;VALUE=DATE:20230622 DTSTAMP:20230613T212500Z END:VEVENT END:VCALENDAR`); }); it('reformats all-day date-time properties missing', () => { expect( reformatDateTimes(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART:20221004 END:VEVENT END:VCALENDAR`) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:20221004 END:VEVENT END:VCALENDAR`); }); it('reformats date-time properties with uncapitalized markers', () => { expect( reformatDateTimes(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP:20221004t155959z DTSTART:20221004t155959 DTEND:2022-10-05t12:30:00.000zz END:VEVENT END:VCALENDAR`) ).toEqual(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP:20221004T155959Z DTSTART:20221004T155959 DTEND:20221005T123000Z END:VEVENT END:VCALENDAR`); }); }); describe('parseWithRecovery()', () => { it('should parse vevent with bad enclosing and bad line breaks', () => { const result = parseWithRecovery(`BEGIN:VCALENDAR METHOD:REQUEST PRODID:Microsoft Exchange Server 2010 VERSION:2.0 BEGIN:VEVENT DTSTAMP:20190719T130854Z UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;TZID=America/New_York:20190719T120000 DTEND;TZID=Europe/Zurich:20190719T130000 CATEGORIES:ANNIVERSARY,PERSONAL,SPECIAL OCCASION SUMMARY:Our Blissful Anniversary --- Wonderful! LOCATION:A secret ... place END:VEVENT`); expect(result).toEqual({ component: 'vcalendar', method: { value: 'REQUEST' }, version: { value: '2.0' }, prodid: { value: 'Microsoft Exchange Server 2010' }, components: [ { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstamp: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 8, seconds: 54, isUTC: true }, }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, categories: [ { value: ['ANNIVERSARY', 'PERSONAL', 'SPECIAL OCCASION'], }, ], summary: { value: 'Our Blissful Anniversary---Wonderful!', }, location: { value: 'A secret...place', }, }, ], }); }); it('should parse vevent with mixed bad line breaks', () => { const result = parseWithRecovery(`BEGIN:VCALENDAR METHOD:REQUEST\r\nPRODID:Microsoft Exchange Server 2010 VERSION:2.0 BEGIN:VEVENT DTSTAMP:20190719T130854Z UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;TZID=America/New_York:20190719T120000 DTEND;TZID=Europe/Zurich:20190719T130000 CATEGORIES:ANNIVERSARY,PERSONAL,SPECIAL OCCASION SUMMARY:Our Blissful Anniversary --- Wonderful! LOCATION:A secret ... place END:VEVENT END:VCALENDAR`); expect(result).toEqual({ component: 'vcalendar', method: { value: 'REQUEST' }, version: { value: '2.0' }, prodid: { value: 'Microsoft Exchange Server 2010' }, components: [ { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstamp: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 8, seconds: 54, isUTC: true }, }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, categories: [ { value: ['ANNIVERSARY', 'PERSONAL', 'SPECIAL OCCASION'], }, ], summary: { value: 'Our Blissful Anniversary---Wonderful!', }, location: { value: 'A secret...place', }, }, ], }); }); it('should parse vevent with badly formatted date-time properties', () => { const result = parseWithRecovery(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP:20190719T1308 UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;TZID=America/New_York:2019-07-19T12:00:00:000 DTEND: 20290719 LAST-MODIFIED : 20190719t1308zZ END:VEVENT END:VCALENDAR`); expect(result).toEqual({ component: 'vcalendar', version: { value: '2.0' }, components: [ { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstamp: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 8, seconds: 0, isUTC: false }, }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 2029, month: 7, day: 19 }, parameters: { type: 'date' }, }, 'last-modified': { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 8, seconds: 0, isUTC: true }, }, }, ], }); }); it('should parse vevent with ISO-formatted date-time properties', () => { const result = parseWithRecovery(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTAMP:20230202T091854Z UID:[email protected] DTSTART:2023-02-04T09:30:00.000Z DTEND:2023-02-04T09:30:00.000Z RECURRENCE-ID:2023-02-04T10:30:00.000Z END:VEVENT END:VCALENDAR`); expect(result).toEqual({ component: 'vcalendar', version: { value: '2.0' }, components: [ { component: 'vevent', uid: { value: '[email protected]', }, dtstamp: { value: { year: 2023, month: 2, day: 2, hours: 9, minutes: 18, seconds: 54, isUTC: true }, }, dtstart: { value: { year: 2023, month: 2, day: 4, hours: 9, minutes: 30, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2023, month: 2, day: 4, hours: 9, minutes: 30, seconds: 0, isUTC: true }, }, 'recurrence-id': { value: { year: 2023, month: 2, day: 4, hours: 10, minutes: 30, seconds: 0, isUTC: true }, }, }, ], }); }); it('should parse vevent with missing ORGANIZER value parameter', () => { const result = parseWithRecovery(` BEGIN:VCALENDAR BEGIN:VEVENT CLASS:PUBLIC DTSTART:20230304T080000Z DTSTAMP:20230112T203527Z DTEND:20230306T153000Z LOCATION:Sixt South Melbourne, 101-109 Thistlethwaite Street, 3205 South Melbourne, AU TRANSP:TRANSPARENT SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Your rental car from Sixt UID:SIXT_XXXXXX END:VEVENT END:VCALENDAR `); // We can notice that the malformed ORGANIZER field has been omitted during the parsing expect(result).toEqual({ component: 'vcalendar', components: [ { component: 'vevent', class: { value: 'PUBLIC' }, dtstart: { value: { year: 2023, month: 3, day: 4, hours: 8, minutes: 0, seconds: 0, isUTC: true }, }, dtstamp: { value: { year: 2023, month: 1, day: 12, hours: 20, minutes: 35, seconds: 27, isUTC: true }, }, dtend: { value: { year: 2023, month: 3, day: 6, hours: 15, minutes: 30, seconds: 0, isUTC: true }, }, location: { value: 'Sixt South Melbourne, 101-109 Thistlethwaite Street, 3205 South Melbourne, AU', }, transp: { value: 'TRANSPARENT' }, sequence: { value: 0 }, status: { value: 'CONFIRMED' }, summary: { value: 'Your rental car from Sixt' }, uid: { value: 'SIXT_XXXXXX' }, }, ], }); }); });
8,792
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/import.spec.ts
import { enUS } from 'date-fns/locale'; import truncate from '@proton/utils/truncate'; import { ICAL_CALSCALE, ICAL_METHOD, MAX_CHARS_API } from '../../lib/calendar/constants'; import { getSupportedEvent } from '../../lib/calendar/icsSurgery/vevent'; import { extractSupportedEvent, getComponentIdentifier, getSupportedEvents, parseIcs, } from '../../lib/calendar/import/import'; import { parse, parseWithRecoveryAndMaybeErrors } from '../../lib/calendar/vcal'; import { getIcalMethod } from '../../lib/calendar/vcalHelper'; import { omit } from '../../lib/helpers/object'; import { VcalDateTimeProperty, VcalErrorComponent, VcalVcalendar, VcalVeventComponent, VcalVtimezoneComponent, } from '../../lib/interfaces/calendar/VcalModel'; describe('getComponentIdentifier', () => { it('should return the empty string if passed an error', () => { expect(getComponentIdentifier({ error: new Error('error'), icalComponent: 'any' })).toEqual(''); }); it('should return the tzid for a VTIMEZONE', () => { const vtimezone = `BEGIN:VTIMEZONE TZID:Europe/Vilnius BEGIN:DAYLIGHT TZOFFSETFROM:+0200 RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU DTSTART:20030330T030000 TZNAME:EEST TZOFFSETTO:+0300 END:DAYLIGHT BEGIN:STANDARD TZOFFSETFROM:+0300 RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU DTSTART:20031026T040000 TZNAME:EET TZOFFSETTO:+0200 END:STANDARD END:VTIMEZONE`; const timezone = parse(vtimezone) as VcalVtimezoneComponent; expect(getComponentIdentifier(timezone)).toEqual('Europe/Vilnius'); }); it('should return the uid for an event with a normal uid', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=America/New_York:20690312T083000 DTEND;TZID=America/New_York:20690312T093000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(getComponentIdentifier(event)).toEqual('test-event'); }); it('should return the original uid for an event with a hash uid with legacy format', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:original-uid-stmyce9lb3ef@domain.com-sha1-uid-b8ae0238d0011a4961a2d259e33bd383672b9229 DTSTART;TZID=America/New_York:20690312T083000 DTEND;TZID=America/New_York:20690312T093000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(getComponentIdentifier(event)).toEqual('[email protected]'); }); it('should return the original uid for an event with a hash uid with legacy format', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:sha1-uid-b8ae0238d0011a4961a2d259e33bd383672b9229-original-uid-stmyce9lb3ef@domain.com DTSTART;TZID=America/New_York:20690312T083000 DTEND;TZID=America/New_York:20690312T093000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(getComponentIdentifier(event)).toEqual('[email protected]'); }); it('should return the title when the event had no original uid', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:sha1-uid-b8ae0238d0011a4961a2d259e33bd383672b9229 DTSTART;TZID=America/New_York:20690312T083000 DTEND;TZID=America/New_York:20690312T093000 SUMMARY:Test event LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(getComponentIdentifier(event)).toEqual('Test event'); }); it('should return the date-time when the part-day event has no uid and no title', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z DTSTART;TZID=America/New_York:20690312T083000 DTEND;TZID=America/New_York:20690312T093000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(getComponentIdentifier(event, { locale: enUS })).toEqual('Mar 12, 2069, 8:30:00 AM'); }); it('should return the date when the all-day event has no uid and no title', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z DTSTART;VALUE=DATE:20690312 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(getComponentIdentifier(event, { locale: enUS })).toEqual('Mar 12, 2069'); }); }); describe('getSupportedEvent', () => { it('should catch events with start time before 1970', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=America/New_York:19690312T083000 DTEND;TZID=/America/New_York:19690312T093000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Start time out of bounds'); }); it('should catch events with start time after 2038', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;VALUE=DATE:20380101 DTEND;VALUE=DATE:20380102 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Start time out of bounds'); }); it('should catch malformed all-day events', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;VALUE=DATE:20180101 DTEND:20191231T203000Z LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Malformed all-day event'); }); it('should catch events with start and end time after 2038 and take time zones into account', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=America/New_York:20371231T203000 DTEND;TZID=America/New_York:20380101T003000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Start time out of bounds'); }); it('should accept events with sequence', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=America/New_York:20020312T083000 DTEND;TZID=America/New_York:20020312T082959 SEQUENCE:11 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 3, day: 12, hours: 8, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, sequence: { value: 11 }, }); }); it('should fix events with a sequence that is too big', () => { const sequenceOutOfBounds = 2 ** 31 + 3; const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=America/New_York:20020312T083000 DTEND;TZID=America/New_York:20020312T082959 SEQUENCE:${sequenceOutOfBounds} END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 3, day: 12, hours: 8, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, sequence: { value: 3 }, }); }); it('should accept (and re-format) events with negative duration and negative sequence', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=/America/New_York:20020312T083000 DTEND;TZID=/America/New_York:20020312T082959 LOCATION:1CP Conference Room 4350 SEQUENCE:-1 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 3, day: 12, hours: 8, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, }); }); it('should drop DTEND for part-day events with zero duration', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=/mozilla.org/20050126_1/America/New_York:20020312T083000 DTEND;TZID=/mozilla.org/20050126_1/America/New_York:20020312T083000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 3, day: 12, hours: 8, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, }); }); it('should drop DTEND for all-day events with zero duration', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;VALUE=DATE:20020312 DTEND;VALUE=DATE:20020312 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 3, day: 12 }, parameters: { type: 'date' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, }); }); it('should modify events whose duration is specified to convert that into a dtend', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=America/New_York:20020312T083000 DURATION:PT1H0M0S LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true } }, dtstart: { value: { year: 2002, month: 3, day: 12, hours: 8, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, dtend: { value: { year: 2002, month: 3, day: 12, hours: 9, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, }); }); it('should filter out notifications out of bounds', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=America/New_York:19990312T083000 DTEND;TZID=America/New_York:19990312T093000 BEGIN:VALARM ACTION:DISPLAY TRIGGER:-PT10000M END:VALARM LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 1999, month: 3, day: 12, hours: 8, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 1999, month: 3, day: 12, hours: 9, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, }); }); it('should normalize notifications', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;VALUE=DATE:19990312 DTEND;VALUE=DATE:19990313 BEGIN:VALARM ACTION:DISPLAY TRIGGER;VALUE=DATE-TIME:19960401T005545Z END:VALARM LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 1999, month: 3, day: 12 }, parameters: { type: 'date' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, components: [ { component: 'valarm', action: { value: 'DISPLAY' }, trigger: { value: { weeks: 0, days: 1074, hours: 23, minutes: 4, seconds: 0, isNegative: true, }, }, }, ], }); }); it('should catch inconsistent rrules', () => { const veventNoOccurrenceOnDtstart = `BEGIN:VEVENT DTSTART;TZID=Europe/Vilnius:20200503T150000 DTEND;TZID=Europe/Vilnius:20200503T160000 RRULE:FREQ=MONTHLY;BYDAY=1MO DTSTAMP:20200508T121218Z UID:[email protected] END:VEVENT`; const eventNoOccurrenceOnDtstart = parse(veventNoOccurrenceOnDtstart) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: eventNoOccurrenceOnDtstart, hasXWrTimezone: false, guessTzid: 'Asia/Seoul', }) ).toThrowError('Malformed recurring event'); const veventWithByyeardayNotYearly = `BEGIN:VEVENT DTSTART;TZID=Europe/Vilnius:20200103T150000 RRULE:FREQ=MONTHLY;BYYEARDAY=3 DTSTAMP:20200508T121218Z UID:[email protected] END:VEVENT`; const eventWithByyeardayNotYearly = parse(veventWithByyeardayNotYearly) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: eventWithByyeardayNotYearly, hasXWrTimezone: false, guessTzid: 'Asia/Seoul', }) ).toThrowError('Malformed recurring event'); }); it('should catch malformed rrules', () => { const vevent = `BEGIN:VEVENT DTSTART;TZID=Europe/Vilnius:20200503T150000 DTEND;TZID=Europe/Vilnius:20200503T160000 EXDATE;TZID=Europe/Vilnius:20200503T150000 DTSTAMP:20200508T121218Z UID:[email protected] END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Malformed recurring event'); }); it('should catch inconsistent rrules after reformatting bad untils', () => { const vevent = `BEGIN:VEVENT DTSTART;TZID=Europe/Vilnius:20200503T150000 DTEND;TZID=Europe/Vilnius:20200503T160000 RRULE:FREQ=MONTHLY;BYDAY=1MO;UNTIL=20000101T000000Z DTSTAMP:20200508T121218Z UID:[email protected] END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Malformed recurring event'); }); it('should catch recurring single edits', () => { const vevent = `BEGIN:VEVENT DTSTART;TZID=Europe/Vilnius:20200503T150000 DTEND;TZID=Europe/Vilnius:20200503T160000 RRULE:FREQ=DAILY RECURRENCE-ID;TZID=Europe/Vilnius:20200505T150000 DTSTAMP:20200508T121218Z UID:[email protected] END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Edited event not supported'); }); it('should catch recurring events with no occurrences because of EXDATE', () => { const vevent = `BEGIN:VEVENT DTSTART;TZID=Europe/Warsaw:20130820T145000 DTEND;TZID=Europe/Warsaw:20130820T152000 RRULE:FREQ=DAILY;UNTIL=20130822T125000Z EXDATE;TZID=Europe/Warsaw:20130820T145000 EXDATE;TZID=Europe/Warsaw:20130821T145000 EXDATE;TZID=Europe/Warsaw:20130822T145000 DTSTAMP:20200708T215912Z UID:[email protected] CREATED:20130902T220905Z DESCRIPTION: LAST-MODIFIED:20130902T220905Z LOCATION:Twinpigs - Żory\\, Katowicka 4 SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Scenka: napad na bank TRANSP:OPAQUE END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Recurring event has no occurrences'); }); it('should catch recurring events with no occurrences because of COUNT', () => { const vevent = `BEGIN:VEVENT DTSTART;TZID=Europe/Warsaw:20211020T145000 DTEND;TZID=Europe/Warsaw:20211020T152000 RRULE:FREQ=WEEKLY;COUNT=0 DTSTAMP:20200708T215912Z UID:[email protected] CREATED:20130902T220905Z DESCRIPTION: LAST-MODIFIED:20130902T220905Z LOCATION:Twinpigs - Żory\\, Katowicka 4 SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Scenka: napad na bank TRANSP:OPAQUE END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Recurring event has no occurrences'); }); it('should catch malformed recurring events with no occurrences (throw because of malformed)', () => { const vevent = `BEGIN:VEVENT DTSTART;TZID=Europe/Warsaw:20211020T145000 DTEND;TZID=Europe/Warsaw:20211020T152000 RRULE:FREQ=WEEKLY;WKST=MO;BYDAY=SA;COUNT=0 DTSTAMP:20200708T215912Z UID:[email protected] CREATED:20130902T220905Z DESCRIPTION: LAST-MODIFIED:20130902T220905Z LOCATION:Twinpigs - Żory\\, Katowicka 4 SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Scenka: napad na bank TRANSP:OPAQUE END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Malformed recurring event'); }); it('should catch non-supported rrules', () => { const vevent = `BEGIN:VEVENT DTSTART;TZID=Europe/Vilnius:20200518T150000 DTEND;TZID=Europe/Vilnius:20200518T160000 RRULE:FREQ=MONTHLY;BYDAY=-2MO DTSTAMP:20200508T121218Z UID:[email protected] END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Recurring rule not supported'); }); it('should normalize exdate', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=W. Europe Standard Time:20021230T203000 RRULE:FREQ=DAILY EXDATE;TZID=W. Europe Standard Time:20200610T170000,20200611T170000 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 12, day: 30, hours: 20, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Berlin' }, }, sequence: { value: 0 }, exdate: [ { parameters: { tzid: 'Europe/Berlin', }, value: { day: 10, hours: 17, isUTC: false, minutes: 0, month: 6, seconds: 0, year: 2020, }, }, { parameters: { tzid: 'Europe/Berlin', }, value: { day: 11, hours: 17, isUTC: false, minutes: 0, month: 6, seconds: 0, year: 2020, }, }, ], rrule: { value: { freq: 'DAILY', }, }, }); }); it('should reformat some invalid exdates', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;VALUE=DATE:20021230 RRULE:FREQ=DAILY EXDATE;TZID=W. Europe Standard Time:20200610T170000,20200611T170000 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 12, day: 30 }, parameters: { type: 'date' }, }, sequence: { value: 0 }, exdate: [ { parameters: { type: 'date' }, value: { day: 10, month: 6, year: 2020 }, }, { parameters: { type: 'date' }, value: { day: 11, month: 6, year: 2020 }, }, ], rrule: { value: { freq: 'DAILY' } }, }); }); it('should support unofficial time zones in our database and normalize recurrence-id', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=Mountain Time (U.S. & Canada):20021230T203000 DTEND;TZID=W. Europe Standard Time:20030101T003000 RECURRENCE-ID;TZID=Sarajevo, Skopje, Sofija, Vilnius, Warsaw, Zagreb:20030102T003000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 12, day: 30, hours: 20, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/Denver' }, }, dtend: { value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Berlin' }, }, sequence: { value: 0 }, 'recurrence-id': { value: { year: 2003, month: 1, day: 2, hours: 0, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Sarajevo' }, }, location: { value: '1CP Conference Room 4350' }, }); }); it('should localize Zulu times in the presence of a calendar time zone for non-recurring events', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART:20110613T150000Z DTEND:20110613T160000Z LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: true, calendarTzid: 'Europe/Zurich', guessTzid: 'Asia/Seoul', }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2011, month: 6, day: 13, hours: 17, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, dtend: { value: { year: 2011, month: 6, day: 13, hours: 18, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, sequence: { value: 0 }, location: { value: '1CP Conference Room 4350' }, }); }); it('should not localize Zulu times in the presence of a calendar time zone for recurring events', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART:20110613T150000Z DTEND:20110613T160000Z RECURRENCE-ID:20110618T150000Z LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: true, calendarTzid: 'Europe/Zurich', guessTzid: 'Asia/Seoul', }) ).toEqual({ component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2011, month: 6, day: 13, hours: 15, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2011, month: 6, day: 13, hours: 16, minutes: 0, seconds: 0, isUTC: true }, }, 'recurrence-id': { value: { year: 2011, month: 6, day: 18, hours: 15, minutes: 0, seconds: 0, isUTC: true }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, }); }); it('should localize events with floating times with the guess time zone if no global time zone has been specified', () => { const vevent = ` BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART:20021231T203000 DTEND:20030101T003000 RECURRENCE-ID:20030102T003000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul', }) ).toEqual({ ...event, dtstart: { value: event.dtstart.value, parameters: { tzid: 'Asia/Seoul' } } as VcalDateTimeProperty, dtend: { value: event.dtend!.value, parameters: { tzid: 'Asia/Seoul' } } as VcalDateTimeProperty, 'recurrence-id': { value: event['recurrence-id']!.value, parameters: { tzid: 'Asia/Seoul' }, } as VcalDateTimeProperty, sequence: { value: 0 }, }); }); it(`should reject events with floating times if a non-supported global time zone has been specified`, () => { const vevent = ` BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART:20021231T203000 DTEND:20030101T003000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: true, guessTzid: 'Asia/Seoul' }) ).toThrowError('Calendar time zone not supported'); }); it('should support floating times if a supported global time zone has been specified', () => { const vevent = ` BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART:20021231T203000 DTEND:20030101T003000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const tzid = 'Europe/Brussels'; const event = parse(vevent) as VcalVeventComponent & Required<Pick<VcalVeventComponent, 'dtend'>>; expect( getSupportedEvent({ vcalVeventComponent: event, calendarTzid: tzid, hasXWrTimezone: true, guessTzid: 'Asia/Seoul', }) ).toEqual({ ...event, dtstart: { value: event.dtstart.value, parameters: { tzid } } as VcalDateTimeProperty, dtend: { value: event.dtend.value, parameters: { tzid } } as VcalDateTimeProperty, sequence: { value: 0 }, }); }); it('should ignore global time zone if part-day event time is not floating', () => { const vevent = ` BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=Europe/Vilnius:20200518T150000 DTEND;TZID=Europe/Vilnius:20200518T160000 LOCATION:1CP Conference Room 4350 SEQUENCE:0 END:VEVENT`; const tzid = 'Europe/Brussels'; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, calendarTzid: tzid, hasXWrTimezone: true, guessTzid: 'Asia/Seoul', }) ).toEqual(event); }); it('should ignore global time zone for all-day events', () => { const vevent = ` BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;VALUE=DATE:20200518 DTEND;VALUE=DATE:20200520 LOCATION:1CP Conference Room 4350 SEQUENCE:1 END:VEVENT`; const tzid = 'Europe/Brussels'; const event = parse(vevent) as VcalVeventComponent; expect( getSupportedEvent({ vcalVeventComponent: event, calendarTzid: tzid, hasXWrTimezone: true, guessTzid: 'Asia/Seoul', }) ).toEqual(event); }); it('should not support other time zones not in our list', () => { const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:test-event DTSTART;TZID=Chamorro Standard Time:20021231T203000 DTEND;TZID=Chamorro Standard Time:20030101T003000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(() => getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toThrowError('Time zone not supported'); }); it('should crop long UIDs and truncate titles, descriptions and locations', () => { const loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien et. Ac tincidunt vitae semper quis lectus nulla at volutpat. Egestas congue quisque egestas diam in arcu. Cras adipiscing enim eu turpis. Ullamcorper eget nulla facilisi etiam dignissim diam quis. Vulputate enim nulla aliquet porttitor lacus luctus accumsan tortor posuere. Pulvinar mattis nunc sed blandit libero volutpat sed. Enim nec dui nunc mattis enim ut tellus elementum. Vulputate dignissim suspendisse in est ante in nibh mauris. Malesuada pellentesque elit eget gravida cum. Amet aliquam id diam maecenas ultricies. Aliquam sem fringilla ut morbi tincidunt augue interdum velit. Nec sagittis aliquam malesuada bibendum arcu vitae elementum curabitur. Adipiscing elit duis tristique sollicitudin nibh sit. Pulvinar proin gravida hendrerit lectus. Sit amet justo donec enim diam. Purus sit amet luctus venenatis lectus magna. Iaculis at erat pellentesque adipiscing commodo. Morbi quis commodo odio aenean. Sed cras ornare arcu dui vivamus arcu felis bibendum. Viverra orci sagittis eu volutpat. Tempor orci eu lobortis elementum nibh tellus molestie nunc non. Turpis egestas integer eget aliquet. Venenatis lectus magna fringilla urna porttitor. Neque gravida in fermentum et sollicitudin. Tempor commodo ullamcorper a lacus vestibulum sed arcu non odio. Ac orci phasellus egestas tellus rutrum tellus pellentesque eu. Et magnis dis parturient montes nascetur ridiculus mus mauris. Massa sapien faucibus et molestie ac feugiat sed lectus. Et malesuada fames ac turpis. Tristique nulla aliquet enim tortor at auctor urna. Sit amet luctus venenatis lectus magna fringilla urna porttitor rhoncus. Enim eu turpis egestas pretium aenean pharetra magna ac. Lacus luctus accumsan tortor posuere ac ut. Volutpat ac tincidunt vitae semper quis lectus nulla. Egestas sed sed risus pretium quam vulputate dignissim suspendisse in. Mauris in aliquam sem fringilla ut morbi tincidunt augue interdum. Pharetra et ultrices neque ornare aenean euismod. Vitae aliquet nec ullamcorper sit amet risus nullam eget felis. Egestas congue quisque egestas diam in arcu cursus euismod. Tellus rutrum tellus pellentesque eu. Nunc scelerisque viverra mauris in aliquam sem fringilla ut. Morbi tristique senectus et netus et malesuada fames ac. Risus sed vulputate odio ut enim blandit volutpat. Pellentesque sit amet porttitor eget. Pharetra convallis posuere morbi leo urna molestie at. Tempor commodo ullamcorper a lacus vestibulum sed. Convallis tellus id interdum velit laoreet id donec ultrices. Nec ultrices dui sapien eget mi proin sed libero enim. Sit amet mauris commodo quis imperdiet massa. Sagittis purus sit amet volutpat consequat mauris nunc. Neque aliquam vestibulum morbi blandit cursus risus at ultrices. Id aliquet risus feugiat in ante metus dictum at tempor. Dignissim sodales ut eu sem integer vitae justo. Laoreet sit amet cursus sit. Eget aliquet nibh praesent tristique. Scelerisque varius morbi enim nunc faucibus. In arcu cursus euismod quis viverra nibh. At volutpat diam ut venenatis tellus in. Sodales neque sodales ut etiam sit amet nisl. Turpis in eu mi bibendum neque egestas congue quisque. Eu consequat ac felis donec et odio. Rutrum quisque non tellus orci ac auctor augue mauris augue. Mollis nunc sed id semper risus. Euismod in pellentesque massa placerat duis ultricies lacus sed turpis. Tellus orci ac auctor augue mauris augue neque gravida. Mi sit amet mauris commodo quis imperdiet massa. Ullamcorper velit sed ullamcorper morbi tincidunt ornare massa eget egestas. Ipsum faucibus vitae aliquet nec ullamcorper sit amet. Massa tincidunt dui ut ornare lectus sit.'; const longUID = 'this-is-gonna-be-a-loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong-uid@proton.me'; const croppedUID = longUID.substring(longUID.length - MAX_CHARS_API.UID, longUID.length); const vevent = `BEGIN:VEVENT DTSTAMP:19980309T231000Z UID:this-is-gonna-be-a-loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong-uid@proton.me DTSTART;VALUE=DATE:20080101 DTEND;VALUE=DATE:20080102 SUMMARY:Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien et. Ac tincidunt vitae semper quis lectus nulla at volutpat. Egestas congue quisque egestas diam in arcu. Cras adipiscing enim eu turpis. Ullamcorper eget nulla facilisi etiam dignissim diam quis. Vulputate enim nulla aliquet porttitor lacus luctus accumsan tortor posuere. Pulvinar mattis nunc sed blandit libero volutpat sed. Enim nec dui nunc mattis enim ut tellus elementum. Vulputate dignissim suspendisse in est ante in nibh mauris. Malesuada pellentesque elit eget gravida cum. Amet aliquam id diam maecenas ultricies. Aliquam sem fringilla ut morbi tincidunt augue interdum velit. Nec sagittis aliquam malesuada bibendum arcu vitae elementum curabitur. Adipiscing elit duis tristique sollicitudin nibh sit. Pulvinar proin gravida hendrerit lectus. Sit amet justo donec enim diam. DESCRIPTION:Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien et. Ac tincidunt vitae semper quis lectus nulla at volutpat. Egestas congue quisque egestas diam in arcu. Cras adipiscing enim eu turpis. Ullamcorper eget nulla facilisi etiam dignissim diam quis. Vulputate enim nulla aliquet porttitor lacus luctus accumsan tortor posuere. Pulvinar mattis nunc sed blandit libero volutpat sed. Enim nec dui nunc mattis enim ut tellus elementum. Vulputate dignissim suspendisse in est ante in nibh mauris. Malesuada pellentesque elit eget gravida cum. Amet aliquam id diam maecenas ultricies. Aliquam sem fringilla ut morbi tincidunt augue interdum velit. Nec sagittis aliquam malesuada bibendum arcu vitae elementum curabitur. Adipiscing elit duis tristique sollicitudin nibh sit. Pulvinar proin gravida hendrerit lectus. Sit amet justo donec enim diam. Purus sit amet luctus venenatis lectus magna. Iaculis at erat pellentesque adipiscing commodo. Morbi quis commodo odio aenean. Sed cras ornare arcu dui vivamus arcu felis bibendum. Viverra orci sagittis eu volutpat. Tempor orci eu lobortis elementum nibh tellus molestie nunc non. Turpis egestas integer eget aliquet. Venenatis lectus magna fringilla urna porttitor. Neque gravida in fermentum et sollicitudin. Tempor commodo ullamcorper a lacus vestibulum sed arcu non odio. Ac orci phasellus egestas tellus rutrum tellus pellentesque eu. Et magnis dis parturient montes nascetur ridiculus mus mauris. Massa sapien faucibus et molestie ac feugiat sed lectus. Et malesuada fames ac turpis. Tristique nulla aliquet enim tortor at auctor urna. Sit amet luctus venenatis lectus magna fringilla urna porttitor rhoncus. Enim eu turpis egestas pretium aenean pharetra magna ac. Lacus luctus accumsan tortor posuere ac ut. Volutpat ac tincidunt vitae semper quis lectus nulla. Egestas sed sed risus pretium quam vulputate dignissim suspendisse in. Mauris in aliquam sem fringilla ut morbi tincidunt augue interdum. Pharetra et ultrices neque ornare aenean euismod. Vitae aliquet nec ullamcorper sit amet risus nullam eget felis. Egestas congue quisque egestas diam in arcu cursus euismod. Tellus rutrum tellus pellentesque eu. Nunc scelerisque viverra mauris in aliquam sem fringilla ut. Morbi tristique senectus et netus et malesuada fames ac. Risus sed vulputate odio ut enim blandit volutpat. Pellentesque sit amet porttitor eget. Pharetra convallis posuere morbi leo urna molestie at. Tempor commodo ullamcorper a lacus vestibulum sed. Convallis tellus id interdum velit laoreet id donec ultrices. Nec ultrices dui sapien eget mi proin sed libero enim. Sit amet mauris commodo quis imperdiet massa. Sagittis purus sit amet volutpat consequat mauris nunc. Neque aliquam vestibulum morbi blandit cursus risus at ultrices. Id aliquet risus feugiat in ante metus dictum at tempor. Dignissim sodales ut eu sem integer vitae justo. Laoreet sit amet cursus sit. Eget aliquet nibh praesent tristique. Scelerisque varius morbi enim nunc faucibus. In arcu cursus euismod quis viverra nibh. At volutpat diam ut venenatis tellus in. Sodales neque sodales ut etiam sit amet nisl. Turpis in eu mi bibendum neque egestas congue quisque. Eu consequat ac felis donec et odio. Rutrum quisque non tellus orci ac auctor augue mauris augue. Mollis nunc sed id semper risus. Euismod in pellentesque massa placerat duis ultricies lacus sed turpis. Tellus orci ac auctor augue mauris augue neque gravida. Mi sit amet mauris commodo quis imperdiet massa. Ullamcorper velit sed ullamcorper morbi tincidunt ornare massa eget egestas. Ipsum faucibus vitae aliquet nec ullamcorper sit amet. Massa tincidunt dui ut ornare lectus sit. LOCATION:Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien et. Ac tincidunt vitae semper quis lectus nulla at volutpat. Egestas congue quisque egestas diam in arcu. Cras adipiscing enim eu turpis. Ullamcorper eget nulla facilisi etiam dignissim diam quis. Vulputate enim nulla aliquet porttitor lacus luctus accumsan tortor posuere. Pulvinar mattis nunc sed blandit libero volutpat sed. Enim nec dui nunc mattis enim ut tellus elementum. Vulputate dignissim suspendisse in est ante in nibh mauris. Malesuada pellentesque elit eget gravida cum. Amet aliquam id diam maecenas ultricies. Aliquam sem fringilla ut morbi tincidunt augue interdum velit. Nec sagittis aliquam malesuada bibendum arcu vitae elementum curabitur. Adipiscing elit duis tristique sollicitudin nibh sit. Pulvinar proin gravida hendrerit lectus. Sit amet justo donec enim diam. END:VEVENT`; const event = parse(vevent) as VcalVeventComponent; expect(croppedUID.length === MAX_CHARS_API.UID); expect( getSupportedEvent({ vcalVeventComponent: event, hasXWrTimezone: false, guessTzid: 'Asia/Seoul' }) ).toEqual({ ...omit(event, ['dtend']), uid: { value: croppedUID }, summary: { value: truncate(loremIpsum, MAX_CHARS_API.TITLE) }, location: { value: truncate(loremIpsum, MAX_CHARS_API.LOCATION) }, description: { value: truncate(loremIpsum, MAX_CHARS_API.EVENT_DESCRIPTION) }, sequence: { value: 0 }, }); }); }); describe('extractSupportedEvent', () => { it('should add a uid if the event has none', async () => { const vevent = ` BEGIN:VEVENT DTSTAMP:19980309T231000Z DTSTART;TZID=Europe/Brussels:20021231T203000 DTEND;TZID=Europe/Brussels:20030101T003000 LOCATION:1CP Conference Room 4350 END:VEVENT`; const tzid = 'Europe/Brussels'; const event = parse(vevent) as VcalVeventComponent & Required<Pick<VcalVeventComponent, 'dtend'>>; const supportedEvent = await extractSupportedEvent({ method: ICAL_METHOD.PUBLISH, vcalComponent: event, calendarTzid: tzid, hasXWrTimezone: true, guessTzid: 'Europe/Zurich', }); expect(supportedEvent).toEqual({ component: 'vevent', uid: { value: 'sha1-uid-0ff30d1f26a94abe627d9f715db16714b01be84c' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }, dtend: { value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, }); }); it('should override the uid if the event is an invitation, preserve it in the new uid, and drop recurrence-id', async () => { const vevent = ` BEGIN:VEVENT UID:lalalala DTSTAMP:19980309T231000Z DTSTART;TZID=Europe/Brussels:20021231T203000 DTEND;TZID=Europe/Brussels:20030101T003000 RECURRENCE-ID:20110618T150000Z LOCATION:1CP Conference Room 4350 END:VEVENT`; const tzid = 'Europe/Brussels'; const event = parse(vevent) as VcalVeventComponent & Required<Pick<VcalVeventComponent, 'dtend'>>; const supportedEvent = await extractSupportedEvent({ method: ICAL_METHOD.REQUEST, vcalComponent: event, calendarTzid: tzid, hasXWrTimezone: true, guessTzid: 'Europe/Zurich', }); expect(supportedEvent).toEqual({ component: 'vevent', uid: { value: 'original-uid-lalalala-sha1-uid-d39ba53e577d2eae6ba0baf8539e1fa468fbeabb' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }, dtend: { value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, }); }); it('should drop the recurrence id if we overrode the uid', async () => { const vevent = ` BEGIN:VEVENT DTSTAMP:19980309T231000Z DTSTART;TZID=Europe/Brussels:20021231T203000 DTEND;TZID=Europe/Brussels:20030101T003000 RECURRENCE-ID:20110618T150000Z LOCATION:1CP Conference Room 4350 END:VEVENT`; const tzid = 'Europe/Brussels'; const event = parse(vevent) as VcalVeventComponent & Required<Pick<VcalVeventComponent, 'dtend'>>; const supportedEvent = await extractSupportedEvent({ method: ICAL_METHOD.PUBLISH, vcalComponent: event, calendarTzid: tzid, hasXWrTimezone: true, guessTzid: 'Europe/Zurich', }); expect(supportedEvent).toEqual({ component: 'vevent', uid: { value: 'sha1-uid-ab36432982bccb6dad294500ece330c5829f93ad' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }, dtend: { value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, }); }); it('should fix bad DTSTAMPs', async () => { const vevent = `BEGIN:VEVENT DTSTART;TZID=America/New_York:20221012T171500 DTEND;TZID=America/New_York:20221012T182500 DTSTAMP;TZID=America/New_York:20221007T151646 UID:[email protected] SEQUENCE:0 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent & Required<Pick<VcalVeventComponent, 'dtend'>>; const supportedEvent = await extractSupportedEvent({ method: ICAL_METHOD.PUBLISH, vcalComponent: event, hasXWrTimezone: false, guessTzid: 'Europe/Zurich', }); expect(supportedEvent).toEqual({ component: 'vevent', uid: { value: '[email protected]' }, dtstamp: { value: { year: 2022, month: 10, day: 7, hours: 19, minutes: 16, seconds: 46, isUTC: true }, }, dtstart: { value: { year: 2022, month: 10, day: 12, hours: 17, minutes: 15, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 2022, month: 10, day: 12, hours: 18, minutes: 25, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, sequence: { value: 0 }, }); }); it('should generate DTSTAMP if not present', async () => { const vevent = `BEGIN:VEVENT DTSTART;TZID=America/New_York:20221012T171500 DTEND;TZID=America/New_York:20221012T182500 UID:[email protected] SEQUENCE:0 END:VEVENT`; const event = parse(vevent) as VcalVeventComponent & Required<Pick<VcalVeventComponent, 'dtend'>>; const supportedEvent = await extractSupportedEvent({ method: ICAL_METHOD.PUBLISH, vcalComponent: event, hasXWrTimezone: false, guessTzid: 'Europe/Zurich', }); expect(Object.keys(supportedEvent)).toContain('dtstamp'); }); it('should not import alarms for invitations', async () => { const vevent = `BEGIN:VEVENT UID:test-event DTSTAMP:19980309T231000Z DTSTART;TZID=Europe/Brussels:20021231T203000 DTEND;TZID=Europe/Brussels:20030101T003000 LOCATION:1CP Conference Room 4350 BEGIN:VALARM TRIGGER:-PT15H ACTION:DISPLAY END:VALARM BEGIN:VALARM TRIGGER:-PT1W2D ACTION:EMAIL END:VALARM END:VEVENT`; const tzid = 'Europe/Brussels'; const event = parse(vevent) as VcalVeventComponent & Required<Pick<VcalVeventComponent, 'dtend'>>; const supportedEvent = await extractSupportedEvent({ method: ICAL_METHOD.REQUEST, vcalComponent: event, calendarTzid: tzid, hasXWrTimezone: true, guessTzid: 'Europe/Zurich', }); expect(supportedEvent).toEqual({ component: 'vevent', uid: { value: 'original-uid-test-event-sha1-uid-a9c06d78f4755f736bfd046b3deb3d76f99ab285' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }, dtend: { value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }, location: { value: '1CP Conference Room 4350' }, sequence: { value: 0 }, }); }); it('should serialize event without potential errors to generate hash uid', async () => { // The alarm trigger is invalid in this vevent, so the VALARM component should be removed during event serialization prior to generate hash uid const veventIcs = `BEGIN:VEVENT DESCRIPTION;LANGUAGE=en-US:\n\n\n UID:040000008200E00074C5B7101A82E00800000000B058B6A2A081D901000000000000000 0100000004A031FE80ACD7C418A7A1762749176F121 SUMMARY:Calendar test DTSTART;TZID=Eastern Standard Time:20230513T123000 DTEND;TZID=Eastern Standard Time:20230513T130000 CLASS:PUBLIC PRIORITY:5 DTSTAMP:20230508T153204Z TRANSP:OPAQUE STATUS:CONFIRMED SEQUENCE:0 LOCATION;LANGUAGE=en-US: BEGIN:VALARM DESCRIPTION:REMINDER TRIGGER;RELATED=START:P ACTION:DISPLAY END:VALARM END:VEVENT`; const event = parseWithRecoveryAndMaybeErrors(veventIcs); const supportedEvent = await extractSupportedEvent({ method: ICAL_METHOD.REQUEST, vcalComponent: event, hasXWrTimezone: false, guessTzid: 'America/New_York', }); expect(supportedEvent).toEqual({ component: 'vevent', uid: { value: 'original-uid-040000008200E00074C5B7101A82E00800000000B058B6A2A081D901000000000000000 0100000004A031FE80ACD7C418A7A1762749176F121-sha1-uid-f286aba29df21425cbf3bcec44de9b7fc5e93ce5', }, dtstamp: { value: { year: 2023, month: 5, day: 8, hours: 15, minutes: 32, seconds: 4, isUTC: true }, }, dtstart: { value: { year: 2023, month: 5, day: 13, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, sequence: { value: 0 }, summary: { value: 'Calendar test' }, dtend: { value: { year: 2023, month: 5, day: 13, hours: 13, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, }); }); }); describe('getSupportedEvents', () => { describe('should guess a time zone to localize floating dates', () => { const generateVcalSetup = ( primaryTimezone = 'Asia/Seoul', xWrTimezone = '', vtimezonesTzids: string[] = [] ) => { const xWrTimezoneString = xWrTimezone ? `X-WR-TIMEZONE:${xWrTimezone}` : ''; const vtimezonesString = vtimezonesTzids .map( (tzid) => `BEGIN:VTIMEZONE TZID:${tzid} END:VTIMEZONE` ) .join('\n'); const vcal = `BEGIN:VCALENDAR PRODID:Proton Calendar VERSION:2.0 METHOD:PUBLISH CALSCALE:GREGORIAN ${xWrTimezoneString} ${vtimezonesString} BEGIN:VEVENT UID:test-uid DTSTAMP:19980309T231000Z DTSTART:20021231T203000 DTEND:20030101T003000 SUMMARY:Floating date-time END:VEVENT END:VCALENDAR`; const { components = [], calscale: calscaleProperty, 'x-wr-timezone': xWrTimezoneProperty, method: methodProperty, } = parse(vcal) as VcalVcalendar; return { components, calscale: calscaleProperty?.value, xWrTimezone: xWrTimezoneProperty?.value, method: getIcalMethod(methodProperty) || ICAL_METHOD.PUBLISH, primaryTimezone, }; }; const localizedVevent = (tzid: string) => ({ component: 'vevent', uid: { value: 'test-uid' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid }, }, dtend: { value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid }, }, summary: { value: 'Floating date-time' }, sequence: { value: 0 }, }); it('when there is both x-wr-timezone and single vtimezone (use x-wr-timezone)', async () => { const [supportedEvent] = await getSupportedEvents( generateVcalSetup('Asia/Seoul', 'Europe/Brussels', ['America/New_York']) ); expect(supportedEvent).toEqual(localizedVevent('Europe/Brussels')); }); it('when there is a single vtimezone and no x-wr-timezone', async () => { const [supportedEvent] = await getSupportedEvents(generateVcalSetup('Asia/Seoul', '', ['Europe/Vilnius'])); expect(supportedEvent).toEqual(localizedVevent('Europe/Vilnius')); }); it('when there is a single vtimezone and x-wr-timezone is not supported', async () => { await expectAsync( getSupportedEvents(generateVcalSetup('Asia/Seoul', 'Moon/Tranquility', ['Europe/Vilnius'])) ).toBeResolvedTo([new Error('Calendar time zone not supported')]); }); it('when there is no vtimezone nor x-wr-timezone (fall back to primary time zone)', async () => { const [supportedEvent] = await getSupportedEvents(generateVcalSetup('Asia/Seoul')); expect(supportedEvent).toEqual({ component: 'vevent', uid: { value: 'test-uid' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true, }, }, dtstart: { value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false, }, parameters: { tzid: 'Asia/Seoul' }, }, summary: { value: 'Floating date-time' }, sequence: { value: 0 }, dtend: { value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false, }, parameters: { tzid: 'Asia/Seoul' }, }, }); }); it('when there is no x-wr-timezone and more than one vtimezone (fall back to primary time zone)', async () => { const [supportedEvent] = await getSupportedEvents( generateVcalSetup('Asia/Seoul', '', ['Europe/Vilnius', 'America/New_York']) ); expect(supportedEvent).toEqual({ component: 'vevent', uid: { value: 'test-uid' }, dtstamp: { value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true, }, }, dtstart: { value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false, }, parameters: { tzid: 'Asia/Seoul' }, }, summary: { value: 'Floating date-time' }, sequence: { value: 0 }, dtend: { value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false, }, parameters: { tzid: 'Asia/Seoul' }, }, }); }); }); }); describe('parseIcs', () => { it('should parse an ics with no method or version', async () => { const icsString = `BEGIN:VCALENDAR PRODID:-//github.com/rianjs/ical.net//NONSGML ical.net 4.0//EN BEGIN:VTIMEZONE TZID:UTC X-LIC-LOCATION:UTC BEGIN:STANDARD DTSTART:20200101T000000 RRULE:FREQ=YEARLY;BYDAY=1WE;BYMONTH=1 TZNAME:UTC TZOFFSETFROM:+0000 TZOFFSETTO:+0000 END:STANDARD END:VTIMEZONE BEGIN:VEVENT ATTENDEE;CN=Ham Burger;RSVP=TRUE:mailto:[email protected] CLASS:PUBLIC DESCRIPTION:\\nHi there\\,\\nThis is a very weird description with tabs and \\n\t\t\tline jumps\\n\t\t\ta few\\n\t\t\tjumps\\n\t\t\tyaaay DTEND:20210430T203000 DTSTAMP:20210429T171519Z DTSTART:20210430T183000 ORGANIZER;CN=:mailto:[email protected] SEQUENCE:0 SUMMARY:Another one bites the dust UID:[email protected] BEGIN:VALARM ACTION:DISPLAY DESCRIPTION:Reminder TRIGGER:-PT1H END:VALARM END:VEVENT END:VCALENDAR`; const ics = new File([new Blob([icsString])], 'invite.ics'); const expectedVtimezone = { component: 'vtimezone', components: [ { component: 'standard', dtstart: { value: { year: 2020, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, isUTC: false }, }, rrule: { value: { freq: 'YEARLY', byday: '1WE', bymonth: 1 } }, tzname: [{ value: 'UTC' }], tzoffsetfrom: [{ value: '+00:00' }], tzoffsetto: [{ value: '+00:00' }], }, ], tzid: { value: 'UTC' }, 'x-lic-location': [{ value: 'UTC' }], } as VcalVtimezoneComponent; const expectedVevent = { component: 'vevent', uid: { value: '[email protected]' }, class: { value: 'PUBLIC' }, dtstamp: { value: { year: 2021, month: 4, day: 29, hours: 17, minutes: 15, seconds: 19, isUTC: true }, }, dtstart: { value: { year: 2021, month: 4, day: 30, hours: 18, minutes: 30, seconds: 0, isUTC: false }, }, dtend: { value: { year: 2021, month: 4, day: 30, hours: 20, minutes: 30, seconds: 0, isUTC: false }, }, summary: { value: 'Another one bites the dust', }, description: { value: '\nHi there,\nThis is a very weird description with tabs and \n\t\t\tlinejumps\n\t\t\ta few\n\t\t\tjumps\n\t\t\tyaaay', }, sequence: { value: 0 }, organizer: { value: 'mailto:[email protected]', parameters: { cn: '' }, }, attendee: [ { value: 'mailto:[email protected]', parameters: { cn: 'Ham Burger', rsvp: 'TRUE' }, }, ], components: [ { component: 'valarm', action: { value: 'DISPLAY' }, description: { value: 'Reminder' }, trigger: { value: { weeks: 0, days: 0, hours: 1, minutes: 0, seconds: 0, isNegative: true } }, }, ], }; expect(await parseIcs(ics)).toEqual({ method: ICAL_METHOD.PUBLISH, calscale: ICAL_CALSCALE.GREGORIAN, xWrTimezone: undefined, components: [expectedVtimezone, expectedVevent], }); }); it('should parse an ics with errors in some events', async () => { const icsString = `BEGIN:VCALENDAR PRODID:-//github.com/rianjs/ical.net//NONSGML ical.net 4.0//EN BEGIN:VTIMEZONE TZID:UTC X-LIC-LOCATION:UTC BEGIN:STANDARD DTSTART:20200101T000000 RRULE:FREQ=YEARLY;BYDAY=1WE;BYMONTH=1 TZNAME:UTC TZOFFSETFROM:+0000 TZOFFSETTO:+0000 END:STANDARD END:VTIMEZONE BEGIN:VEVENT ATTENDEE;CN=Ham Burger;RSVP=TRUE:mailto:[email protected] CLASS:PUBLIC DESCRIPTION:\\nHi there\\,\\nThis is a very weird description with tabs and \\n\t\t\tline jumps\\n\t\t\ta few\\n\t\t\tjumps\\n\t\t\tyaaay DTEND:20210430T203000 DTSTAMP:20210429T171519Z DTSTART:20210430T183000 ORGANIZER;CN=:mailto:[email protected] SEQUENCE:0 SUMMARY:Another one bites the dust UID:[email protected] BEGIN:VALARM ACTION:DISPLAY DESCRIPTION:Reminder TRIGGER:-PT1H END:VALARM END:VEVENT BEGIN:VEVENT DESCRIPTION:We can't recover from the bad DTSTART DTSTAMP:20210429T171519Z DTSTART:2021.04.30T18:35:00 SUMMARY:I'm broken UID:[email protected] END:VEVENT END:VCALENDAR`; const ics = new File([new Blob([icsString])], 'invite.ics'); const expectedVtimezone = { component: 'vtimezone', components: [ { component: 'standard', dtstart: { value: { year: 2020, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, isUTC: false }, }, rrule: { value: { freq: 'YEARLY', byday: '1WE', bymonth: 1 } }, tzname: [{ value: 'UTC' }], tzoffsetfrom: [{ value: '+00:00' }], tzoffsetto: [{ value: '+00:00' }], }, ], tzid: { value: 'UTC' }, 'x-lic-location': [{ value: 'UTC' }], } as VcalVtimezoneComponent; const expectedVevent = { component: 'vevent', uid: { value: '[email protected]' }, class: { value: 'PUBLIC' }, dtstamp: { value: { year: 2021, month: 4, day: 29, hours: 17, minutes: 15, seconds: 19, isUTC: true }, }, dtstart: { value: { year: 2021, month: 4, day: 30, hours: 18, minutes: 30, seconds: 0, isUTC: false }, }, dtend: { value: { year: 2021, month: 4, day: 30, hours: 20, minutes: 30, seconds: 0, isUTC: false }, }, summary: { value: 'Another one bites the dust', }, description: { value: '\nHi there,\nThis is a very weird description with tabs and \n\t\t\tlinejumps\n\t\t\ta few\n\t\t\tjumps\n\t\t\tyaaay', }, sequence: { value: 0 }, organizer: { value: 'mailto:[email protected]', parameters: { cn: '' }, }, attendee: [ { value: 'mailto:[email protected]', parameters: { cn: 'Ham Burger', rsvp: 'TRUE' }, }, ], components: [ { component: 'valarm', action: { value: 'DISPLAY' }, description: { value: 'Reminder' }, trigger: { value: { weeks: 0, days: 0, hours: 1, minutes: 0, seconds: 0, isNegative: true } }, }, ], }; const { method, calscale, xWrTimezone, components } = await parseIcs(ics); expect(method).toEqual(ICAL_METHOD.PUBLISH); expect(calscale).toEqual(ICAL_CALSCALE.GREGORIAN); expect(xWrTimezone).toBe(undefined); expect(components[0]).toEqual(expectedVtimezone); expect(components[1]).toEqual(expectedVevent); expect((components[2] as VcalErrorComponent).error).toBeDefined(); expect((components[2] as VcalErrorComponent).icalComponent).toBeDefined(); }); it('should trim calscale and method', async () => { const icsString = `BEGIN:VCALENDAR PRODID:-//Company Inc//Product Application//EN CALSCALE: GREGORIAN VERSION:2.0 METHOD: Publish BEGIN:VEVENT DTSTART:20220530T143000Z DTEND:20220530T153000Z DTSTAMP:20220528T075010Z ORGANIZER;CN=: UID:6c56b58d-488a-41bf-90a2-9b0d555c3780 CREATED:20220528T075010Z X-ALT-DESC;FMTTYPE=text/html: LAST-MODIFIED:20220528T075010Z LOCATION:Sunny danny 8200 Aarhus N SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Optical transform TRANSP:OPAQUE BEGIN:VALARM TRIGGER:-PT30M REPEAT: DURATION:PTM ACTION:DISPLAY DESCRIPTION: END:VALARM END:VEVENT END:VCALENDAR`; const ics = new File([new Blob([icsString])], 'invite.ics'); const parsedIcs = await parseIcs(ics); expect(parsedIcs.calscale).toEqual(ICAL_CALSCALE.GREGORIAN); expect(parsedIcs.method).toEqual(ICAL_METHOD.PUBLISH); }); it('should not recognize unknown calscales', async () => { const icsString = `BEGIN:VCALENDAR PRODID:-//Company Inc//Product Application//EN CALSCALE: GREGORIANO VERSION:2.0 BEGIN:VEVENT DTSTART:20220530T143000Z DTEND:20220530T153000Z DTSTAMP:20220528T075010Z ORGANIZER;CN=: UID:6c56b58d-488a-41bf-90a2-9b0d555c3780 CREATED:20220528T075010Z X-ALT-DESC;FMTTYPE=text/html: LAST-MODIFIED:20220528T075010Z LOCATION:Sunny danny 8200 Aarhus N SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Optical transform TRANSP:OPAQUE BEGIN:VALARM TRIGGER:-PT30M REPEAT: DURATION:PTM ACTION:DISPLAY DESCRIPTION: END:VALARM END:VEVENT END:VCALENDAR`; const ics = new File([new Blob([icsString])], 'invite.ics'); const parsedIcs = await parseIcs(ics); expect(parsedIcs.calscale).toEqual(undefined); }); it('should throw for unknown methods', async () => { const icsString = `BEGIN:VCALENDAR PRODID:-//Company Inc//Product Application//EN VERSION:2.0 METHOD:ATTEND BEGIN:VEVENT DTSTART:20220530T143000Z DTEND:20220530T153000Z DTSTAMP:20220528T075010Z ORGANIZER;CN=: UID:6c56b58d-488a-41bf-90a2-9b0d555c3780 CREATED:20220528T075010Z X-ALT-DESC;FMTTYPE=text/html: LAST-MODIFIED:20220528T075010Z LOCATION:Sunny danny 8200 Aarhus N SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Optical transform TRANSP:OPAQUE BEGIN:VALARM TRIGGER:-PT30M REPEAT: DURATION:PTM ACTION:DISPLAY DESCRIPTION: END:VALARM END:VEVENT END:VCALENDAR`; const ics = new File([new Blob([icsString])], 'invite.ics'); await expectAsync(parseIcs(ics)).toBeRejectedWithError( 'Your file "invite.ics" has an invalid method and cannot be imported.' ); }); });
8,793
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/recurring.spec.js
import { getOccurrences, getOccurrencesBetween } from '../../lib/calendar/recurrence/recurring'; import { parse } from '../../lib/calendar/vcal'; const stringifyResult = (result) => { return result.map(({ utcStart, utcEnd, occurrenceNumber }) => { return `${utcStart.toISOString()} - ${utcEnd.toISOString()} | ${occurrenceNumber}`; }); }; const stringifyResultFull = (result) => { return result.map(({ localStart, localEnd, utcStart, utcEnd, occurrenceNumber }) => { return `${localStart.toISOString()} - ${localEnd.toISOString()} | ${utcStart.toISOString()} - ${utcEnd.toISOString()} | ${occurrenceNumber}`; }); }; const stringifyResultSimple = (result) => { return result.map(({ utcStart, utcEnd }) => { return `${utcStart.toISOString()} - ${utcEnd.toISOString()}`; }); }; const stringifyLocalResultSimple = (result) => { return result.map(({ localStart, occurrenceNumber }) => { return `${localStart.toISOString()} - ${occurrenceNumber}`; }); }; describe('recurring', () => { const component = { dtstart: { value: { year: 2019, month: 1, day: 30, hours: 2, minutes: 30, seconds: 0, isUTC: false }, parameters: { type: 'date-time', tzid: 'Europe/Zurich', }, }, dtend: { value: { year: 2019, month: 1, day: 30, hours: 3, minutes: 30, seconds: 0, isUTC: false }, parameters: { type: 'date-time', tzid: 'Europe/Zurich', }, }, rrule: { value: { freq: 'DAILY', }, }, }; it('should not get occurrences between if it is out of range', () => { const result = getOccurrencesBetween(component, Date.UTC(2018, 3, 1), Date.UTC(2018, 3, 2)); expect(result).toEqual([]); }); it('should get initial occurrences between a range', () => { const result = getOccurrencesBetween(component, Date.UTC(2018, 1, 1), Date.UTC(2019, 1, 3)); expect(stringifyResult(result)).toEqual([ '2019-01-30T01:30:00.000Z - 2019-01-30T02:30:00.000Z | 1', '2019-01-31T01:30:00.000Z - 2019-01-31T02:30:00.000Z | 2', '2019-02-01T01:30:00.000Z - 2019-02-01T02:30:00.000Z | 3', '2019-02-02T01:30:00.000Z - 2019-02-02T02:30:00.000Z | 4', ]); }); it('should get occurrences between a range', () => { const result = getOccurrencesBetween(component, Date.UTC(2019, 2, 1), Date.UTC(2019, 2, 3)); expect(stringifyResult(result)).toEqual([ '2019-03-01T01:30:00.000Z - 2019-03-01T02:30:00.000Z | 31', '2019-03-02T01:30:00.000Z - 2019-03-02T02:30:00.000Z | 32', ]); }); it('should get occurrences between a dst range', () => { const result = getOccurrencesBetween(component, Date.UTC(2019, 9, 26), Date.UTC(2019, 9, 29)); expect(stringifyResultFull(result)).toEqual([ '2019-10-26T02:30:00.000Z - 2019-10-26T03:30:00.000Z | 2019-10-26T00:30:00.000Z - 2019-10-26T01:30:00.000Z | 270', '2019-10-27T02:30:00.000Z - 2019-10-27T03:30:00.000Z | 2019-10-27T01:30:00.000Z - 2019-10-27T02:30:00.000Z | 271', '2019-10-28T02:30:00.000Z - 2019-10-28T03:30:00.000Z | 2019-10-28T01:30:00.000Z - 2019-10-28T02:30:00.000Z | 272', ]); }); it('should get cached occurrences between a range', () => { const cache = {}; const result1 = getOccurrencesBetween(component, Date.UTC(2019, 2, 1), Date.UTC(2019, 2, 3), cache); const result2 = getOccurrencesBetween(component, Date.UTC(2019, 2, 1), Date.UTC(2019, 2, 3), cache); expect(result1).toEqual(result2); }); it('should fill cache if out of range', () => { const cache = {}; getOccurrencesBetween(component, Date.UTC(2019, 2, 1), Date.UTC(2019, 2, 3), cache); const result2 = getOccurrencesBetween(component, Date.UTC(2031, 2, 1), Date.UTC(2031, 2, 3), cache); expect(stringifyResult(result2)).toEqual([ '2031-03-01T01:30:00.000Z - 2031-03-01T02:30:00.000Z | 4414', '2031-03-02T01:30:00.000Z - 2031-03-02T02:30:00.000Z | 4415', ]); }); it('should fill occurrences with a count', () => { const component = parse(` BEGIN:VEVENT DTSTART;VALUE=DATE:20200129 DTEND;VALUE=DATE:20200130 RRULE:FREQ=WEEKLY;BYDAY=SU,MO,TU,WE,TH,FR,SA;COUNT=3 END:VEVENT`); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2020, 2, 1), cache); expect(stringifyResultSimple(result)).toEqual([ '2020-01-29T00:00:00.000Z - 2020-01-29T00:00:00.000Z', '2020-01-30T00:00:00.000Z - 2020-01-30T00:00:00.000Z', '2020-01-31T00:00:00.000Z - 2020-01-31T00:00:00.000Z', ]); }); it('should return no occurrences for a count = 0', () => { const component = parse(` BEGIN:VEVENT DTSTART;VALUE=DATE:20200129 DTEND;VALUE=DATE:20200130 RRULE:FREQ=DAILY;COUNT=0 END:VEVENT`); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2020, 2, 1), cache); expect(stringifyResultSimple(result)).toEqual([]); }); it('should pick a targeted given occurrence ', () => { const component = parse(` BEGIN:VEVENT DTSTART:20200129T113000Z DTEND:20200129T123000Z RRULE:FREQ=WEEKLY;BYDAY=SU,MO,TU,WE,TH,FR,SA;COUNT=3 END:VEVENT`); const cache = {}; const result = getOccurrencesBetween( component, Date.UTC(2020, 0, 29, 11, 30), Date.UTC(2020, 0, 29, 11, 30), cache ); expect(stringifyResultSimple(result)).toEqual(['2020-01-29T11:30:00.000Z - 2020-01-29T12:30:00.000Z']); }); it('should fill occurrences until 31st of Jan in for all day events', () => { const component = parse(` BEGIN:VEVENT DTSTART;VALUE=DATE:20200129 DTEND;VALUE=DATE:20200130 RRULE:FREQ=WEEKLY;BYDAY=SU,MO,TU,WE,TH,FR,SA;UNTIL=20200131 END:VEVENT`); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2020, 2, 1), cache); expect(stringifyResultSimple(result)).toEqual([ '2020-01-29T00:00:00.000Z - 2020-01-29T00:00:00.000Z', '2020-01-30T00:00:00.000Z - 2020-01-30T00:00:00.000Z', '2020-01-31T00:00:00.000Z - 2020-01-31T00:00:00.000Z', ]); }); it('should fill occurrences until 31st of Jan in UTC time', () => { const component = parse(` BEGIN:VEVENT DTSTART:20200129T130000Z DTEND:20200129T133000Z RRULE:FREQ=WEEKLY;BYDAY=SU,MO,TU,WE,TH,FR,SA;UNTIL=20200131T235959Z END:VEVENT`); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2020, 2, 1), cache); expect(stringifyResultSimple(result)).toEqual([ '2020-01-29T13:00:00.000Z - 2020-01-29T13:30:00.000Z', '2020-01-30T13:00:00.000Z - 2020-01-30T13:30:00.000Z', '2020-01-31T13:00:00.000Z - 2020-01-31T13:30:00.000Z', ]); }); it('should fill occurrences until 31st of Jan in Pago Pago time', () => { const component = parse(` BEGIN:VEVENT DTSTART;TZID=Pacific/Pago_Pago:20200129T000000 DTEND;TZID=Europe/Zurich:20200129T133000 RRULE:FREQ=WEEKLY;BYDAY=SU,MO,TU,WE,TH,FR,SA;UNTIL=20200201T105959Z END:VEVENT`); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2020, 2, 1), cache); expect(stringifyResultSimple(result)).toEqual([ '2020-01-29T11:00:00.000Z - 2020-01-29T12:30:00.000Z', '2020-01-30T11:00:00.000Z - 2020-01-30T12:30:00.000Z', '2020-01-31T11:00:00.000Z - 2020-01-31T12:30:00.000Z', ]); }); it('should fill occurrences for an event starting on a sunday', () => { const component = parse(` BEGIN:VEVENT RRULE:FREQ=WEEKLY;COUNT=4;BYDAY=SA,SU DTSTART;VALUE=DATE:20200126 DTEND;VALUE=DATE:20200127 END:VEVENT `); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2021, 2, 1), cache); expect(stringifyResultSimple(result)).toEqual([ '2020-01-26T00:00:00.000Z - 2020-01-26T00:00:00.000Z', '2020-02-01T00:00:00.000Z - 2020-02-01T00:00:00.000Z', '2020-02-02T00:00:00.000Z - 2020-02-02T00:00:00.000Z', '2020-02-08T00:00:00.000Z - 2020-02-08T00:00:00.000Z', ]); }); it('should fill occurrences for an event with an exdate', () => { const component = parse(` BEGIN:VEVENT RRULE:FREQ=DAILY;COUNT=6 DTSTART;TZID=Europe/Zurich:20200309T043000 DTEND;TZID=Europe/Zurich:20200309T063000 EXDATE;TZID=Europe/Zurich:20200311T043000 EXDATE;TZID=Europe/Zurich:20200313T043000 END:VEVENT `); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2021, 4, 1), cache); expect(stringifyResult(result)).toEqual([ '2020-03-09T03:30:00.000Z - 2020-03-09T05:30:00.000Z | 1', '2020-03-10T03:30:00.000Z - 2020-03-10T05:30:00.000Z | 2', '2020-03-12T03:30:00.000Z - 2020-03-12T05:30:00.000Z | 4', '2020-03-14T03:30:00.000Z - 2020-03-14T05:30:00.000Z | 6', ]); }); it('should fill occurrences for an all day event with an exdate', () => { const component = parse(` BEGIN:VEVENT RRULE:FREQ=DAILY;COUNT=6 DTSTART;VALUE=DATE:20200201 DTEND;VALUE=DATE:20200202 EXDATE;VALUE=DATE:20200201 EXDATE;VALUE=DATE:20200202 EXDATE;VALUE=DATE:20200203 END:VEVENT `); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2021, 4, 1), cache); expect(stringifyResultSimple(result)).toEqual([ '2020-02-04T00:00:00.000Z - 2020-02-04T00:00:00.000Z', '2020-02-05T00:00:00.000Z - 2020-02-05T00:00:00.000Z', '2020-02-06T00:00:00.000Z - 2020-02-06T00:00:00.000Z', ]); }); it('should not fill occurrences for an event without rrule', () => { const component = parse(` BEGIN:VEVENT DTSTART:20200201T030000Z DTEND:20200201T040000Z END:VEVENT `); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2021, 4, 1), cache); expect(stringifyResultSimple(result)).toEqual(['2020-02-01T03:00:00.000Z - 2020-02-01T04:00:00.000Z']); }); it('should fill one occurrence without rrule', () => { const component = parse(` BEGIN:VEVENT DTSTART:20200201T030000Z DTEND:20200201T040000Z END:VEVENT `); expect(getOccurrences({ component, maxCount: 0 }).length).toBe(0); expect(getOccurrences({ component, maxCount: 1 }).length).toBe(1); expect(getOccurrences({ component, maxCount: 2 }).length).toBe(1); }); it('should fill no occurrence for rrule with count = 0', () => { const component = parse(` BEGIN:VEVENT DTSTART:20200201T030000Z DTEND:20200201T040000Z RRULE:FREQ=DAILY;COUNT=0 END:VEVENT `); expect(getOccurrences({ component, maxCount: 1 }).length).toBe(0); }); it('should fill occurrences with max start', () => { const component = parse(` BEGIN:VEVENT DTSTART:20200201T030000Z DTEND:20200201T040000Z RRULE:FREQ=DAILY;COUNT=6 END:VEVENT `); expect( stringifyLocalResultSimple( getOccurrences({ component, maxCount: 999, maxStart: new Date(Date.UTC(2020, 1, 4)), }) ) ).toEqual(['2020-02-01T03:00:00.000Z - 1', '2020-02-02T03:00:00.000Z - 2', '2020-02-03T03:00:00.000Z - 3']); }); it('should fill occurrences for a UTC date with an exdate', () => { const component = parse(` BEGIN:VEVENT RRULE:FREQ=DAILY;COUNT=6 DTSTART:20200201T030000Z DTEND:20200201T040000Z EXDATE:20200202T030000Z EXDATE:20200203T030000Z EXDATE:20200204T030000Z END:VEVENT `); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2021, 4, 1), cache); expect(stringifyResultSimple(result)).toEqual([ '2020-02-01T03:00:00.000Z - 2020-02-01T04:00:00.000Z', '2020-02-05T03:00:00.000Z - 2020-02-05T04:00:00.000Z', '2020-02-06T03:00:00.000Z - 2020-02-06T04:00:00.000Z', ]); }); it('should fill occurrences with an end date in another timezone', () => { const component = parse(` BEGIN:VEVENT RRULE:FREQ=DAILY;COUNT=2;INTERVAL=60 DTSTART;TZID=Europe/Zurich:20200901T080000 DTEND:20200901T060000Z END:VEVENT `); const cache = {}; const result = getOccurrencesBetween(component, Date.UTC(2020, 0, 1), Date.UTC(2021, 4, 1), cache); expect(stringifyResultFull(result)).toEqual([ '2020-09-01T08:00:00.000Z - 2020-09-01T06:00:00.000Z | 2020-09-01T06:00:00.000Z - 2020-09-01T06:00:00.000Z | 1', '2020-10-31T08:00:00.000Z - 2020-10-31T07:00:00.000Z | 2020-10-31T07:00:00.000Z - 2020-10-31T07:00:00.000Z | 2', ]); }); });
8,794
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/sanitize.spec.ts
import { restrictedCalendarSanitize } from '../../lib/calendar/sanitize'; describe('sanitize description', () => { it('should drop disallowed tags', () => { expect( restrictedCalendarSanitize( `<div><img src="https://protonmail.com" alt="test"/></span><a href="https://protonmail.com">protonmail</a></div>` ) ).toEqual(`<a href="https://protonmail.com" rel="noopener noreferrer" target="_blank">protonmail</a>`); }); it('should drop disallowed attributes', () => { expect(restrictedCalendarSanitize(`<span style="font-family: sans-serif">text</span>`)).toEqual( `<span>text</span>` ); }); });
8,795
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/serialize.spec.ts
import { CryptoProxy, PublicKeyReference, SessionKey, toPublicKeyReference } from '@proton/crypto'; import { getIsAllDay } from '@proton/shared/lib/calendar/veventHelper'; import { disableRandomMock, initRandomMock } from '@proton/testing/lib/mockRandomValues'; import { ATTENDEE_STATUS_API, EVENT_VERIFICATION_STATUS } from '../../lib/calendar/constants'; import { readCalendarEvent, readSessionKeys } from '../../lib/calendar/deserialize'; import { unwrap, wrap } from '../../lib/calendar/helper'; import { createCalendarEvent } from '../../lib/calendar/serialize'; import { setVcalProdId } from '../../lib/calendar/vcalConfig'; import { toCRLF } from '../../lib/helpers/string'; import { RequireSome } from '../../lib/interfaces'; import { Attendee, CalendarEventData, CreateOrUpdateCalendarEventData, VcalVeventComponent, } from '../../lib/interfaces/calendar'; import { DecryptableKey, DecryptableKey2 } from '../keys/keys.data'; const veventComponent: VcalVeventComponent = { component: 'vevent', components: [ { component: 'valarm', action: { value: 'DISPLAY' }, trigger: { value: { weeks: 0, days: 0, hours: 15, minutes: 0, seconds: 0, isNegative: true }, }, }, ], uid: { value: '123' }, dtstamp: { value: { year: 2019, month: 12, day: 11, hours: 12, minutes: 12, seconds: 12, isUTC: true }, }, dtstart: { value: { year: 2019, month: 12, day: 11, hours: 12, minutes: 12, seconds: 12, isUTC: true }, }, dtend: { value: { year: 2019, month: 12, day: 12, hours: 12, minutes: 12, seconds: 12, isUTC: true }, }, summary: { value: 'my title' }, comment: [{ value: 'asdasd' }], attendee: [ { value: 'mailto:[email protected]', parameters: { cutype: 'INDIVIDUAL', role: 'REQ-PARTICIPANT', rsvp: 'TRUE', partstat: 'NEEDS-ACTION', 'x-pm-token': 'abc', cn: '[email protected]', }, }, { value: 'mailto:[email protected]', parameters: { cutype: 'INDIVIDUAL', role: 'REQ-PARTICIPANT', rsvp: 'TRUE', partstat: 'TENTATIVE', 'x-pm-token': 'bcd', cn: 'Dr No.', }, }, { value: 'mailto:[email protected]', parameters: { cutype: 'INDIVIDUAL', role: 'NON-PARTICIPANT', partstat: 'ACCEPTED', rsvp: 'FALSE', cn: 'Miss Moneypenny', 'x-pm-token': 'cde', }, }, ], }; interface CreateCalendarEventData extends RequireSome< Partial<Omit<CreateOrUpdateCalendarEventData, 'Permissions'>>, | 'SharedEventContent' | 'CalendarEventContent' | 'AttendeesEventContent' | 'SharedKeyPacket' | 'CalendarKeyPacket' > { AddressKeyPacket: string | null; } const transformToExternal = ( data: CreateCalendarEventData, publicAddressKey: PublicKeyReference, isAllDay: boolean, sharedSessionKey?: SessionKey, calendarSessionKey?: SessionKey ) => { const withAuthor = (x: Omit<CalendarEventData, 'Author'>[], author: string): CalendarEventData[] => { return x.map((y) => ({ ...y, Author: author })); }; const withFullAttendee = ( x?: Omit<Attendee, 'UpdateTime' | 'ID'>[], ID = 'dummyID', UpdateTime = 0 ): Attendee[] => { return (x || []).map((y, i) => ({ ...y, ID: `${ID}-${i}`, UpdateTime })); }; return { event: { SharedEvents: withAuthor(data.SharedEventContent, 'me'), CalendarEvents: withAuthor(data.CalendarEventContent, 'me'), AttendeesEvents: withAuthor(data.AttendeesEventContent, 'me'), Attendees: withFullAttendee(data.Attendees), Notifications: data.Notifications, FullDay: +isAllDay, CalendarID: 'calendarID', ID: 'eventID', }, publicKeysMap: { me: [publicAddressKey], }, sharedSessionKey, calendarSessionKey, calendarSettings: { ID: 'settingsID', CalendarID: 'calendarID', DefaultEventDuration: 30, DefaultPartDayNotifications: [], DefaultFullDayNotifications: [], }, addresses: [], }; }; describe('calendar encryption', () => { beforeAll(() => initRandomMock()); afterAll(() => disableRandomMock()); it('should encrypt and sign calendar events', async () => { const dummyProdId = 'Proton Calendar'; setVcalProdId(dummyProdId); const calendarKey = await CryptoProxy.importPrivateKey({ armoredKey: DecryptableKey.PrivateKey, passphrase: '123', }); const addressKey = await CryptoProxy.importPrivateKey({ armoredKey: DecryptableKey2, passphrase: '123' }); // without default notifications expect( await createCalendarEvent({ eventComponent: veventComponent, privateKey: addressKey, publicKey: calendarKey, isCreateEvent: true, isSwitchCalendar: false, hasDefaultNotifications: false, }) ).toEqual({ SharedKeyPacket: 'wV4DatuD4HBmK9ESAQdAh5aMHBZCvQYA9q2Gm4j5LJYj0N/ETwHe/+Icmt09yl8w81ByP+wHwvShTNdKZNv7ziSuGkYloQ9Y2hReRQR0Vdacz4LtBa2T3H17aBbI/rBs', SharedEventContent: [ { Type: 2, Data: wrap( 'BEGIN:VEVENT\r\nUID:123\r\nDTSTAMP:20191211T121212Z\r\nDTSTART:20191211T121212Z\r\nDTEND:20191212T121212Z\r\nEND:VEVENT', dummyProdId ), Signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/), }, { Type: 3, // the following check is just to ensure some stability in the process generating the signatures // i.e. given the same input, we produce the same encrypted data Data: jasmine.stringMatching(/0sADAfKRArUuTJnXofqQYdEjeY\+U6lg.*/g), Signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/g), }, ], CalendarKeyPacket: 'wV4DatuD4HBmK9ESAQdAh5aMHBZCvQYA9q2Gm4j5LJYj0N/ETwHe/+Icmt09yl8w81ByP+wHwvShTNdKZNv7ziSuGkYloQ9Y2hReRQR0Vdacz4LtBa2T3H17aBbI/rBs', CalendarEventContent: [ { Type: 3, // the following check is just to ensure some stability in the process generating the signatures // i.e. given the same input, we produce the same encrypted data Data: jasmine.stringMatching(/0sABAfKRArUuTJnXofqQYdEjeY\+U6lg.*/g), Signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/g), }, ], Notifications: [{ Type: 1, Trigger: '-PT15H' }], AttendeesEventContent: [ { Type: 3, // the following check is just to ensure some stability in the process generating the signatures // i.e. given the same input, we produce the same encrypted data Data: jasmine.stringMatching(/0sE8AfKRArUuTJnXofqQYdEjeY\+U6lh.*/g), Signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/g), }, ], Attendees: [ { Token: 'abc', Status: ATTENDEE_STATUS_API.NEEDS_ACTION }, { Token: 'bcd', Status: ATTENDEE_STATUS_API.TENTATIVE }, { Token: 'cde', Status: ATTENDEE_STATUS_API.ACCEPTED }, ], }); // with default notifications expect( await createCalendarEvent({ eventComponent: veventComponent, privateKey: addressKey, publicKey: calendarKey, isCreateEvent: true, isSwitchCalendar: false, hasDefaultNotifications: true, }) ).toEqual({ SharedKeyPacket: 'wV4DatuD4HBmK9ESAQdAh5aMHBZCvQYA9q2Gm4j5LJYj0N/ETwHe/+Icmt09yl8w81ByP+wHwvShTNdKZNv7ziSuGkYloQ9Y2hReRQR0Vdacz4LtBa2T3H17aBbI/rBs', SharedEventContent: [ { Type: 2, Data: wrap( 'BEGIN:VEVENT\r\nUID:123\r\nDTSTAMP:20191211T121212Z\r\nDTSTART:20191211T121212Z\r\nDTEND:20191212T121212Z\r\nEND:VEVENT', dummyProdId ), Signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/), }, { Type: 3, // the following check is just to ensure some stability in the process generating the signatures // i.e. given the same input, we produce the same encrypted data Data: jasmine.stringMatching(/0sADAfKRArUuTJnXofqQYdEjeY\+U6lg.*/g), Signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/g), }, ], CalendarKeyPacket: 'wV4DatuD4HBmK9ESAQdAh5aMHBZCvQYA9q2Gm4j5LJYj0N/ETwHe/+Icmt09yl8w81ByP+wHwvShTNdKZNv7ziSuGkYloQ9Y2hReRQR0Vdacz4LtBa2T3H17aBbI/rBs', CalendarEventContent: [ { Type: 3, // the following check is just to ensure some stability in the process generating the signatures // i.e. given the same input, we produce the same encrypted data Data: jasmine.stringMatching(/0sABAfKRArUuTJnXofqQYdEjeY\+U6lg.*/g), Signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/g), }, ], Notifications: null, AttendeesEventContent: [ { Type: 3, // the following check is just to ensure some stability in the process generating the signatures // i.e. given the same input, we produce the same encrypted data Data: jasmine.stringMatching(/0sE8AfKRArUuTJnXofqQYdEjeY\+U6lh.*/g), Signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/g), }, ], Attendees: [ { Token: 'abc', Status: ATTENDEE_STATUS_API.NEEDS_ACTION }, { Token: 'bcd', Status: ATTENDEE_STATUS_API.TENTATIVE }, { Token: 'cde', Status: ATTENDEE_STATUS_API.ACCEPTED }, ], }); setVcalProdId(''); }); it('should roundtrip', async () => { const addressKey = await CryptoProxy.importPrivateKey({ armoredKey: DecryptableKey2, passphrase: '123' }); const calendarKey = await CryptoProxy.importPrivateKey({ armoredKey: DecryptableKey.PrivateKey, passphrase: '123', }); const publicKey = await toPublicKeyReference(calendarKey); const publicAddressKey = await toPublicKeyReference(addressKey); const data = (await createCalendarEvent({ eventComponent: veventComponent, privateKey: addressKey, publicKey, isCreateEvent: true, isSwitchCalendar: false, hasDefaultNotifications: false, })) as CreateCalendarEventData; const [sharedSessionKey, calendarSessionKey] = await readSessionKeys({ calendarEvent: data, privateKeys: calendarKey, }); const { veventComponent: decryptedVeventComponent, verificationStatus } = await readCalendarEvent( transformToExternal( data, publicAddressKey, getIsAllDay(veventComponent), sharedSessionKey, calendarSessionKey ) ); expect(decryptedVeventComponent).toEqual(veventComponent); expect(verificationStatus).toEqual(EVENT_VERIFICATION_STATUS.SUCCESSFUL); }); }); describe('wrapping', () => { it('should add wrapping', () => { expect(wrap('asd')).toEqual( toCRLF(`BEGIN:VCALENDAR VERSION:2.0 asd END:VCALENDAR`) ); expect(wrap('asd', 'gfd')).toEqual( toCRLF(`BEGIN:VCALENDAR VERSION:2.0 PRODID:gfd asd END:VCALENDAR`) ); }); it('should remove wrapping', () => { expect(unwrap(wrap('BEGIN:VEVENT asd END:VEVENT', 'gfd'))).toEqual('BEGIN:VEVENT asd END:VEVENT'); }); });
8,796
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/urlify.spec.ts
import urlify from '../../lib/calendar/urlify'; describe('urlify', () => { it('urlifies', () => { const string = `asd https://dog.com ftps://dog.das/asdasd21.31233#asdad?dog=awd file://dog mailto:[email protected]> } ta www.dog.com dog.com <a class="boop" href="dog.com">something else </a> sms:+4444444 tel:+4444444 http://jdfasf.ffasdf A <a href="line.com">line </a> with one https://link1.com and <a href="https://blob.com">another </a> https://link2.com <https://asdasd.adfadf.adfasf> <[email protected]:[email protected]>`; const result = `asd <a href="https://dog.com">https://dog.com</a> <a href="ftps://dog.das/asdasd21.31233#asdad?dog=awd">ftps://dog.das/asdasd21.31233#asdad?dog=awd</a> <a href="file://dog">file://dog</a> <a href="mailto:[email protected]">mailto:[email protected]</a>> } ta www.dog.com dog.com <a class="boop" href="dog.com">something else </a> <a href="sms:+4444444">sms:+4444444</a> <a href="tel:+4444444">tel:+4444444</a> http://jdfasf.ffasdf A <a href="line.com">line </a> with one <a href="https://link1.com">https://link1.com</a> and <a href="https://blob.com">another </a> <a href="https://link2.com">https://link2.com</a> <<a href="https://asdasd.adfadf.adfasf">https://asdasd.adfadf.adfasf</a>> <[email protected].<a href="mailto:[email protected]">mailto:[email protected]</a>>`; expect(urlify(string)).toEqual(result); }); });
8,797
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/valarm.spec.ts
import { getIsValidAlarm, getSupportedAlarm } from '../../lib/calendar/icsSurgery/valarm'; import { VcalDateProperty, VcalValarmComponent } from '../../lib/interfaces/calendar'; describe('getIsValidAlarm', () => { const baseTriggerValue = { weeks: 0, days: 1, hours: 0, minutes: 0, seconds: 0, isNegative: true }; const baseAlarm = { component: 'valarm', action: { value: 'DISPLAY' }, trigger: { value: baseTriggerValue }, } as VcalValarmComponent; it('it reject alarms with unknown action', () => { const alarm = { ...baseAlarm, action: { value: 'WHATEVER' } }; expect(getIsValidAlarm(alarm)).toEqual(false); }); it('it should reject alarms with repeat but no duration', () => { const alarm = { ...baseAlarm, repeat: { value: '1' } }; expect(getIsValidAlarm(alarm)).toEqual(false); }); it('it should reject alarms with a malformed trigger', () => { const alarm = { ...baseAlarm, trigger: { value: { year: 2020, month: 5, day: 2 }, parameters: { type: 'date-time' }, }, } as VcalValarmComponent; expect(getIsValidAlarm(alarm)).toEqual(false); }); }); describe('getSupportedAlarm', () => { const dtstartPartDay = { value: { year: 2020, month: 5, day: 11, hours: 12, minutes: 30, seconds: 0, isUTC: true }, }; const dtstartAllDay = { value: { year: 2020, month: 5, day: 11 }, parameters: { type: 'date' }, } as VcalDateProperty; const baseTriggerValue = { weeks: 0, days: 1, hours: 0, minutes: 0, seconds: 0, isNegative: true }; const baseAlarm = { component: 'valarm', action: { value: 'DISPLAY' }, trigger: { value: baseTriggerValue }, } as VcalValarmComponent; it('it should filter out alarms with trigger related to end time', () => { const alarm = { ...baseAlarm, trigger: { value: { ...baseTriggerValue }, parameters: { related: 'END' }, }, }; expect(getSupportedAlarm(alarm, dtstartPartDay)).toEqual(undefined); }); // Duplicating EMAIL and DISPLAY to ensure both work it('it should filter out attendees, description and summary', () => { const emailAlarm = { ...baseAlarm, action: { value: 'EMAIL' }, description: { value: 'test' }, summary: { value: 'test' }, attendee: [{ value: 'mailto:[email protected]' }], trigger: { value: { ...baseTriggerValue }, }, }; const emailExpected = { ...baseAlarm, action: { value: 'EMAIL' }, trigger: { value: { ...baseTriggerValue }, }, }; const displayAlarm = { ...baseAlarm, action: { value: 'DISPLAY' }, description: { value: 'test' }, summary: { value: 'test' }, attendee: [{ value: 'mailto:[email protected]' }], trigger: { value: { ...baseTriggerValue }, }, }; const displayExpected = { ...baseAlarm, action: { value: 'DISPLAY' }, trigger: { value: { ...baseTriggerValue }, }, }; expect(getSupportedAlarm(emailAlarm, dtstartPartDay)).toEqual(emailExpected); expect(getSupportedAlarm(displayAlarm, dtstartPartDay)).toEqual(displayExpected); }); it('it should filter out future notifications', () => { const alarm = { ...baseAlarm, trigger: { value: { ...baseTriggerValue, isNegative: false }, }, }; expect(getSupportedAlarm(alarm, dtstartPartDay)).toEqual(undefined); expect(getSupportedAlarm(alarm, dtstartAllDay)).toEqual(undefined); }); it('it should normalize triggers for part-day events', () => { const alarms: VcalValarmComponent[] = [ { ...baseAlarm, trigger: { value: { weeks: 0, days: 1, hours: 2, minutes: 1, seconds: 30, isNegative: true }, }, }, { ...baseAlarm, trigger: { value: { year: 2020, month: 4, day: 12, hours: 9, minutes: 30, seconds: 0, isUTC: true }, parameters: { type: 'date-time' }, }, }, ]; const expected = [ { ...baseAlarm, trigger: { value: { weeks: 0, days: 0, hours: 0, minutes: 1561, seconds: 0, isNegative: true }, }, }, { ...baseAlarm, trigger: { value: { weeks: 0, days: 0, hours: 699, minutes: 0, seconds: 0, isNegative: true }, }, }, ]; const results = alarms.map((alarm) => getSupportedAlarm(alarm, dtstartPartDay)); expect(results).toEqual(expected); }); it('it should normalize triggers for all-day events', () => { const alarms: VcalValarmComponent[] = [ { ...baseAlarm, trigger: { value: { weeks: 0, days: 1, hours: 2, minutes: 1, seconds: 30, isNegative: true }, }, }, { ...baseAlarm, trigger: { value: { year: 2020, month: 4, day: 12, hours: 9, minutes: 30, seconds: 0, isUTC: true }, parameters: { type: 'date-time' }, }, }, ]; const expected = [ { ...baseAlarm, trigger: { value: { weeks: 0, days: 1, hours: 2, minutes: 1, seconds: 0, isNegative: true }, }, }, { ...baseAlarm, trigger: { value: { weeks: 0, days: 28, hours: 14, minutes: 30, seconds: 0, isNegative: true }, }, }, ]; const results = alarms.map((alarm) => getSupportedAlarm(alarm, dtstartAllDay)); expect(results).toEqual(expected); }); it('it should filter out notifications out of bounds for part-day events', () => { const alarms: VcalValarmComponent[] = [ { ...baseAlarm, trigger: { value: { weeks: 1000, days: 1, hours: 2, minutes: 1, seconds: 30, isNegative: true }, }, }, { ...baseAlarm, trigger: { value: { year: 1851, month: 4, day: 12, hours: 9, minutes: 30, seconds: 0, isUTC: true }, parameters: { type: 'date-time' }, }, }, ]; const expected = alarms.map(() => undefined); const results = alarms.map((alarm) => getSupportedAlarm(alarm, dtstartPartDay)); expect(results).toEqual(expected); }); it('it should filter out notifications out of bounds for all-day events', () => { const alarms: VcalValarmComponent[] = [ { ...baseAlarm, trigger: { value: { weeks: 1000, days: 1, hours: 2, minutes: 1, seconds: 30, isNegative: true }, }, }, { ...baseAlarm, trigger: { value: { year: 1851, month: 4, day: 12, hours: 9, minutes: 30, seconds: 0, isUTC: true }, parameters: { type: 'date-time' }, }, }, ]; const expected = alarms.map(() => undefined); const results = alarms.map((alarm) => getSupportedAlarm(alarm, dtstartAllDay)); expect(results).toEqual(expected); }); });
8,798
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/vcal.spec.ts
import { fromTriggerString, getMillisecondsFromTriggerString, getVeventWithoutErrors, parse, parseWithRecoveryAndMaybeErrors, serialize, } from '../../lib/calendar/vcal'; import { DAY, HOUR, MINUTE, SECOND, WEEK } from '../../lib/constants'; import { VcalErrorComponent, VcalValarmComponent, VcalVcalendarWithMaybeErrors, VcalVeventComponent, VcalVeventComponentWithMaybeErrors, } from '../../lib/interfaces/calendar'; const vevent = `BEGIN:VEVENT DTSTAMP:20190719T130854Z UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;TZID=America/New_York:20190719T120000 DTEND;TZID=Europe/Zurich:20190719T130000 SEQUENCE:0 CATEGORIES:ANNIVERSARY,PERSONAL,SPECIAL OCCASION SUMMARY:Our Blissful Anniversary END:VEVENT`; const allDayVevent = `BEGIN:VEVENT UID:9E018059-2165-4170-B32F-6936E88E61E5 DTSTART;VALUE=DATE:20190812 DTEND;VALUE=DATE:20190813 SUMMARY:text END:VEVENT`; const veventWithRecurrenceId = `BEGIN:VEVENT UID:9E018059-2165-4170-B32F-6936E88E61E5 RECURRENCE-ID;TZID=Europe/Zurich:20200311T100000 DTSTART;TZID=Europe/Zurich:20200311T100000 DTEND;TZID=Europe/Zurich:20200312T100000 SUMMARY:text END:VEVENT`; const veventWithAttendees = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;VALUE=DATE:20190812 DTEND;VALUE=DATE:20190813 SUMMARY:text ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;RSVP=TRUE;X-PM-TOKEN=123;CN [email protected]:mailto:[email protected] ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;RSVP=TRUE;X-PM-TOKEN=123;CN =Dr No.:mailto:[email protected] ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=NON-PARTICIPANT;RSVP=FALSE;CN=Miss Moneypen ny:mailto:[email protected] END:VEVENT`; const valarm = `BEGIN:VALARM TRIGGER:-PT15H ACTION:DISPLAY DESCRIPTION:asd END:VALARM`; const valarmInVevent = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTAMP:20190719T110000Z DTSTART:20190719T120000Z DTEND:20190719T130000Z BEGIN:VALARM ACTION:DISPLAY TRIGGER:-PT15H END:VALARM END:VEVENT`; const veventRruleDaily1 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART:20190719T120000Z DTEND:20190719T130000Z RRULE:FREQ=DAILY;COUNT=10;INTERVAL=3 END:VEVENT`; const veventRruleDaily2 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;VALUE=DATE:20190719 DTEND;VALUE=DATE:20190719 RRULE:FREQ=DAILY;UNTIL=20200130 END:VEVENT`; const veventRruleDaily3 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART:20190719T120000Z DTEND:20190719T130000Z RRULE:FREQ=DAILY;UNTIL=20200130T225959Z END:VEVENT`; const veventRruleDaily4 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;TZID=America/New_York:20190719T120000 DTEND:20190719T130000Z RRULE:FREQ=DAILY;UNTIL=20200130T225959Z END:VEVENT`; const veventsRruleDaily = [veventRruleDaily1, veventRruleDaily2, veventRruleDaily3, veventRruleDaily4]; const veventRruleWeekly1 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART:20190719T120000Z DTEND:20190719T130000Z RRULE:FREQ=WEEKLY;COUNT=10;INTERVAL=3;BYDAY=WE,TH END:VEVENT`; const veventRruleWeekly2 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;VALUE=DATE:20190719 DTEND;VALUE=DATE:20190719 RRULE:FREQ=WEEKLY;BYDAY=MO;UNTIL=20200130 END:VEVENT`; const veventRruleWeekly3 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART:20190719T120000Z DTEND:20190719T130000Z RRULE:FREQ=WEEKLY;BYDAY=MO;UNTIL=20200130T225959Z END:VEVENT`; const veventRruleWeekly4 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;TZID=America/New_York:20190719T120000 DTEND:20190719T130000Z RRULE:FREQ=WEEKLY;BYDAY=MO;UNTIL=20200130T225959Z END:VEVENT`; const veventsRruleWeekly = [veventRruleWeekly1, veventRruleWeekly2, veventRruleWeekly3, veventRruleWeekly4]; const veventRruleMonthly1 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART:20190719T120000Z DTEND:20190719T130000Z RRULE:FREQ=MONTHLY;INTERVAL=2;BYMONTHDAY=13;UNTIL=20200130T230000Z END:VEVENT`; const veventRruleMonthly2 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART:20190719T120000Z DTEND:20190719T130000Z RRULE:FREQ=MONTHLY;COUNT=4;BYSETPOS=2;BYDAY=TU END:VEVENT`; const veventRruleMonthly3 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;VALUE=DATE:20190719 DTEND;VALUE=DATE:20190719 RRULE:FREQ=MONTHLY;BYSETPOS=-1;BYDAY=MO;UNTIL=20200130 END:VEVENT`; const veventRruleMonthly4 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;TZID=America/New_York:20190719T120000 DTEND:20190719T130000Z RRULE:FREQ=MONTHLY;BYMONTHDAY=2;UNTIL=20200130T225959Z END:VEVENT`; const veventsRruleMonthly = [veventRruleMonthly1, veventRruleMonthly2, veventRruleMonthly3, veventRruleMonthly4]; const veventRruleYearly1 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART:20190719T120000Z DTEND:20190719T130000Z RRULE:FREQ=YEARLY;COUNT=4;BYMONTH=7;BYMONTHDAY=25 END:VEVENT`; const veventRruleYearly2 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;VALUE=DATE:20190719 DTEND;VALUE=DATE:20190719 RRULE:FREQ=YEARLY;INTERVAL=2;UNTIL=20200130 END:VEVENT`; const veventRruleYearly3 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART:20190719T120000Z DTEND:20190719T130000Z RRULE:FREQ=YEARLY;INTERVAL=2;BYMONTH=7;BYMONTHDAY=25;UNTIL=20200130T225959Z END:VEVENT`; const veventRruleYearly4 = `BEGIN:VEVENT UID:7E018059-2165-4170-B32F-6936E88E61E5 DTSTART;TZID=America/New_York:20190719T120000 DTEND:20190719T130000Z RRULE:FREQ=YEARLY;UNTIL=20200130T225959Z END:VEVENT`; const veventsRruleYearly = [veventRruleYearly1, veventRruleYearly2, veventRruleYearly3, veventRruleYearly4]; const vfreebusy = `BEGIN:VFREEBUSY UID:[email protected] ORGANIZER:mailto:[email protected] ATTENDEE:mailto:[email protected] DTSTAMP:19970901T100000Z FREEBUSY:19971015T050000Z/PT8H30M,19971015T160000Z/PT5H30M,19971015T223000Z/PT6H30M URL:http://example.com/pub/busy/jpublic-01.ifb COMMENT:This iCalendar file contains busy time information for the next three months. END:VFREEBUSY`; const vfreebusy2 = `BEGIN:VFREEBUSY UID:[email protected] DTSTAMP:19970901T120000Z ORGANIZER:[email protected] DTSTART:19980313T141711Z DTEND:19980410T141711Z FREEBUSY:19980314T233000Z/19980315T003000Z FREEBUSY:19980316T153000Z/19980316T163000Z FREEBUSY:19980318T030000Z/19980318T040000Z URL:http://www.example.com/calendar/busytime/jsmith.ifb END:VFREEBUSY`; const veventWithTrueBoolean = `BEGIN:VEVENT X-PM-PROTON-REPLY;VALUE=BOOLEAN:TRUE END:VEVENT`; const veventWithFalseBoolean = `BEGIN:VEVENT X-PM-PROTON-REPLY;VALUE=BOOLEAN:FALSE END:VEVENT`; const veventWithRandomBoolean = `BEGIN:VEVENT X-PM-PROTON-REPLY;VALUE=BOOLEAN:GNEEEE END:VEVENT`; const veventWithInvalidVAlarm = ` BEGIN:VEVENT DESCRIPTION;LANGUAGE=en-US:\n\n\n UID:040000008200E00074C5B7101A82E00800000000B058B6A2A081D901000000000000000 0100000004A031FE80ACD7C418A7A1762749176F121 SUMMARY:Calendar test DTSTART;TZID=Eastern Standard Time:20230513T123000 DTEND;TZID=Eastern Standard Time:20230513T130000 CLASS:PUBLIC PRIORITY:5 DTSTAMP:20230508T153204Z TRANSP:OPAQUE STATUS:CONFIRMED SEQUENCE:0 LOCATION;LANGUAGE=en-US: BEGIN:VALARM DESCRIPTION:REMINDER TRIGGER;RELATED=START:P ACTION:DISPLAY END:VALARM END:VEVENT `; describe('calendar', () => { it('should parse vcalendar', () => { const result = parse(`BEGIN:VCALENDAR PRODID:-//Google Inc//Google Calendar 70.9054//EN VERSION:2.0 CALSCALE:GREGORIAN METHOD:PUBLISH X-WR-CALNAME:Daily X-WR-TIMEZONE:Europe/Vilnius END:VCALENDAR`); expect(result).toEqual({ component: 'vcalendar', version: { value: '2.0', }, prodid: { value: '-//Google Inc//Google Calendar 70.9054//EN', }, calscale: { value: 'GREGORIAN', }, method: { value: 'PUBLISH', }, 'x-wr-timezone': { value: 'Europe/Vilnius', }, 'x-wr-calname': { value: 'Daily', }, }); }); it('should parse vevent', () => { const result = parse(vevent); expect(result).toEqual({ component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstamp: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 8, seconds: 54, isUTC: true }, }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, sequence: { value: 0, }, categories: [ { value: ['ANNIVERSARY', 'PERSONAL', 'SPECIAL OCCASION'], }, ], summary: { value: 'Our Blissful Anniversary', }, }); }); it('should parse Boolean properties', () => { expect(parse(veventWithTrueBoolean)).toEqual({ component: 'vevent', 'x-pm-proton-reply': { value: 'true', parameters: { type: 'boolean' } }, }); expect(parse(veventWithFalseBoolean)).toEqual({ component: 'vevent', 'x-pm-proton-reply': { value: 'false', parameters: { type: 'boolean' } }, }); expect(parse(veventWithRandomBoolean)).toEqual({ component: 'vevent', 'x-pm-proton-reply': { value: 'false', parameters: { type: 'boolean' } }, }); }); it('should parse valarm', () => { const result = parse(valarm) as VcalValarmComponent; expect(result).toEqual({ component: 'valarm', trigger: { value: { weeks: 0, days: 0, hours: 15, minutes: 0, seconds: 0, isNegative: true }, }, action: { value: 'DISPLAY', }, description: { value: 'asd', }, }); }); it('should parse vfreebusy2', () => { expect(parse(vfreebusy2)).toEqual({ component: 'vfreebusy', uid: { value: '[email protected]', }, dtstamp: { value: { year: 1997, month: 9, day: 1, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, organizer: { value: '[email protected]', }, dtstart: { value: { year: 1998, month: 3, day: 13, hours: 14, minutes: 17, seconds: 11, isUTC: true, }, }, dtend: { value: { year: 1998, month: 4, day: 10, hours: 14, minutes: 17, seconds: 11, isUTC: true, }, }, freebusy: [ { value: [ { start: { year: 1998, month: 3, day: 14, hours: 23, minutes: 30, seconds: 0, isUTC: true, }, end: { year: 1998, month: 3, day: 15, hours: 0, minutes: 30, seconds: 0, isUTC: true, }, }, ], }, { value: [ { start: { year: 1998, month: 3, day: 16, hours: 15, minutes: 30, seconds: 0, isUTC: true, }, end: { year: 1998, month: 3, day: 16, hours: 16, minutes: 30, seconds: 0, isUTC: true, }, }, ], }, { value: [ { start: { year: 1998, month: 3, day: 18, hours: 3, minutes: 0, seconds: 0, isUTC: true, }, end: { year: 1998, month: 3, day: 18, hours: 4, minutes: 0, seconds: 0, isUTC: true, }, }, ], }, ], url: { value: 'http://www.example.com/calendar/busytime/jsmith.ifb', }, }); }); it('should parse vfreebusy', () => { expect(parse(vfreebusy)).toEqual({ component: 'vfreebusy', uid: { value: '[email protected]', }, dtstamp: { value: { year: 1997, month: 9, day: 1, hours: 10, minutes: 0, seconds: 0, isUTC: true }, }, organizer: { value: 'mailto:[email protected]', }, attendee: [ { value: 'mailto:[email protected]', }, ], freebusy: [ { value: [ { start: { year: 1997, month: 10, day: 15, hours: 5, minutes: 0, seconds: 0, isUTC: true }, duration: { weeks: 0, days: 0, hours: 8, minutes: 30, seconds: 0, isNegative: false }, }, { start: { year: 1997, month: 10, day: 15, hours: 16, minutes: 0, seconds: 0, isUTC: true }, duration: { weeks: 0, days: 0, hours: 5, minutes: 30, seconds: 0, isNegative: false }, }, { start: { year: 1997, month: 10, day: 15, hours: 22, minutes: 30, seconds: 0, isUTC: true }, duration: { weeks: 0, days: 0, hours: 6, minutes: 30, seconds: 0, isNegative: false }, }, ], }, ], comment: [ { value: 'This iCalendar file contains busy time information for the next three months.', }, ], url: { value: 'http://example.com/pub/busy/jpublic-01.ifb', }, }); }); it('should parse all day vevent', () => { const { dtstart } = parse(allDayVevent) as VcalVeventComponent; expect(dtstart).toEqual({ value: { year: 2019, month: 8, day: 12 }, parameters: { type: 'date' }, }); }); it('should parse vevent with recurrence id', () => { const { dtstart, 'recurrence-id': recurrenceId } = parse(veventWithRecurrenceId) as VcalVeventComponent; expect(recurrenceId).toEqual({ value: { year: 2020, month: 3, day: 11, hours: 10, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }); expect(dtstart).toEqual({ value: { year: 2020, month: 3, day: 11, hours: 10, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }); }); it('should parse valarm in vevent', () => { const component = parse(valarmInVevent) as VcalVeventComponent; expect(component).toEqual({ component: 'vevent', components: [ { component: 'valarm', action: { value: 'DISPLAY' }, trigger: { value: { weeks: 0, days: 0, hours: 15, minutes: 0, seconds: 0, isNegative: true }, }, }, ], uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstamp: { value: { year: 2019, month: 7, day: 19, hours: 11, minutes: 0, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, }); }); it('should parse daily rrule in vevent', () => { const components = veventsRruleDaily.map(parse); expect(components).toEqual([ { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'DAILY', count: 10, interval: 3, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2019, month: 7, day: 19 }, parameters: { type: 'date' }, }, rrule: { value: { freq: 'DAILY', until: { year: 2020, month: 1, day: 30 }, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'DAILY', until: { year: 2020, month: 1, day: 30, hours: 22, minutes: 59, seconds: 59, isUTC: true }, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'DAILY', until: { year: 2020, month: 1, day: 30, hours: 22, minutes: 59, seconds: 59, isUTC: true }, }, }, }, ]); }); it('should parse weekly rrule in vevent', () => { const components = veventsRruleWeekly.map(parse); expect(components).toEqual([ { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'WEEKLY', count: 10, interval: 3, byday: ['WE', 'TH'], }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2019, month: 7, day: 19 }, parameters: { type: 'date' }, }, rrule: { value: { freq: 'WEEKLY', byday: 'MO', until: { year: 2020, month: 1, day: 30 }, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'WEEKLY', byday: 'MO', until: { year: 2020, month: 1, day: 30, hours: 22, minutes: 59, seconds: 59, isUTC: true }, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'WEEKLY', byday: 'MO', until: { year: 2020, month: 1, day: 30, hours: 22, minutes: 59, seconds: 59, isUTC: true }, }, }, }, ]); }); it('should parse monthly rrule in vevent', () => { const components = veventsRruleMonthly.map(parse); expect(components).toEqual([ { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'MONTHLY', interval: 2, bymonthday: 13, until: { year: 2020, month: 1, day: 30, hours: 23, minutes: 0, seconds: 0, isUTC: true }, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'MONTHLY', bysetpos: 2, byday: 'TU', count: 4, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2019, month: 7, day: 19 }, parameters: { type: 'date' }, }, rrule: { value: { freq: 'MONTHLY', bysetpos: -1, byday: 'MO', until: { year: 2020, month: 1, day: 30 }, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'MONTHLY', bymonthday: 2, until: { year: 2020, month: 1, day: 30, hours: 22, minutes: 59, seconds: 59, isUTC: true }, }, }, }, ]); }); it('should parse yearly rrule in vevent', () => { const components = veventsRruleYearly.map(parse); expect(components).toEqual([ { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'YEARLY', bymonth: 7, bymonthday: 25, count: 4, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2019, month: 7, day: 19 }, parameters: { type: 'date' }, }, rrule: { value: { freq: 'YEARLY', interval: 2, until: { year: 2020, month: 1, day: 30 }, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'YEARLY', interval: 2, bymonth: 7, bymonthday: 25, until: { year: 2020, month: 1, day: 30, hours: 22, minutes: 59, seconds: 59, isUTC: true }, }, }, }, { component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 13, minutes: 0, seconds: 0, isUTC: true }, }, rrule: { value: { freq: 'YEARLY', until: { year: 2020, month: 1, day: 30, hours: 22, minutes: 59, seconds: 59, isUTC: true }, }, }, }, ]); }); it('should parse attendees in vevent', () => { const component = parse(veventWithAttendees); expect(component).toEqual({ component: 'vevent', uid: { value: '7E018059-2165-4170-B32F-6936E88E61E5', }, dtstart: { value: { year: 2019, month: 8, day: 12 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2019, month: 8, day: 13 }, parameters: { type: 'date' }, }, summary: { value: 'text', }, attendee: [ { value: 'mailto:[email protected]', parameters: { cutype: 'INDIVIDUAL', role: 'REQ-PARTICIPANT', rsvp: 'TRUE', 'x-pm-token': '123', cn: '[email protected]', }, }, { value: 'mailto:[email protected]', parameters: { cutype: 'INDIVIDUAL', role: 'REQ-PARTICIPANT', rsvp: 'TRUE', 'x-pm-token': '123', cn: 'Dr No.', }, }, { value: 'mailto:[email protected]', parameters: { cutype: 'INDIVIDUAL', role: 'NON-PARTICIPANT', rsvp: 'FALSE', cn: 'Miss Moneypenny', }, }, ], }); }); const trimAll = (str: string) => str.replace(/\r?\n ?|\r/g, ''); it('should round trip valarm in vevent', () => { const result = serialize(parse(valarmInVevent)); expect(trimAll(result)).toEqual(trimAll(valarmInVevent)); }); it('should round trip vfreebusy', () => { const result = serialize(parse(vfreebusy)); expect(trimAll(result)).toEqual(trimAll(vfreebusy)); }); it('should round trip vfreebusy2', () => { const result = serialize(parse(vfreebusy2)); expect(trimAll(result)).toEqual(trimAll(vfreebusy2)); }); it('should round trip rrule in vevent', () => { const vevents = [...veventsRruleDaily, ...veventsRruleWeekly, ...veventsRruleMonthly, ...veventsRruleYearly]; const results = vevents.map((vevent) => serialize(parse(vevent))); expect(results.map(trimAll)).toEqual(vevents.map(trimAll)); }); it('should round trip vevent', () => { const result = serialize(parse(vevent)); expect(trimAll(result)).toEqual(trimAll(vevent)); }); it('should round trip vevent with recurrence-id', () => { const result = serialize(parse(veventWithRecurrenceId)); expect(trimAll(result)).toEqual(trimAll(veventWithRecurrenceId)); }); it('should round trip vevent with attendees', () => { const result = serialize(parse(veventWithAttendees)); expect(trimAll(result)).toEqual(trimAll(veventWithAttendees)); }); it('should round trip all day vevent', () => { const result = serialize(parse(allDayVevent)); expect(trimAll(result)).toEqual(trimAll(allDayVevent)); }); it('should normalize exdate', () => { const veventWithExdate = `BEGIN:VEVENT RRULE:FREQ=DAILY;COUNT=6 DTSTART;TZID=Europe/Zurich:20200309T043000 DTEND;TZID=Europe/Zurich:20200309T063000 EXDATE:19960402T010000Z,19960403T010000Z,19960404T010000Z EXDATE;TZID=Europe/Zurich:20200311T043000 EXDATE;TZID=Europe/Zurich:20200313T043000 EXDATE;VALUE=DATE:20200311 END:VEVENT `; const normalizedVevent = `BEGIN:VEVENT RRULE:FREQ=DAILY;COUNT=6 DTSTART;TZID=Europe/Zurich:20200309T043000 DTEND;TZID=Europe/Zurich:20200309T063000 EXDATE:19960402T010000Z EXDATE:19960403T010000Z EXDATE:19960404T010000Z EXDATE;TZID=Europe/Zurich:20200311T043000 EXDATE;TZID=Europe/Zurich:20200313T043000 EXDATE;VALUE=DATE:20200311 END:VEVENT`; const result = serialize(parse(veventWithExdate)); expect(trimAll(result)).toEqual(trimAll(normalizedVevent)); }); it('should parse trigger string', () => { expect(fromTriggerString('-PT30M')).toEqual({ weeks: 0, days: 0, hours: 0, minutes: 30, seconds: 0, isNegative: true, }); }); it('should convert trigger strings into milliseconds', () => { expect(getMillisecondsFromTriggerString('-PT30M')).toEqual(-30 * MINUTE); expect(getMillisecondsFromTriggerString('PT1H')).toEqual(HOUR); expect(getMillisecondsFromTriggerString('-P1D')).toEqual(-DAY); expect(getMillisecondsFromTriggerString('-PT2H34M12S')).toEqual(-2 * HOUR - 34 * MINUTE - 12 * SECOND); expect(getMillisecondsFromTriggerString('P2W1DT1S')).toEqual(2 * WEEK + DAY + SECOND); }); it('should filter out invalid vAlarm', () => { const parsed = parseWithRecoveryAndMaybeErrors(veventWithInvalidVAlarm) as VcalVeventComponentWithMaybeErrors; expect(getVeventWithoutErrors(parsed)).toEqual({ component: 'vevent', components: [], description: { value: '', parameters: { language: 'en-US' } }, uid: { value: '040000008200E00074C5B7101A82E00800000000B058B6A2A081D901000000000000000 0100000004A031FE80ACD7C418A7A1762749176F121', }, summary: { value: 'Calendar test', }, dtstart: { value: { year: 2023, month: 5, day: 13, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Eastern Standard Time' }, }, dtend: { value: { year: 2023, month: 5, day: 13, hours: 13, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Eastern Standard Time', }, }, class: { value: 'PUBLIC' }, priority: { value: 5 }, dtstamp: { value: { year: 2023, month: 5, day: 8, hours: 15, minutes: 32, seconds: 4, isUTC: true }, }, transp: { value: 'OPAQUE' }, status: { value: 'CONFIRMED' }, sequence: { value: 0 }, location: { value: '', parameters: { language: 'en-US' } }, }); }); }); describe('parseWithRecoveryAndMaybeErrors', () => { it('should catch errors from badly formatted all-day dates (with recovery for those off)', () => { const ics = `BEGIN:VCALENDAR BEGIN:VEVENT UID:test-uid DTSTAMP:20200405T143241Z DTSTART:20200309 END:VEVENT END:VCALENDAR`; const result = parseWithRecoveryAndMaybeErrors(ics, { retryDateTimes: false }) as VcalVcalendarWithMaybeErrors; expect(result.component).toEqual('vcalendar'); expect((result.components as VcalErrorComponent[])[0].error).toMatch('invalid date-time value'); }); it('should catch errors from badly formatted date-times (with recovery for those off)', () => { const ics = `BEGIN:VCALENDAR X-LOTUS-CHARSET:UTF-8 VERSION:2.0 PRODID:http://www.bahn.de METHOD:PUBLISH BEGIN:VEVENT UID:bahn2023-06-21082400 CLASS:PUBLIC SUMMARY:Hamburg Hbf -> Paris Est DTSTART;TZID=Europe/Berlin:2023-06-21T082400 DTEND;TZID=Europe/Berlin:2023-06-21T165400 DTSTAMP:2023-06-13T212500Z END:VEVENT END:VCALENDAR`; const result = parseWithRecoveryAndMaybeErrors(ics, { retryDateTimes: false }) as VcalVcalendarWithMaybeErrors; expect(result.component).toEqual('vcalendar'); expect((result.components as VcalErrorComponent[])[0].error).toMatch('invalid date-time value'); }); it('should catch errors from badly formatted dates (with recovery for those off)', () => { const ics = `BEGIN:VCALENDAR X-LOTUS-CHARSET:UTF-8 VERSION:2.0 PRODID:http://www.bahn.de METHOD:PUBLISH BEGIN:VEVENT UID:bahn2023-06-21082400 CLASS:PUBLIC SUMMARY:Hamburg Hbf -> Paris Est DTSTART;VALUE=DATE:2023-06-21 DTEND;VALUE=DATE:2023-06-21 DTSTAMP:20230613T212500Z END:VEVENT END:VCALENDAR`; const result = parseWithRecoveryAndMaybeErrors(ics, { retryDateTimes: false }) as VcalVcalendarWithMaybeErrors; expect(result.component).toEqual('vcalendar'); expect((result.components as VcalErrorComponent[])[0].error).toMatch('could not extract integer'); }); });
8,799