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/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/vcalConverter.spec.js
import { dateTimeToProperty, dayToNumericDay, getDateTimePropertyInDifferentTimezone, getHasModifiedDateTimes, numericDayToDay, propertyToLocalDate, propertyToUTCDate, } from '../../lib/calendar/vcalConverter'; describe('propertyToUTCDate', () => { it('should convert all-day properties to UTC end-of-day times', () => { const property = { value: { year: 2021, month: 7, day: 7 }, parameters: { type: 'date' }, }; expect(+propertyToUTCDate(property)).toEqual(Date.UTC(2021, 6, 7)); }); it('should convert Zulu date-time properties', () => { const property = { value: { year: 2021, month: 7, day: 7, hours: 7, minutes: 7, seconds: 7, isUTC: true }, }; expect(+propertyToUTCDate(property)).toEqual(Date.UTC(2021, 6, 7, 7, 7, 7)); }); it('should convert floating date-time properties to Zulu time', () => { const property = { value: { year: 2021, month: 7, day: 7, hours: 7, minutes: 7, seconds: 7, isUTC: false }, }; expect(+propertyToUTCDate(property)).toEqual(Date.UTC(2021, 6, 7, 7, 7, 7)); }); it('should convert localized date-time properties', () => { const property = { value: { year: 2021, month: 7, day: 7, hours: 7, minutes: 7, seconds: 7, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }; expect(+propertyToUTCDate(property)).toEqual(Date.UTC(2021, 6, 7, 5, 7, 7)); }); }); describe('propertyToLocalDate', () => { it('should convert all-day properties to local end-of-day times', () => { const property = { value: { year: 2021, month: 7, day: 7 }, parameters: { type: 'date' }, }; expect(+propertyToLocalDate(property)).toEqual(+new Date(2021, 6, 7)); }); it('should convert Zulu date-time properties', () => { const property = { value: { year: 2021, month: 7, day: 7, hours: 7, minutes: 7, seconds: 7, isUTC: true }, }; expect(+propertyToLocalDate(property)).toEqual(Date.UTC(2021, 6, 7, 7, 7, 7)); }); it('should convert floating date-time properties to Zulu time', () => { const property = { value: { year: 2021, month: 7, day: 7, hours: 7, minutes: 7, seconds: 7, isUTC: false }, }; expect(+propertyToLocalDate(property)).toEqual(Date.UTC(2021, 6, 7, 7, 7, 7)); }); it('should convert localized date-time properties', () => { const property = { value: { year: 2021, month: 7, day: 7, hours: 7, minutes: 7, seconds: 7, isUTC: false }, parameters: { tzid: 'Europe/Brussels' }, }; expect(+propertyToLocalDate(property)).toEqual(Date.UTC(2021, 6, 7, 5, 7, 7)); }); }); describe('dateTimeToProperty', () => { it('should convert a date with a timezone into a property', () => { const property = dateTimeToProperty( { year: 2019, month: 10, day: 1, hours: 1, minutes: 13, }, false, 'Etc/UTC' ); expect(property).toEqual({ value: { year: 2019, month: 10, day: 1, hours: 1, minutes: 13, seconds: 0, isUTC: false }, parameters: { tzid: 'Etc/UTC', }, }); }); it('should convert utc time', () => { const property = dateTimeToProperty( { year: 2019, month: 10, day: 1, hours: 1, minutes: 13, }, true ); expect(property).toEqual({ value: { year: 2019, month: 10, day: 1, hours: 1, minutes: 13, seconds: 0, isUTC: true }, }); }); }); describe('day converter', () => { it('should convert from number to day', () => { expect(numericDayToDay(-3)).toEqual('TH'); expect(numericDayToDay(-2)).toEqual('FR'); expect(numericDayToDay(-1)).toEqual('SA'); expect(numericDayToDay(0)).toEqual('SU'); expect(numericDayToDay(1)).toEqual('MO'); expect(numericDayToDay(2)).toEqual('TU'); expect(numericDayToDay(3)).toEqual('WE'); }); it('should convert from day to number', () => { expect(dayToNumericDay('SU')).toEqual(0); expect(dayToNumericDay('MO')).toEqual(1); expect(dayToNumericDay('TU')).toEqual(2); expect(dayToNumericDay('WE')).toEqual(3); expect(dayToNumericDay('TH')).toEqual(4); expect(dayToNumericDay('FR')).toEqual(5); expect(dayToNumericDay('SA')).toEqual(6); expect(dayToNumericDay('su')).toBeUndefined(); expect(dayToNumericDay('asd')).toBeUndefined(); }); }); describe('getDateTimePropertyInDifferentTimezone', () => { const tzid = 'Pacific/Honolulu'; it('should not modify all-day properties', () => { const property = { value: { year: 2020, month: 4, day: 23 }, parameters: { type: 'date' }, }; expect(getDateTimePropertyInDifferentTimezone(property, tzid)).toEqual(property); expect(getDateTimePropertyInDifferentTimezone(property, tzid, true)).toEqual(property); }); it('should change the timezone of UTC dates', () => { const property = { value: { year: 2020, month: 4, day: 23, hours: 12, minutes: 30, seconds: 0, isUTC: true }, }; const expected = { value: { year: 2020, month: 4, day: 23, hours: 2, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid }, }; expect(getDateTimePropertyInDifferentTimezone(property, tzid)).toEqual(expected); }); it('should change the timezone of timezoned dates', () => { const property = { value: { year: 2020, month: 4, day: 23, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }; const expected = { value: { year: 2020, month: 4, day: 23, hours: 0, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid }, }; expect(getDateTimePropertyInDifferentTimezone(property, tzid)).toEqual(expected); }); it('should return simplified form of UTC dates', () => { const property = { value: { year: 2020, month: 4, day: 23, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }; const expected = { value: { year: 2020, month: 4, day: 23, hours: 10, minutes: 30, seconds: 0, isUTC: true }, }; expect(getDateTimePropertyInDifferentTimezone(property, 'UTC')).toEqual(expected); }); }); describe('getHasModifiedDateTimes', () => { it('should detect same times as equal for part-day events', () => { const vevent1 = { dtstart: { value: { year: 2020, month: 4, day: 23, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, dtend: { value: { year: 2020, month: 4, day: 23, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, }; const vevent2 = { dtstart: { value: { year: 2020, month: 4, day: 23, hours: 11, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/London' }, }, }; expect(getHasModifiedDateTimes(vevent1, vevent2)).toEqual(false); }); it('should detect same times as equal for all-day events', () => { const vevent1 = { dtstart: { value: { year: 2020, month: 4, day: 23 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 4, day: 24 }, parameters: { type: 'date' }, }, }; const vevent2 = { dtstart: { value: { year: 2020, month: 4, day: 23 }, parameters: { type: 'date' }, }, }; expect(getHasModifiedDateTimes(vevent1, vevent2)).toEqual(false); }); it('should detect different start times as different for part-day events', () => { const vevent1 = { dtstart: { value: { year: 2020, month: 4, day: 23, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, dtend: { value: { year: 2020, month: 4, day: 23, hours: 13, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, }; const vevent2 = { dtstart: { value: { year: 2020, month: 4, day: 23, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/London' }, }, dtend: { value: { year: 2020, month: 4, day: 23, hours: 13, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, }; expect(getHasModifiedDateTimes(vevent1, vevent2)).toEqual(true); }); it('should detect different end times as different for all-day events', () => { const vevent1 = { dtstart: { value: { year: 2020, month: 4, day: 23, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, dtend: { value: { year: 2020, month: 4, day: 23, hours: 12, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, }; const vevent2 = { dtstart: { value: { year: 2020, month: 4, day: 23, hours: 11, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/London' }, }, dtend: { value: { year: 2020, month: 4, day: 23, hours: 13, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, }; expect(getHasModifiedDateTimes(vevent1, vevent2)).toEqual(true); }); it('should detect different start times as different for all-day events', () => { const vevent1 = { dtstart: { value: { year: 2020, month: 4, day: 21 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 4, day: 24 }, parameters: { type: 'date' }, }, }; const vevent2 = { dtstart: { value: { year: 2020, month: 4, day: 22 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 4, day: 24 }, parameters: { type: 'date' }, }, }; expect(getHasModifiedDateTimes(vevent1, vevent2)).toEqual(true); }); it('should detect different end times as different for all-day events', () => { const vevent1 = { dtstart: { value: { year: 2020, month: 4, day: 21 }, parameters: { type: 'date' }, }, }; const vevent2 = { dtstart: { value: { year: 2020, month: 4, day: 21 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 4, day: 24 }, parameters: { type: 'date' }, }, }; expect(getHasModifiedDateTimes(vevent1, vevent2)).toEqual(true); }); });
8,800
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/veventHelper.spec.ts
import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar'; import { CALENDAR_CARD_TYPE } from '../../lib/calendar/constants'; import { parse } from '../../lib/calendar/vcal'; import { getVeventParts, withMandatoryPublishFields, withoutRedundantDtEnd } from '../../lib/calendar/veventHelper'; import { toCRLF } from '../../lib/helpers/string'; const { ENCRYPTED_AND_SIGNED, SIGNED, CLEAR_TEXT } = CALENDAR_CARD_TYPE; describe('getVeventParts()', () => { it('should split shared parts', () => { const y = parse(`BEGIN:VEVENT UID:abc DTSTART;TZID=Europe/Zurich:20200311T100000 DTEND;TZID=Europe/Zurich:20200312T100000 DESCRIPTION:bca SUMMARY:dcf SEQUENCE:2 LOCATION:asd END:VEVENT `) as VcalVeventComponent; const result = getVeventParts(y); expect(result).toEqual({ sharedPart: { [SIGNED]: toCRLF(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:abc DTSTART;TZID=Europe/Zurich:20200311T100000 DTEND;TZID=Europe/Zurich:20200312T100000 SEQUENCE:2 END:VEVENT END:VCALENDAR`), [ENCRYPTED_AND_SIGNED]: toCRLF(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:abc DESCRIPTION:bca SUMMARY:dcf LOCATION:asd END:VEVENT END:VCALENDAR`), }, calendarPart: { [SIGNED]: undefined, [ENCRYPTED_AND_SIGNED]: undefined }, personalPart: { [SIGNED]: undefined, [ENCRYPTED_AND_SIGNED]: undefined }, attendeesPart: { [CLEAR_TEXT]: [], [SIGNED]: undefined, [ENCRYPTED_AND_SIGNED]: undefined }, notificationsPart: [], }); }); it('should split shared, calendar, and personal parts', () => { const y = parse(`BEGIN:VEVENT UID:abc DTSTART;TZID=Europe/Zurich:20200311T100000 DTEND;TZID=Europe/Zurich:20200312T100000 STATUS:TENTATIVE COMMENT:my comment DESCRIPTION:bca TRANSP:TRANSPARENT SUMMARY:dcf LOCATION:asd SEQUENCE:1 BEGIN:VALARM UID:abc TRIGGER:-PT15H ACTION:DISPLAY DESCRIPTION:asd END:VALARM END:VEVENT `) as VcalVeventComponent; const result = getVeventParts(y); expect(result).toEqual({ sharedPart: { [SIGNED]: toCRLF(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:abc DTSTART;TZID=Europe/Zurich:20200311T100000 DTEND;TZID=Europe/Zurich:20200312T100000 SEQUENCE:1 END:VEVENT END:VCALENDAR`), [ENCRYPTED_AND_SIGNED]: toCRLF(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:abc DESCRIPTION:bca SUMMARY:dcf LOCATION:asd END:VEVENT END:VCALENDAR`), }, calendarPart: { [SIGNED]: toCRLF(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:abc STATUS:TENTATIVE TRANSP:TRANSPARENT END:VEVENT END:VCALENDAR`), [ENCRYPTED_AND_SIGNED]: toCRLF(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:abc COMMENT:my comment END:VEVENT END:VCALENDAR`), }, personalPart: { [SIGNED]: toCRLF(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:abc BEGIN:VALARM UID:abc TRIGGER:-PT15H ACTION:DISPLAY DESCRIPTION:asd END:VALARM END:VEVENT END:VCALENDAR`), [ENCRYPTED_AND_SIGNED]: undefined, }, attendeesPart: { [CLEAR_TEXT]: [], [SIGNED]: undefined, [ENCRYPTED_AND_SIGNED]: undefined }, notificationsPart: [{ Type: 1, Trigger: '-PT15H' }], }); }); }); describe('withMandatoryPublishFields()', () => { it('should add description for display alarms, and description, summary and attendee for email ones', () => { const vevent = parse(`BEGIN:VEVENT UID:abc DTSTART;TZID=Europe/Zurich:20200311T100000 DTSTAMP:20200308T134254Z STATUS:TENTATIVE COMMENT:my comment DESCRIPTION:bca TRANSP:TRANSPARENT SUMMARY:dcf LOCATION:asd SEQUENCE:1 BEGIN:VALARM TRIGGER:-PT15M ACTION:DISPLAY END:VALARM BEGIN:VALARM TRIGGER:PT15H ACTION:DISPLAY END:VALARM BEGIN:VALARM TRIGGER:-PT1W2D ACTION:EMAIL END:VALARM END:VEVENT `) as VcalVeventComponent; const expected: VcalVeventComponent = { component: 'vevent', uid: { value: 'abc' }, dtstart: { value: { year: 2020, month: 3, day: 11, hours: 10, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, dtstamp: { value: { year: 2020, month: 3, day: 8, hours: 13, minutes: 42, seconds: 54, isUTC: true }, }, status: { value: 'TENTATIVE' }, comment: [{ value: 'my comment' }], description: { value: 'bca' }, transp: { value: 'TRANSPARENT' }, summary: { value: 'dcf' }, location: { value: 'asd' }, sequence: { value: 1 }, components: [ { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { days: 0, hours: 0, isNegative: true, minutes: 15, seconds: 0, weeks: 0, }, }, description: { value: 'dcf' }, }, { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { days: 0, hours: 15, isNegative: false, minutes: 0, seconds: 0, weeks: 0, }, }, description: { value: 'dcf' }, }, { component: 'valarm', action: { value: 'EMAIL', }, trigger: { value: { days: 2, hours: 0, isNegative: true, minutes: 0, seconds: 0, weeks: 1, }, }, summary: { value: 'dcf' }, description: { value: 'dcf' }, attendee: [{ value: 'mailto:[email protected]' }], }, ], }; expect(withMandatoryPublishFields(vevent, '[email protected]')).toEqual(expected); }); it('should add a null summary if the event has no title', () => { const vevent = parse(`BEGIN:VEVENT UID:abc DTSTART;TZID=Europe/Zurich:20200311T100000 DTSTAMP:20200308T134254Z BEGIN:VALARM TRIGGER:-PT15M ACTION:DISPLAY END:VALARM BEGIN:VALARM TRIGGER:-PT1W2D ACTION:EMAIL END:VALARM END:VEVENT `) as VcalVeventComponent; const expected: VcalVeventComponent = { component: 'vevent', uid: { value: 'abc' }, dtstart: { value: { year: 2020, month: 3, day: 11, hours: 10, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, dtstamp: { value: { year: 2020, month: 3, day: 8, hours: 13, minutes: 42, seconds: 54, isUTC: true }, }, summary: { value: '' }, components: [ { component: 'valarm', action: { value: 'DISPLAY', }, trigger: { value: { days: 0, hours: 0, isNegative: true, minutes: 15, seconds: 0, weeks: 0, }, }, description: { value: '(no title)' }, }, { component: 'valarm', action: { value: 'EMAIL', }, trigger: { value: { days: 2, hours: 0, isNegative: true, minutes: 0, seconds: 0, weeks: 1, }, }, summary: { value: '(no title)' }, description: { value: '(no title)' }, attendee: [{ value: 'mailto:[email protected]' }], }, ], }; expect(withMandatoryPublishFields(vevent, '[email protected]')).toEqual(expected); }); }); describe('withoutRedundantDtEnd', () => { describe('full day', () => { it('should remove redundant dtend', () => { const ALL_DAY_COMPONENT = parse(`BEGIN:VEVENT UID:abc DTSTAMP:20230614T101702Z DTSTART;VALUE=DATE:20190812 DTEND;VALUE=DATE:20190813 SUMMARY:text RRULE:FREQ=DAILY END:VEVENT`) as VcalVeventComponent; expect(withoutRedundantDtEnd(ALL_DAY_COMPONENT)).toEqual({ component: 'vevent', uid: { value: 'abc' }, dtstart: { value: { year: 2019, month: 8, day: 12 }, parameters: { type: 'date' } }, dtstamp: { value: { year: 2023, month: 6, day: 14, hours: 10, minutes: 17, seconds: 2, isUTC: true } }, summary: { value: 'text' }, rrule: { value: { freq: 'DAILY' } }, }); }); it('should not remove dtend', () => { const ALL_DAY_COMPONENT = parse(`BEGIN:VEVENT UID:abc DTSTAMP:20230614T101702Z DTSTART;VALUE=DATE:20190812 DTEND;VALUE=DATE:20190814 SUMMARY:text RRULE:FREQ=DAILY END:VEVENT`) as VcalVeventComponent; expect(withoutRedundantDtEnd(ALL_DAY_COMPONENT)).toEqual({ component: 'vevent', uid: { value: 'abc' }, dtstart: { value: { year: 2019, month: 8, day: 12 }, parameters: { type: 'date' } }, dtstamp: { value: { year: 2023, month: 6, day: 14, hours: 10, minutes: 17, seconds: 2, isUTC: true } }, dtend: { value: { year: 2019, month: 8, day: 14 }, parameters: { type: 'date' } }, summary: { value: 'text' }, rrule: { value: { freq: 'DAILY' } }, }); }); }); describe('part day', () => { it('should remove redundant dtend', () => { const PART_DAY_COMPONENT = parse(`BEGIN:VEVENT UID:abc DTSTAMP:20230614T101702Z DTSTART;TZID=Europe/Zurich:20190719T120000 DTEND;TZID=Europe/Zurich:20190719T120000 SUMMARY:text RRULE:FREQ=DAILY END:VEVENT`) as VcalVeventComponent; expect(withoutRedundantDtEnd(PART_DAY_COMPONENT)).toEqual({ component: 'vevent', uid: { value: 'abc' }, dtstamp: { value: { year: 2023, month: 6, day: 14, hours: 10, minutes: 17, seconds: 2, isUTC: true } }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich', }, }, summary: { value: 'text' }, rrule: { value: { freq: 'DAILY' } }, }); }); it('should not remove dtend', () => { const PART_DAY_COMPONENT = parse(`BEGIN:VEVENT UID:abc DTSTAMP:20230614T101702Z DTSTART;TZID=Europe/Zurich:20190719T120000 DTEND:20190719T160000Z SUMMARY:text RRULE:FREQ=DAILY END:VEVENT`) as VcalVeventComponent; expect(withoutRedundantDtEnd(PART_DAY_COMPONENT)).toEqual({ component: 'vevent', uid: { value: 'abc' }, dtstamp: { value: { year: 2023, month: 6, day: 14, hours: 10, minutes: 17, seconds: 2, isUTC: true } }, dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, dtend: { value: { year: 2019, month: 7, day: 19, hours: 16, minutes: 0, seconds: 0, isUTC: true } }, summary: { value: 'text' }, rrule: { value: { freq: 'DAILY' } }, }); }); }); });
8,801
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/alarms/modelToValarm.spec.ts
import { modelToValarmComponent } from '../../../lib/calendar/alarms/modelToValarm'; import { NOTIFICATION_TYPE_API, NOTIFICATION_UNITS, NOTIFICATION_WHEN } from '../../../lib/calendar/constants'; describe('modelToValarm', () => { describe('part day', () => { it('should set correct trigger', () => { expect( modelToValarmComponent({ id: '-1', isAllDay: false, value: 15, type: NOTIFICATION_TYPE_API.DEVICE, unit: NOTIFICATION_UNITS.MINUTE, when: NOTIFICATION_WHEN.BEFORE, }) ).toEqual({ component: 'valarm', trigger: { value: { weeks: 0, days: 0, hours: 0, minutes: 15, seconds: 0, isNegative: true } }, action: { value: 'DISPLAY' }, }); }); }); describe('full day', () => { it('should set correct trigger', () => { expect( modelToValarmComponent({ id: '-1', type: NOTIFICATION_TYPE_API.DEVICE, unit: NOTIFICATION_UNITS.DAY, when: NOTIFICATION_WHEN.BEFORE, isAllDay: true, at: new Date(2000, 0, 1, 10, 1), }) ).toEqual({ component: 'valarm', trigger: { value: { weeks: 0, days: 0, hours: 13, minutes: 59, seconds: 0, isNegative: true } }, action: { value: 'DISPLAY' }, }); }); }); });
8,802
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/holidaysCalendar/holidaysCalendar.spec.ts
import { findHolidaysCalendarByCountryCodeAndLanguageTag, getHolidaysCalendarsFromCountryCode, getHolidaysCalendarsFromTimeZone, getSuggestedHolidaysCalendar, } from '@proton/shared/lib/calendar/holidaysCalendar/holidaysCalendar'; import { HolidaysDirectoryCalendar } from '@proton/shared/lib/interfaces/calendar'; const frCalendar = { CalendarID: 'calendarID1', Country: 'France', CountryCode: 'fr', LanguageCode: 'fr', Language: 'Français', Timezones: ['Europe/Paris'], Passphrase: 'dummyPassphrase', Hidden: false, SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const chEnCalendar = { CalendarID: 'calendarID2', Country: 'Switzerland', CountryCode: 'ch', LanguageCode: 'en', Language: 'English', Timezones: ['Europe/Zurich'], Passphrase: 'dummyPassphrase', Hidden: false, SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const chDeCalendar = { CalendarID: 'calendarID3', Country: 'Switzerland', CountryCode: 'ch', LanguageCode: 'de', Language: 'Deutsch', Timezones: ['Europe/Zurich'], Passphrase: 'dummyPassphrase', Hidden: false, SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const beFrCalendar = { CalendarID: 'calendarID4', Country: 'Belgium', CountryCode: 'be', LanguageCode: 'fr', Language: 'Français', Timezones: ['Europe/Brussels'], Passphrase: 'dummyPassphrase', Hidden: false, SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const beNlCalendar = { CalendarID: 'calendarID5', Country: 'Belgium', CountryCode: 'be', LanguageCode: 'nl', Language: 'Dutch', Timezones: ['Europe/Brussels'], Passphrase: 'dummyPassphrase', Hidden: false, SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const nlCalendar = { CalendarID: 'calendarID6', Country: 'Netherlands', CountryCode: 'nl', LanguageCode: 'nl', Language: 'Dutch', Timezones: ['Europe/Brussels'], Passphrase: 'dummyPassphrase', Hidden: false, SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const auCalendar = { CalendarID: 'calendarID7', Country: 'Australia', CountryCode: 'au', LanguageCode: 'en', Language: 'English', Timezones: [ 'Antarctica/Macquarie', 'Australia/Adelaide', 'Australia/Brisbane', 'Australia/Broken_Hill', 'Australia/Darwin', 'Australia/Eucla', 'Australia/Hobart', 'Australia/Lindeman', 'Australia/Lord_Howe', 'Australia/Melbourne', 'Australia/Perth', 'Australia/Sydney', ], Hidden: false, Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const directory: HolidaysDirectoryCalendar[] = [ frCalendar, chEnCalendar, chDeCalendar, beNlCalendar, beFrCalendar, nlCalendar, auCalendar, ]; describe('Holidays calendars helpers', () => { describe('getHolidaysCalendarsFromTimezone', () => { it('should return all holidays calendars from the same time zone', () => { const tzid = 'Europe/Zurich'; const expected = [chEnCalendar, chDeCalendar]; expect(getHolidaysCalendarsFromTimeZone(directory, tzid)).toEqual(expected); }); }); describe('getHolidaysCalendarsFromCountryCode', () => { it('should return all holidays calendars from the same country code, sorted by languages', () => { const countryCode = 'ch'; const expected = [chDeCalendar, chEnCalendar]; expect(getHolidaysCalendarsFromCountryCode(directory, countryCode)).toEqual(expected); }); }); describe('findHolidaysCalendarByCountryCodeAndLanguageCode', () => { it('should return the holidays calendar with the same language', () => { const countryCode = 'ch'; const languageTags = ['en']; const expected = chEnCalendar; expect(findHolidaysCalendarByCountryCodeAndLanguageTag(directory, countryCode, languageTags)).toEqual( expected ); }); it('should return the holidays calendar with the first language', () => { const countryCode = 'ch'; // No calendar with the same language code is available in the options, so we return the first calendar sorted by languages const languageTags = ['not in options']; const expected = chDeCalendar; expect(findHolidaysCalendarByCountryCodeAndLanguageTag(directory, countryCode, languageTags)).toEqual( expected ); }); }); describe('getSuggestedHolidaysCalendar', () => { it('should not return a calendar if no time zone matches', () => { const tzid = 'does not exist'; const protonLanguage = 'en_US'; const languageTags: string[] = []; expect(getSuggestedHolidaysCalendar(directory, tzid, protonLanguage, languageTags)).toBeUndefined(); }); it('should return the only holidays calendar found', () => { const tzid = 'Australia/Adelaide'; const protonLanguage = 'en_US'; const languageTags = ['en-au']; const expected = auCalendar; expect(getSuggestedHolidaysCalendar(directory, tzid, protonLanguage, languageTags)).toEqual(expected); }); it('should return the holidays calendar with the same language (one country match)', () => { const tzid = 'Europe/Zurich'; const protonLanguage = 'en_US'; const languageTags = ['fr-ch']; const expected = chEnCalendar; expect(getSuggestedHolidaysCalendar(directory, tzid, protonLanguage, languageTags)).toEqual(expected); }); it('should return the holidays calendar with the first language (one country match)', () => { const tzid = 'Europe/Zurich'; // No calendar with the same language code is available in the options, so we return the first calendar sorted by languages const protonLanguage = 'nl_NL'; const languageTags = ['nl-be']; const expected = chDeCalendar; expect(getSuggestedHolidaysCalendar(directory, tzid, protonLanguage, languageTags)).toEqual(expected); }); it('should return undefined when there is a multiple country match and no language match', () => { const tzid = 'Europe/Brussels'; const protonLanguage = 'en_US'; const languageTags = ['en-US']; expect(getSuggestedHolidaysCalendar(directory, tzid, protonLanguage, languageTags)).toBeUndefined(); }); it('should return the holidays calendar with the country preferred by language (multiple country match)', () => { const tzid = 'Europe/Brussels'; const protonLanguage = 'en_US'; const languageTags = ['en-US', 'nl-nl']; const expected = nlCalendar; expect(getSuggestedHolidaysCalendar(directory, tzid, protonLanguage, languageTags)).toEqual(expected); }); it('should return the holidays calendar with the preferred Proton language (multiple country match)', () => { const tzid = 'Europe/Brussels'; const protonLanguage = 'fr_FR'; const languageTags = ['en-US', 'fr-be']; const expected = beFrCalendar; expect(getSuggestedHolidaysCalendar(directory, tzid, protonLanguage, languageTags)).toEqual(expected); }); it('should return the holidays calendar with the preferred browser language if the Proton language is not in the list (multiple country match)', () => { const tzid = 'Europe/Brussels'; const protonLanguage = 'es_ES'; const languageTags = ['en-US', 'fr-be']; const expected = beFrCalendar; expect(getSuggestedHolidaysCalendar(directory, tzid, protonLanguage, languageTags)).toEqual(expected); }); it(`should return the holidays calendar with the first language if we couldn't match a language (multiple country match)`, () => { const tzid = 'Europe/Brussels'; const protonLanguage = 'es_ES'; const languageTags = ['en-US', 'en-be']; const expected = beNlCalendar; expect(getSuggestedHolidaysCalendar(directory, tzid, protonLanguage, languageTags)).toEqual(expected); }); }); });
8,803
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/icsSurgery/vevent.spec.ts
import { getDtendPropertyFromDuration, getSupportedDtstamp } from '../../../lib/calendar/icsSurgery/vevent'; describe('getSupportedDtstamp()', () => { it('leaves untouched a proper DTSTAMP', () => { expect( getSupportedDtstamp( { value: { year: 2020, month: 1, day: 31, hours: 15, minutes: 11, seconds: 11, isUTC: true }, }, 1666017619812 ) ).toEqual({ value: { year: 2020, month: 1, day: 31, hours: 15, minutes: 11, seconds: 11, isUTC: true } }); }); it('leaves untouched a DTSTAMP with Zulu marker and time zone', () => { expect( getSupportedDtstamp( { value: { year: 2020, month: 1, day: 31, hours: 15, minutes: 11, seconds: 11, isUTC: true }, parameters: { tzid: 'Asia/Seoul' }, }, 1666017619812 ) ).toEqual({ value: { year: 2020, month: 1, day: 31, hours: 15, minutes: 11, seconds: 11, isUTC: true } }); }); it('converts a time-zoned DTSTAMP', () => { expect( getSupportedDtstamp( { value: { year: 2020, month: 1, day: 31, hours: 15, minutes: 11, seconds: 11, isUTC: false }, parameters: { tzid: 'America/Montevideo' }, }, 1666017619812 ) ).toEqual({ value: { year: 2020, month: 1, day: 31, hours: 18, minutes: 11, seconds: 11, isUTC: true } }); }); it('converts a time-zoned DTSTAMP with a TZID that needs conversion', () => { expect( getSupportedDtstamp( { value: { year: 2020, month: 1, day: 31, hours: 15, minutes: 11, seconds: 11, isUTC: false }, parameters: { tzid: '/mozilla.org/20050126_1/Asia/Pyongyang' }, }, 1666017619812 ) ).toEqual({ value: { year: 2020, month: 1, day: 31, hours: 6, minutes: 11, seconds: 11, isUTC: true } }); }); it('converts a floating DTSTAMP', () => { expect( getSupportedDtstamp( { value: { year: 2020, month: 1, day: 31, hours: 15, minutes: 11, seconds: 11, isUTC: false }, }, 1666017619812 ) ).toEqual({ value: { year: 2020, month: 1, day: 31, hours: 15, minutes: 11, seconds: 11, isUTC: true } }); }); it('converts an all-day DTSTAMP', () => { expect( getSupportedDtstamp( { value: { year: 2020, month: 1, day: 31 }, parameters: { type: 'date' }, }, 1666017619812 ) ).toEqual({ value: { year: 2020, month: 1, day: 31, hours: 0, minutes: 0, seconds: 0, isUTC: true } }); }); it('converts an all-day DTSTAMP with TZID', () => { expect( getSupportedDtstamp( { value: { year: 2020, month: 1, day: 31 }, parameters: { type: 'date', tzid: 'America/Montevideo' }, }, 1666017619812 ) ).toEqual({ value: { year: 2020, month: 1, day: 31, hours: 3, minutes: 0, seconds: 0, isUTC: true } }); }); it('defaults to the given timestamp if a time zone is present but not supported', () => { expect( getSupportedDtstamp( { value: { year: 2020, month: 1, day: 31 }, parameters: { type: 'date', tzid: 'Europe/My_home' }, }, 1666017619812 ) ).toEqual({ value: { year: 2022, month: 10, day: 17, hours: 14, minutes: 40, seconds: 19, isUTC: true } }); }); }); describe('getDtendPropertyFromDuration()', () => { it('returns the appropriate dtend when given a duration and start', () => { // UTC part day expect( getDtendPropertyFromDuration( { value: { year: 2020, month: 1, day: 31, hours: 0, minutes: 0, seconds: 0, isUTC: true } }, { weeks: 0, days: 1, hours: 0, minutes: 0, seconds: 0, isNegative: false, } ) ).toEqual({ value: { year: 2020, month: 2, day: 1, hours: 0, minutes: 0, seconds: 0, isUTC: true } }); // Localized part day expect( getDtendPropertyFromDuration( { parameters: { tzid: 'Europe/Zurich' }, value: { year: 2020, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, isUTC: false }, }, { weeks: 0, days: 1, hours: 1, minutes: 0, seconds: 0, isNegative: false, } ) ).toEqual({ parameters: { tzid: 'Europe/Zurich' }, value: { year: 2020, month: 1, day: 2, hours: 1, minutes: 0, seconds: 0, isUTC: false }, }); // All day with 1 day duration expect( getDtendPropertyFromDuration( { parameters: { type: 'date' }, value: { year: 2020, month: 1, day: 1 }, }, { weeks: 0, days: 1, hours: 0, minutes: 0, seconds: 0, isNegative: false, } ) ).toBeUndefined(); // All day badly formatted with 1 second duration expect( getDtendPropertyFromDuration( { parameters: { type: 'date' }, value: { year: 2020, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, isUTC: true }, }, { weeks: 0, days: 0, hours: 0, minutes: 0, seconds: 1, isNegative: false, } ) ).toBeUndefined(); // All day badly formatted with slightly over 1 day duration expect( getDtendPropertyFromDuration( { parameters: { type: 'date' }, value: { year: 2020, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, isUTC: true }, }, { weeks: 0, days: 1, hours: 0, minutes: 0, seconds: 1, isNegative: false, } ) ).toEqual({ parameters: { type: 'date' }, value: { year: 2020, month: 1, day: 3 }, }); // UTC Part day with complex dueration expect( getDtendPropertyFromDuration( { value: { year: 2020, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, isUTC: true }, }, { weeks: 2, days: 3, hours: 4, minutes: 5, seconds: 6, isNegative: false, } ) ).toEqual({ value: { year: 2020, month: 1, day: 18, hours: 4, minutes: 5, seconds: 6, isUTC: true }, }); // All day badly formatted complex duration expect( getDtendPropertyFromDuration( { parameters: { type: 'date' }, value: { year: 2020, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, isUTC: true }, }, { weeks: 5, days: 1, hours: 1, minutes: 1, seconds: 1, isNegative: false, } ) ).toEqual({ parameters: { type: 'date' }, value: { year: 2020, month: 2, day: 7 }, }); // All day negative duration expect( getDtendPropertyFromDuration( { parameters: { type: 'date' }, value: { year: 2020, month: 1, day: 1 }, }, { weeks: 5, days: 1, hours: 1, minutes: 1, seconds: 1, isNegative: true, } ) ).toBeUndefined(); }); });
8,804
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/integration/invite.spec.js
import { enUS } from 'date-fns/locale'; import { ICAL_ATTENDEE_STATUS, ICAL_METHOD } from '../../../lib/calendar/constants'; import { createInviteIcs, generateEmailBody, generateEmailSubject } from '../../../lib/calendar/mailIntegration/invite'; import { omit } from '../../../lib/helpers/object'; import { toCRLF } from '../../../lib/helpers/string'; import { RE_PREFIX } from '../../../lib/mail/messages'; const exampleVevent = { component: 'vevent', uid: { value: 'test-event' }, dtstamp: { value: { year: 2020, month: 9, day: 1, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }, dtstart: { value: { year: 2020, month: 3, day: 12, hours: 8, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Zurich' }, }, dtend: { value: { year: 2020, month: 3, day: 12, hours: 9, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, rrule: { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15 } } }, location: { value: 'asd' }, sequence: { value: 0 }, attendee: [ { value: 'emailto:[email protected]', parameters: { cn: 'Unknown attendee 1', partstat: ICAL_ATTENDEE_STATUS.ACCEPTED }, }, { value: 'emailto:[email protected]', parameters: { cn: 'Unknown attendee 2', partstat: ICAL_ATTENDEE_STATUS.TENTATIVE }, }, { value: 'emailto:[email protected]', parameters: { cn: 'Unknown attendee 3', partstat: ICAL_ATTENDEE_STATUS.DECLINED }, }, { value: 'emailto:[email protected]', parameters: { cn: 'Unknown attendee 4', partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION }, }, ], 'x-pm-session-key': { value: 'mNDd2g2LlUFUwTQZwtLuN3/ci3jq1n/DKX0oIAXgHi0=' }, 'x-pm-shared-event-id': { value: 'bbGoXaSj-v8UdMSbebf1GkWPkEiuSYqFU7KddqOMZ8bT63uah7OO8b6WlLrqVlqUjhJ0hEY8VFDvmn2sG0biE2MBSPv-wF5DmmS8cdH8zPI=', }, 'x-pm-proton-reply': { value: 'true', parameters: { type: 'boolean' } }, }; describe('createInviteIcs for REQUEST method', () => { it('should create the correct ics with the expected X-PM fields', () => { const params = { method: ICAL_METHOD.REQUEST, prodId: 'Proton Calendar', attendeesTo: [{ value: 'mailto:[email protected]', parameters: { partstat: ICAL_ATTENDEE_STATUS.ACCEPTED } }], vevent: exampleVevent, keepDtstamp: true, }; const ics = createInviteIcs(params); const expected = `BEGIN:VCALENDAR PRODID:Proton Calendar VERSION:2.0 METHOD:REQUEST CALSCALE:GREGORIAN BEGIN:VEVENT UID:test-event DTSTAMP:20200901T120000Z DTSTART;TZID=Europe/Zurich:20200312T083000 DTEND;TZID=America/New_York:20200312T093000 RRULE:FREQ=WEEKLY;UNTIL=20200515 LOCATION:asd SEQUENCE:0 ATTENDEE;CN=Unknown attendee 1;PARTSTAT=ACCEPTED:emailto:[email protected] ATTENDEE;CN=Unknown attendee 2;PARTSTAT=TENTATIVE:emailto:[email protected] ATTENDEE;CN=Unknown attendee 3;PARTSTAT=DECLINED:emailto:[email protected] ATTENDEE;CN=Unknown attendee 4;PARTSTAT=NEEDS-ACTION:emailto:[email protected] e X-PM-SESSION-KEY:mNDd2g2LlUFUwTQZwtLuN3/ci3jq1n/DKX0oIAXgHi0= X-PM-SHARED-EVENT-ID:bbGoXaSj-v8UdMSbebf1GkWPkEiuSYqFU7KddqOMZ8bT63uah7OO8b 6WlLrqVlqUjhJ0hEY8VFDvmn2sG0biE2MBSPv-wF5DmmS8cdH8zPI= SUMMARY: END:VEVENT END:VCALENDAR`; expect(ics).toEqual(toCRLF(expected)); }); }); describe('createInviteIcs for REPLY method', () => { it('should create the correct ics when there is no summary', () => { const params = { method: ICAL_METHOD.REPLY, prodId: 'Proton Calendar', attendeesTo: [{ value: 'mailto:[email protected]', parameters: { partstat: ICAL_ATTENDEE_STATUS.ACCEPTED } }], vevent: exampleVevent, keepDtstamp: true, }; const ics = createInviteIcs(params); const expected = `BEGIN:VCALENDAR PRODID:Proton Calendar VERSION:2.0 METHOD:REPLY CALSCALE:GREGORIAN BEGIN:VEVENT UID:test-event DTSTART;TZID=Europe/Zurich:20200312T083000 DTEND;TZID=America/New_York:20200312T093000 SEQUENCE:0 RRULE:FREQ=WEEKLY;UNTIL=20200515 LOCATION:asd DTSTAMP:20200901T120000Z X-PM-PROTON-REPLY;VALUE=BOOLEAN:TRUE ATTENDEE;PARTSTAT=ACCEPTED:mailto:[email protected] END:VEVENT END:VCALENDAR`; expect(ics).toEqual(toCRLF(expected)); }); it('should create the correct ics when there is an empty summary', () => { const params = { method: ICAL_METHOD.REPLY, prodId: 'Proton Calendar', attendeesTo: [{ value: 'mailto:[email protected]', parameters: { partstat: ICAL_ATTENDEE_STATUS.TENTATIVE } }], vevent: { ...exampleVevent, summary: { value: '' }, }, keepDtstamp: true, }; const ics = createInviteIcs(params); const expected = `BEGIN:VCALENDAR PRODID:Proton Calendar VERSION:2.0 METHOD:REPLY CALSCALE:GREGORIAN BEGIN:VEVENT UID:test-event DTSTART;TZID=Europe/Zurich:20200312T083000 DTEND;TZID=America/New_York:20200312T093000 SEQUENCE:0 RRULE:FREQ=WEEKLY;UNTIL=20200515 LOCATION:asd SUMMARY: DTSTAMP:20200901T120000Z X-PM-PROTON-REPLY;VALUE=BOOLEAN:TRUE ATTENDEE;PARTSTAT=TENTATIVE:mailto:[email protected] END:VEVENT END:VCALENDAR`; expect(ics).toEqual(toCRLF(expected)); }); it('should create the correct ics when there is a summary, a recurrence-id and rrule (should remove it)', () => { const params = { method: ICAL_METHOD.REPLY, prodId: 'Proton Calendar', attendeesTo: [{ value: 'mailto:[email protected]', parameters: { partstat: ICAL_ATTENDEE_STATUS.DECLINED } }], vevent: { ...exampleVevent, 'recurrence-id': { value: { year: 2021, month: 6, day: 18, hours: 15, minutes: 0, seconds: 0, isUTC: true }, }, summary: { value: 'dcf' }, }, keepDtstamp: true, }; const ics = createInviteIcs(params); const expected = `BEGIN:VCALENDAR PRODID:Proton Calendar VERSION:2.0 METHOD:REPLY CALSCALE:GREGORIAN BEGIN:VEVENT UID:test-event DTSTART;TZID=Europe/Zurich:20200312T083000 DTEND;TZID=America/New_York:20200312T093000 SEQUENCE:0 RECURRENCE-ID:20210618T150000Z LOCATION:asd SUMMARY:dcf DTSTAMP:20200901T120000Z X-PM-PROTON-REPLY;VALUE=BOOLEAN:TRUE ATTENDEE;PARTSTAT=DECLINED:mailto:[email protected] END:VEVENT END:VCALENDAR`; expect(ics).toEqual(toCRLF(expected)); }); it('should create the correct ics when there are no X-PM fields', () => { const params = { method: ICAL_METHOD.REPLY, prodId: 'Proton Calendar', attendeesTo: [{ value: 'mailto:[email protected]', parameters: { partstat: ICAL_ATTENDEE_STATUS.DECLINED } }], vevent: omit(exampleVevent, ['x-pm-shared-event-id', 'x-pm-session-key', 'x-pm-proton-reply']), keepDtstamp: true, }; const ics = createInviteIcs(params); const expected = `BEGIN:VCALENDAR PRODID:Proton Calendar VERSION:2.0 METHOD:REPLY CALSCALE:GREGORIAN BEGIN:VEVENT UID:test-event DTSTART;TZID=Europe/Zurich:20200312T083000 DTEND;TZID=America/New_York:20200312T093000 SEQUENCE:0 RRULE:FREQ=WEEKLY;UNTIL=20200515 LOCATION:asd DTSTAMP:20200901T120000Z ATTENDEE;PARTSTAT=DECLINED:mailto:[email protected] END:VEVENT END:VCALENDAR`; expect(ics).toEqual(toCRLF(expected)); }); }); describe('createInviteIcs for CANCEL method', () => { it('should create the correct ics', () => { const params = { method: ICAL_METHOD.CANCEL, prodId: 'Proton Calendar', attendeesTo: [ { value: 'mailto:[email protected]', parameters: { partstat: ICAL_ATTENDEE_STATUS.ACCEPTED } }, { value: 'mailto:[email protected]', parameters: { partstat: ICAL_ATTENDEE_STATUS.TENTATIVE } }, { value: 'mailto:[email protected]', parameters: { partstat: ICAL_ATTENDEE_STATUS.DECLINED } }, { value: 'mailto:[email protected]', parameters: { partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION } }, ], vevent: exampleVevent, keepDtstamp: true, }; const ics = createInviteIcs(params); const expected = `BEGIN:VCALENDAR PRODID:Proton Calendar VERSION:2.0 METHOD:CANCEL CALSCALE:GREGORIAN BEGIN:VEVENT UID:test-event DTSTART;TZID=Europe/Zurich:20200312T083000 DTEND;TZID=America/New_York:20200312T093000 SEQUENCE:0 RRULE:FREQ=WEEKLY;UNTIL=20200515 LOCATION:asd DTSTAMP:20200901T120000Z X-PM-SHARED-EVENT-ID:bbGoXaSj-v8UdMSbebf1GkWPkEiuSYqFU7KddqOMZ8bT63uah7OO8b 6WlLrqVlqUjhJ0hEY8VFDvmn2sG0biE2MBSPv-wF5DmmS8cdH8zPI= ATTENDEE:mailto:[email protected] ATTENDEE:mailto:[email protected] ATTENDEE:mailto:[email protected] ATTENDEE:mailto:[email protected] END:VEVENT END:VCALENDAR`; expect(ics).toEqual(toCRLF(expected)); }); }); describe('generateEmailSubject', () => { it('should return the expected subject for a new invite to an all-day single-day event', () => { const vevent = { ...exampleVevent, dtstart: { value: { year: 2020, month: 10, day: 12 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 10, day: 13 }, parameters: { type: 'date' }, }, }; const expected = 'Invitation for an event on Monday October 12th, 2020'; expect( generateEmailSubject({ vevent, method: ICAL_METHOD.REQUEST, isCreateEvent: true, dateFormatOptions: { locale: enUS }, }) ).toEqual(expected); }); it('should return the expected subject for an update to an all-day multiple-day event', () => { const vevent = { ...exampleVevent, dtstart: { value: { year: 2020, month: 3, day: 22 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 3, day: 24 }, parameters: { type: 'date' }, }, }; const expected = 'Update for an event starting on Sunday March 22nd, 2020'; expect( generateEmailSubject({ vevent, method: ICAL_METHOD.REQUEST, isCreateEvent: false, dateFormatOptions: { locale: enUS }, }) ).toEqual(expected); }); it('should return the expected subject for a cancellation of a part-day event', () => { const expected = 'Cancellation of an event starting on Thursday March 12th, 2020 at 8:30 AM (GMT+1)'; expect( generateEmailSubject({ vevent: exampleVevent, method: ICAL_METHOD.CANCEL, isCreateEvent: false, dateFormatOptions: { locale: enUS }, }) ).toEqual(expected); }); it('should return the expected subject for a reply', () => { const expected = `${RE_PREFIX} Invitation for an event starting on Sunday March 22nd, 2020`; const expectedSingleFullDay = `${RE_PREFIX} Invitation for an event on Sunday March 22nd, 2020`; expect( generateEmailSubject({ vevent: { ...exampleVevent, dtstart: { value: { year: 2020, month: 3, day: 22 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 3, day: 24 }, parameters: { type: 'date' }, }, }, method: ICAL_METHOD.REPLY, isCreateEvent: false, dateFormatOptions: { locale: enUS }, }) ).toEqual(expected); expect( generateEmailSubject({ vevent: { ...exampleVevent, dtstart: { value: { year: 2020, month: 3, day: 22 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 3, day: 23 }, parameters: { type: 'date' }, }, }, method: ICAL_METHOD.REPLY, isCreateEvent: false, dateFormatOptions: { locale: enUS }, }) ).toEqual(expectedSingleFullDay); }); }); describe('generateEmailBody', () => { it('should return the expected body for a new invite to an all-day single-day event with no description', () => { const vevent = { ...exampleVevent, dtstart: { value: { year: 2020, month: 10, day: 12 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 10, day: 13 }, parameters: { type: 'date' }, }, }; const expected = `You are invited to (no title) When: Monday October 12th, 2020 (all day) Where: asd`; expect( generateEmailBody({ vevent, method: ICAL_METHOD.REQUEST, isCreateEvent: true, options: { locale: enUS }, }) ).toEqual(expected); }); it('should return the expected body for a new invite to an all-day single-day event with no location', () => { const vevent = { ...omit(exampleVevent, ['location', 'dtend']), summary: { value: 'Watch movie' }, dtstart: { value: { year: 2020, month: 10, day: 12 }, parameters: { type: 'date' }, }, description: { value: 'I am a good description' }, }; const expected = `You are invited to Watch movie When: Monday October 12th, 2020 (all day) Description: I am a good description`; expect( generateEmailBody({ vevent, method: ICAL_METHOD.REQUEST, isCreateEvent: true, options: { locale: enUS }, }) ).toEqual(expected); }); it('should return the expected body for an update to an to an all-day multiple-day event with no location nor description', () => { const vevent = { ...omit(exampleVevent, ['location', 'description']), dtstart: { value: { year: 2020, month: 3, day: 22 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 3, day: 24 }, parameters: { type: 'date' }, }, }; const expected = `(no title) has been updated. When: Sunday March 22nd, 2020 - Monday March 23rd, 2020`; expect( generateEmailBody({ vevent, method: ICAL_METHOD.REQUEST, isCreateEvent: false, options: { locale: enUS }, }) ).toEqual(expected); }); it('should return the expected body for an update to an to an all-day multiple-day event with both location and description', () => { const vevent = { ...exampleVevent, dtstart: { value: { year: 2020, month: 3, day: 22 }, parameters: { type: 'date' }, }, dtend: { value: { year: 2020, month: 3, day: 24 }, parameters: { type: 'date' }, }, summary: { value: 'Watch movie' }, description: { value: 'I am a good description' }, }; const expected = `Watch movie has been updated. When: Sunday March 22nd, 2020 - Monday March 23rd, 2020 Where: asd Description: I am a good description`; expect( generateEmailBody({ vevent, method: ICAL_METHOD.REQUEST, isCreateEvent: false, options: { locale: enUS }, }) ).toEqual(expected); }); it('should return the expected body for an update to an to a part-day event with both location and description', () => { const vevent = { ...exampleVevent, summary: { value: 'Watch movie' }, description: { value: 'I am a good description' }, }; const expected = `Watch movie has been updated. When: Thursday March 12th, 2020 at 8:30 AM (GMT+1) - Thursday March 12th, 2020 at 9:30 AM (GMT-4) Where: asd Description: I am a good description`; expect( generateEmailBody({ vevent, method: ICAL_METHOD.REQUEST, isCreateEvent: false, options: { locale: enUS }, }) ).toEqual(expected); }); it('should return the expected body for a cancellation of a part-day event with both location and description', () => { const expected = '(no title) has been canceled.'; expect( generateEmailBody({ vevent: exampleVevent, method: ICAL_METHOD.CANCEL, isCreateEvent: false, options: { locale: enUS }, }) ).toEqual(expected); }); it('should return the expected body for a reply', () => { const emailAddress = '[email protected]'; const expected = `${emailAddress} has declined your invitation to (no title)`; expect( generateEmailBody({ vevent: exampleVevent, method: ICAL_METHOD.REPLY, isCreateEvent: false, options: { locale: enUS }, emailAddress, partstat: ICAL_ATTENDEE_STATUS.DECLINED, }) ).toEqual(expected); }); it('should throw if no partstat is passed for a reply', () => { const emailAddress = '[email protected]'; expect(() => generateEmailBody({ vevent: exampleVevent, method: ICAL_METHOD.REPLY, isCreateEvent: false, options: { locale: enUS }, emailAddress, }) ).toThrow(); }); it('should throw if an invalid partstat is passed for a reply', () => { const emailAddress = '[email protected]'; expect(() => generateEmailBody({ vevent: exampleVevent, method: ICAL_METHOD.REPLY, isCreateEvent: false, options: { locale: enUS }, emailAddress, partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION, }) ).toThrow(); }); });
8,805
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/rrule/rrule.spec.js
import { FREQUENCY } from '../../../lib/calendar/constants'; import { getDayAndSetpos, getHasConsistentRrule, getHasOccurrences, getIsRruleCustom, getIsRruleSimple, getIsRruleSupported, getIsStandardByday, getSupportedRrule, getSupportedUntil, } from '../../../lib/calendar/recurrence/rrule'; import { parse } from '../../../lib/calendar/vcal'; describe('getIsStandardByday', () => { it('returns true for standard BYDAY strings', () => { const bydays = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA']; expect(bydays.map(getIsStandardByday)).toEqual(bydays.map(() => true)); }); it('returns false for non-standard BYDAY strings', () => { const bydays = ['1SU', 'SUN', 'S', 'DO', '']; expect(bydays.map(getIsStandardByday)).toEqual(bydays.map(() => false)); }); }); describe('getDayAndSetpos', () => { it('gets the day and setpos correctly', () => { const bydays = ['1SU', '+2MO', '-1FR', 'WE']; const results = [{ setpos: 1, day: 'SU' }, { setpos: 2, day: 'MO' }, { setpos: -1, day: 'FR' }, { day: 'WE' }]; expect(bydays.map((byday) => getDayAndSetpos(byday))).toEqual(results); }); }); describe('getSupportedUntil', () => { it('should keep the date for all-day events', () => { const tzid = 'Pacific/Niue'; const until = { year: 2020, month: 6, day: 27, hours: 10, minutes: 59, seconds: 59, isUTC: true }; const dtstartValue = { year: 2010, month: 6, day: 27 }; const expected = { year: 2020, month: 6, day: 27 }; expect( getSupportedUntil({ until, dtstart: { parameters: { type: 'date' }, value: dtstartValue }, tzid, }) ).toEqual(expected); }); it('should always return the same until if it was at the end of the day already', () => { const tzid = 'Pacific/Niue'; const until = { year: 2020, month: 6, day: 27, hours: 10, minutes: 59, seconds: 59, isUTC: true }; const dtstartValue = { year: 2010, month: 6, day: 27, hours: 10, minutes: 59, seconds: 59, isUTC: false }; expect(getSupportedUntil({ until, dtstart: { parameters: { tzid }, value: dtstartValue } })).toEqual(until); }); it('should always return an until at the end of the day', () => { const tzid = 'Pacific/Niue'; const untils = [ { year: 2020, month: 6, day: 27, hours: 15, minutes: 14, isUTC: true }, { year: 2020, month: 6, day: 27 }, ]; const expected = [ { year: 2020, month: 6, day: 28, hours: 10, minutes: 59, seconds: 59, isUTC: true }, { year: 2020, month: 6, day: 27, hours: 10, minutes: 59, seconds: 59, isUTC: true }, ]; const dtstartValue = { year: 2010, month: 6, day: 28, hours: 10, minutes: 59, seconds: 59, isUTC: false }; expect( untils.map((until) => getSupportedUntil({ until, dtstart: { parameters: { tzid }, value: dtstartValue } })) ).toEqual(expected); }); it('should keep the right date for all-day events when a guess tzid is passed', () => { const guessTzid = 'Asia/Taipei'; const until = { year: 2020, month: 11, day: 24, hours: 16, minutes: 0, seconds: 0, isUTC: true }; const dtstartValue = { year: 2010, month: 11, day: 24 }; const expected = { year: 2020, month: 11, day: 25 }; expect( getSupportedUntil({ until, dtstart: { parameters: { type: 'date' }, value: dtstartValue }, guessTzid, }) ).toEqual(expected); }); }); describe('getIsRruleSimple', () => { it('returns true for simple recurring events', () => { const rrules = [ { freq: FREQUENCY.DAILY, interval: 1, }, { freq: FREQUENCY.WEEKLY, interval: 1, byday: 'SA', }, { freq: FREQUENCY.MONTHLY, interval: 1, bymonthday: 23, }, { freq: FREQUENCY.YEARLY, interval: 1, bymonth: 5, }, { freq: FREQUENCY.YEARLY, interval: 1, bymonthday: 23, }, ]; expect(rrules.map(getIsRruleSimple)).toEqual(rrules.map(() => true)); }); it('returns false for supported custom-recurring events', () => { const rrules = [ { freq: FREQUENCY.DAILY, count: 3, interval: 2, }, { freq: FREQUENCY.WEEKLY, byday: ['SA', 'FR'], }, { freq: FREQUENCY.WEEKLY, byday: ['SA', 'FR'], count: 1, }, { freq: FREQUENCY.WEEKLY, until: { year: 2020, month: 5, day: 10 }, }, { freq: FREQUENCY.MONTHLY, bysetpos: 2, byday: 'WE', }, { freq: FREQUENCY.MONTHLY, byday: '-1WE', until: { year: 2020, month: 5, day: 10 }, }, { freq: FREQUENCY.YEARLY, interval: 2, }, { freq: FREQUENCY.YEARLY, count: 3, }, ]; expect(rrules.map(getIsRruleSimple)).toEqual(rrules.map(() => false)); }); it('returns false for non-supported custom-recurring events', () => { const rrules = [ { freq: 'HOURLY', }, { freq: FREQUENCY.WEEKLY, byday: ['SA', 'FR'], byhour: [8, 9], }, { freq: FREQUENCY.WEEKLY, byday: 'SA', bysetpos: 1, }, { freq: FREQUENCY.MONTHLY, byday: ['MO', 'WE'], }, { freq: FREQUENCY.YEARLY, bymonthday: 2, bymonth: 5, byday: 'TH', }, { freq: FREQUENCY.YEARLY, byday: 'MO', byweekno: 20, }, ]; expect(rrules.map(getIsRruleSimple)).toEqual(rrules.map(() => false)); }); }); describe('getIsRruleCustom', () => { it('returns false for simple recurring events', () => { const rrules = [ { freq: FREQUENCY.DAILY, interval: 1, }, { freq: FREQUENCY.WEEKLY, interval: 1, byday: 'SA', }, { freq: FREQUENCY.MONTHLY, interval: 1, bymonthday: 23, }, { freq: FREQUENCY.YEARLY, interval: 1, bymonth: 5, }, { freq: FREQUENCY.YEARLY, interval: 1, bymonthday: 23, }, ]; expect(rrules.map(getIsRruleCustom)).toEqual(rrules.map(() => false)); }); it('returns true for supported custom-recurring events', () => { const rrules = [ { freq: FREQUENCY.DAILY, count: 3, interval: 2, }, { freq: FREQUENCY.WEEKLY, byday: ['SA', 'FR'], }, { freq: FREQUENCY.WEEKLY, byday: ['SA', 'FR'], count: 1, }, { freq: FREQUENCY.WEEKLY, until: { year: 2020, month: 5, day: 10 }, }, { freq: FREQUENCY.MONTHLY, bysetpos: 2, byday: 'WE', }, { freq: FREQUENCY.MONTHLY, byday: '-1WE', until: { year: 2020, month: 5, day: 10 }, }, { freq: FREQUENCY.YEARLY, interval: 2, }, { freq: FREQUENCY.YEARLY, count: 1, }, ]; expect(rrules.map(getIsRruleCustom)).toEqual(rrules.map(() => true)); }); it('returns false for non-supported custom-recurring events', () => { const rrules = [ { freq: FREQUENCY.DAILY, count: 3, interval: 2, byday: ['TU', 'TH'], }, { freq: FREQUENCY.WEEKLY, byday: ['SA', 'FR'], bymonth: 1, count: 2, }, { freq: FREQUENCY.WEEKLY, until: { year: 2020, month: 5, day: 10 }, bysetpos: 3, }, { freq: FREQUENCY.MONTHLY, bysetpos: 2, }, { freq: FREQUENCY.MONTHLY, byday: 'SU', }, ]; expect(rrules.map(getIsRruleCustom)).toEqual(rrules.map(() => false)); }); }); describe('getHasOccurrences', () => { it('should filter out events that generate no occurrence', () => { const vevent = { dtstart: { value: { year: 2015, month: 8, day: 25, hours: 18, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Paris', }, }, rrule: { value: { freq: 'DAILY', count: 2, }, }, exdate: [ { value: { year: 2015, month: 8, day: 25, hours: 18, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Paris', }, }, { value: { year: 2015, month: 8, day: 26, hours: 18, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Paris', }, }, ], }; expect(getHasOccurrences(vevent)).toEqual(false); }); }); describe('getIsRruleSupported', () => { it('should accept events with monthly recurring rules of the form BYDAY=+/-nDD', () => { const vevents = [ `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=1SU\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=+2WE\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;COUNT=1;BYDAY=4MO\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=-1SA\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;COUNT=3;INTERVAL=2;BYDAY=TH;BYSETPOS=-1\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=TU;BYSETPOS=3\r\nEND:VEVENT`, ]; const rrules = vevents.map((vevent) => { const { rrule } = parse(vevent); return rrule.value; }); expect(rrules.map((rrule) => getIsRruleSupported(rrule))).toEqual(vevents.map(() => true)); }); it('should accept events with custom recurring rules for invitations that are not supported via import', () => { const vevents = [ `BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;BYHOUR=9,11;BYMINUTE=30\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=WEEKLY;BYMONTH=1,2,3;BYHOUR=9\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYMONTHDAY=8,9,10,-1\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;BYWEEKNO=50;BYMONTH=12\r\nEND:VEVENT`, ]; const rrules = vevents.map((vevent) => { const { rrule } = parse(vevent); return rrule.value; }); expect(rrules.map((rrule) => getIsRruleSupported(rrule))).toEqual(vevents.map(() => false)); expect(rrules.map((rrule) => getIsRruleSupported(rrule, true))).toEqual(vevents.map(() => true)); }); it('should accept events with valid yearly recurring rules', () => { const vevents = [ `BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;UNTIL=20200330T150000Z;INTERVAL=1;BYMONTHDAY=30;BYMONTH=3\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=2;BYMONTH=5\r\nEND:VEVENT`, ]; const rrules = vevents.map((vevent) => { const { rrule } = parse(vevent); return rrule.value; }); expect(rrules.map((rrule) => getIsRruleSupported(rrule))).toEqual(vevents.map(() => true)); }); it('should refuse events with invalid monthly recurring rules', () => { const vevents = [ `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=1SU,2MO\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=-2WE\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=5TH\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=FR\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=FR;BYSETPOS=5\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;BYDAY=TU;BYSETPOS=-2\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;INTERVAL=2;BYMONTHDAY=10,13,14\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=MONTHLY;INTERVAL=1;BYSETPOS=1;BYDAY=SU,MO,TU,WE,TH,FR,SA\r\nEND:VEVENT`, ]; const rrules = vevents.map((vevent) => { const { rrule } = parse(vevent); return rrule.value; }); expect(rrules.map((rrule) => getIsRruleSupported(rrule))).toEqual(vevents.map(() => false)); }); it('should refuse events with invalid yearly recurring rules', () => { const vevents = [ `BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=1,2,3,4,5,6,7,8,9,10,11,12\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;BYMONTHDAY=11,22\r\nEND:VEVENT`, `BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=2;BYMONTHDAY=17\r\nEND:VEVENT`, ]; const rrules = vevents.map((vevent) => { const { rrule } = parse(vevent); return rrule.value; }); expect(rrules.map((rrule) => getIsRruleSupported(rrule))).toEqual(vevents.map(() => false)); }); }); describe('getSupportedRrule', () => { const dtstartPartDayUTC = { value: { year: 2020, month: 5, day: 11, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }; const dtstartPartDayZoned = { value: { year: 2020, month: 5, day: 11, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'Antarctica/Troll' }, }; const dtstartAllDay = { value: { year: 2020, month: 5, day: 11 }, parameters: { type: 'date' }, }; it('should reformat rrules with a badly formatted UNTIL', () => { const vevents = [ { dtstart: dtstartPartDayUTC, rrule: { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15 } } }, }, { dtstart: dtstartPartDayZoned, rrule: { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15 } } }, }, { dtstart: dtstartAllDay, rrule: { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15, hours: 12, minutes: 0, seconds: 30, isUTC: false }, }, }, }, ]; const expected = [ { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15, hours: 23, minutes: 59, seconds: 59, isUTC: true }, }, }, { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15, hours: 21, minutes: 59, seconds: 59, isUTC: true }, }, }, { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15 } } }, ]; expect(vevents.map((vevent) => getSupportedRrule(vevent))).toEqual(expected); }); it('should reformat rrules with UNTIL in the middle of the day', () => { const vevents = [ { dtstart: dtstartPartDayUTC, rrule: { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15, hours: 12, minutes: 0, seconds: 30, isUTC: true }, }, }, }, { dtstart: dtstartPartDayZoned, rrule: { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15, hours: 12, minutes: 0, seconds: 30, isUTC: true }, }, }, }, ]; const expected = [ { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15, hours: 23, minutes: 59, seconds: 59, isUTC: true }, }, }, { value: { freq: 'WEEKLY', until: { year: 2020, month: 5, day: 15, hours: 21, minutes: 59, seconds: 59, isUTC: true }, }, }, ]; expect(vevents.map((vevent) => getSupportedRrule(vevent))).toEqual(expected); }); }); describe('getHasConsistentRrule', () => { const dtstartPartDayUTC = { value: { year: 2020, month: 5, day: 11, hours: 12, minutes: 0, seconds: 0, isUTC: true }, }; it('should not allow count and until together', () => { const dtstart = { value: { year: 2015, month: 8, day: 25, hours: 18, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Paris', }, }; const until = { year: 2015, month: 8, day: 30, hours: 16, minutes: 29, seconds: 59, isUTC: true }; expect( getHasConsistentRrule({ dtstart, rrule: { value: { freq: 'DAILY', until, }, }, }) ).toEqual(true); expect( getHasConsistentRrule({ dtstart, rrule: { value: { freq: 'DAILY', count: 1, }, }, }) ).toEqual(true); expect( getHasConsistentRrule({ dtstart, rrule: { value: { freq: 'DAILY', until, count: 1, }, }, }) ).toEqual(false); }); it('should not allow byyearday for frequencies other than yearly', () => { const dtstart = { value: { year: 2022, month: 1, day: 27, hours: 18, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Paris', }, }; expect( getHasConsistentRrule({ dtstart, rrule: { value: { freq: 'DAILY', byyearday: 27, }, }, }) ).toEqual(false); expect( getHasConsistentRrule({ dtstart, rrule: { value: { freq: 'WEEKLY', byyearday: 27, count: 3, interval: 2, }, }, }) ).toEqual(false); expect( getHasConsistentRrule({ dtstart, rrule: { value: { freq: 'MONTHLY', bymonthday: 27, byyearday: 27, }, }, }) ).toEqual(false); expect( getHasConsistentRrule({ dtstart, rrule: { value: { freq: 'YEARLY', byyearday: 27, }, }, }) ).toEqual(true); }); it('should filter out inconsistent rrules', () => { const rrules = [ { freq: 'MONTHLY', byday: '1MO', }, { freq: 'MONTHLY', byday: '-2MO', }, { freq: 'MONTHLY', byday: 'SU', }, { freq: 'MONTHLY', byday: 'MO', bysetpos: 3, }, ]; const vevents = rrules.map((rrule) => ({ dtstart: dtstartPartDayUTC, rrule: { value: rrule }, })); const expected = vevents.map(() => false); expect(vevents.map((vevent) => getHasConsistentRrule(vevent))).toEqual(expected); }); it('should exclude exdate when checking consistency', () => { const vevent = { dtstart: { value: { year: 2015, month: 8, day: 25, hours: 18, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Paris', }, }, rrule: { value: { freq: 'DAILY', until: { year: 2015, month: 8, day: 30, hours: 16, minutes: 29, seconds: 59, isUTC: true }, }, }, exdate: [ { value: { year: 2015, month: 8, day: 25, hours: 18, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Paris', }, }, ], }; expect(getHasConsistentRrule(vevent)).toEqual(true); }); it('should not care about COUNT = 0', () => { const vevent = { dtstart: { value: { year: 2015, month: 8, day: 25, hours: 18, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Paris', }, }, rrule: { value: { freq: 'DAILY', count: 0, }, }, }; expect(getHasConsistentRrule(vevent)).toEqual(true); }); it('should not care about UNTIL earlier than DTSTART', () => { const vevent = { dtstart: { value: { year: 2015, month: 8, day: 25, hours: 18, minutes: 30, seconds: 0, isUTC: false }, parameters: { tzid: 'Europe/Paris', }, }, rrule: { value: { freq: 'DAILY', until: { year: 2015, month: 8, day: 25, hours: 16, minutes: 0, seconds: 0, isUTC: true }, }, }, }; expect(getHasConsistentRrule(vevent)).toEqual(true); }); });
8,806
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/rrule/rruleEqual.spec.js
import { FREQUENCY } from '../../../lib/calendar/constants'; import { getIsRruleEqual } from '../../../lib/calendar/recurrence/rruleEqual'; const getTest = (a, b, c, result) => ({ a, b, c, result, }); describe('rrule equal', () => { [ getTest({ freq: FREQUENCY.ONCE }, undefined, false, false), getTest({ freq: FREQUENCY.ONCE }, { freq: FREQUENCY.ONCE }, false, true), getTest({ freq: FREQUENCY.ONCE }, { freq: FREQUENCY.WEEKLY }, false, false), getTest( { freq: FREQUENCY.MONTHLY, byday: ['TU', 'MO'], }, { freq: FREQUENCY.MONTHLY, byday: ['MO', 'TU'], }, false, true ), getTest( { freq: FREQUENCY.MONTHLY, byday: ['MO'], }, { freq: FREQUENCY.MONTHLY, byday: 'MO', }, false, false ), getTest( { freq: FREQUENCY.MONTHLY, byday: ['TU', 'MO'], }, { freq: FREQUENCY.WEEKLY, }, false, false ), getTest({ count: 2 }, { count: 2 }, false, true), getTest({ count: 2 }, { count: 3 }, false, false), getTest( { freq: FREQUENCY.WEEKLY, count: 65, }, { freq: FREQUENCY.WEEKLY, count: 65, byday: 'WE', }, false, true ), getTest( { freq: FREQUENCY.WEEKLY, until: { year: 2020, month: 1, day: 1, }, }, { freq: FREQUENCY.WEEKLY, until: { year: 2020, month: 1, day: 2, }, }, false, false ), getTest( { freq: FREQUENCY.WEEKLY, until: { year: 2020, month: 1, day: 1, }, }, { freq: FREQUENCY.WEEKLY, until: { year: 2020, month: 1, day: 1, }, }, false, true ), getTest( { until: { year: 2020, month: 1, day: 1, }, }, { until: { year: 2020, month: 1, day: 1, hours: 12, minutes: 59, seconds: 59, }, }, false, true ), getTest( {}, { until: { year: 2020, month: 1, day: 1, hours: 12, minutes: 59, seconds: 59, }, }, false, false ), getTest( { until: { year: 2020, month: 1, day: 1, hours: 12, minutes: 59, seconds: 59, }, }, {}, false, false ), getTest( { until: { year: 2020, month: 1, day: 1, hours: 12, minutes: 59, seconds: 59, }, }, { until: { year: 2020, month: 1, day: 2, hours: 12, minutes: 59, seconds: 59, }, }, false, false ), getTest( { freq: FREQUENCY.WEEKLY, byday: [1, 2, 3], interval: 2, wkst: 'SU' }, { freq: FREQUENCY.WEEKLY, byday: [1, 2, 3], interval: 2 }, false, false ), getTest( { freq: FREQUENCY.WEEKLY, byday: [1, 2, 3], interval: 2, wkst: 'SU' }, { freq: FREQUENCY.WEEKLY, byday: [1, 2, 3], interval: 2 }, true, true ), getTest({ bymonth: [1, 3, 2] }, { bymonth: [3, 2, 1] }, false, true), getTest({}, { bymonth: [1, 3, 2] }, false, false), getTest({ freq: FREQUENCY.WEEKLY, byday: [1] }, { freq: FREQUENCY.WEEKLY }, false, true), getTest({ freq: FREQUENCY.WEEKLY, byday: [1], bymonth: [8] }, { freq: FREQUENCY.WEEKLY }, false, false), getTest({ freq: FREQUENCY.MONTHLY, bymonthday: [13] }, { freq: FREQUENCY.MONTHLY }, false, true), getTest({ freq: FREQUENCY.MONTHLY, bymonthday: [13], byday: [2] }, { freq: FREQUENCY.MONTHLY }, false, false), getTest({ freq: FREQUENCY.YEARLY, byday: [7], bymonth: [7] }, { freq: FREQUENCY.YEARLY }, false, true), getTest({ freq: FREQUENCY.YEARLY, byday: [7] }, { freq: FREQUENCY.YEARLY }, false, false), ].forEach(({ a, b, c, result }, i) => { it(`is rrule equal for ${i}`, () => { expect(getIsRruleEqual({ value: a }, { value: b }, c)).toEqual(result); }); }); });
8,807
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/rrule/rruleSubset.spec.js
import { FREQUENCY } from '../../../lib/calendar/constants'; import { getIsRruleSubset } from '../../../lib/calendar/recurrence/rruleSubset'; const getTest = (a, b, result) => ({ a, b, result, }); describe('rrule subset', () => { const dummyVevent = { dtstart: { value: { year: 2021, month: 1, day: 6, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, }; const dummyUntil = { value: { year: 2021, month: 1, day: 10, hours: 23, minutes: 59, seconds: 59, isUTC: false }, parameters: { tzid: 'America/New_York' }, }; [ getTest( { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY, count: 10 } } }, { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY } } }, true ), getTest( { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY, interval: 2 } } }, { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY } } }, true ), getTest( { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY, interval: 2, until: dummyUntil } } }, { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY, until: dummyUntil } } }, true ), getTest( { ...dummyVevent, rrule: { value: { freq: FREQUENCY.WEEKLY, byday: ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] } }, }, { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY } } }, true ), getTest( { ...dummyVevent, rrule: { value: { freq: FREQUENCY.WEEKLY, byday: ['WE', 'FR', 'SU'], count: 3 } } }, { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY, interval: 2, count: 3 } } }, true ), getTest( { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY } } }, { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY, count: 10 } } }, false ), getTest( { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY, interval: 2 } } }, { ...dummyVevent, rrule: { value: { freq: FREQUENCY.DAILY, interval: 3 } } }, false ), getTest( { ...dummyVevent, rrule: { value: { freq: FREQUENCY.MONTHLY, byday: 'WE', bysetpos: 1 } } }, { ...dummyVevent, rrule: { value: { freq: FREQUENCY.MONTHLY } } }, false ), getTest( { dtstart: { value: { year: 2020, month: 1, day: 6, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, rrule: { value: { freq: FREQUENCY.WEEKLY, interval: 2, byday: ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'], wkst: 'SU', }, }, }, { dtstart: { value: { year: 2020, month: 1, day: 6, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, rrule: { value: { freq: FREQUENCY.WEEKLY, interval: 2, byday: ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'], }, }, }, false ), ].forEach(({ a, b, result }, i) => { it(`is rrule subset for ${i}`, () => { expect(getIsRruleSubset(a, b)).toEqual(result); }); }); });
8,808
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/rrule/rruleUntil.spec.js
import { FREQUENCY } from '../../../lib/calendar/constants'; import { withRruleUntil } from '../../../lib/calendar/recurrence/rruleUntil'; import { getDateProperty, getDateTimeProperty } from '../../../lib/calendar/vcalConverter'; import { fromLocalDate } from '../../../lib/date/timezone'; const getTest = (name, a, b, result) => ({ name, a, b, result, }); const getUntil = (date) => ({ ...fromLocalDate(date), isUTC: true, }); describe('rrule until', () => { [ getTest( 'ignore non-until', { freq: FREQUENCY.ONCE }, getDateProperty({ year: 2020, month: 1, day: 1, }), { freq: FREQUENCY.ONCE } ), getTest( 'convert from a date-time until to date if start is all day', { freq: FREQUENCY.ONCE, until: getUntil(new Date(2020, 1, 10, 12, 59, 59)), }, getDateProperty({ year: 2020, month: 1, day: 1 }), { freq: FREQUENCY.ONCE, until: { year: 2020, month: 2, day: 10 }, } ), getTest( 'convert from a date until to date-time if start is part-day', { freq: FREQUENCY.ONCE, until: { year: 2020, month: 2, day: 10 }, }, getDateTimeProperty({ year: 2020, month: 1, day: 1, hours: 6, minutes: 12 }, 'Europe/Zurich'), { freq: FREQUENCY.ONCE, until: getUntil(new Date(2020, 1, 10, 22, 59, 59)), } ), getTest( 'convert date-time timezone if start is part-day', { freq: FREQUENCY.ONCE, until: getUntil(new Date(2020, 1, 10, 22, 59, 59)), }, getDateTimeProperty({ year: 2020, month: 1, day: 1, hours: 6, minutes: 12 }, 'UTC'), { freq: FREQUENCY.ONCE, until: getUntil(new Date(2020, 1, 10, 23, 59, 59)), } ), ].forEach(({ name, a, b, result }) => { it(name, () => { expect(withRruleUntil({ value: a }, b)).toEqual({ value: result }); }); }); });
8,809
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/rrule/rruleWkst.spec.js
import withVeventRruleWkst from '../../../lib/calendar/recurrence/rruleWkst'; describe('rrule wkst', () => { it('should apply a wkst if it is relevant (weekly)', () => { const vevent = { component: 'vevent', dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, summary: { value: 'asd', }, rrule: { value: { freq: 'WEEKLY', byday: ['MO'], interval: 2, }, }, }; const newVevent = withVeventRruleWkst(vevent, 0); expect(newVevent).toEqual({ component: 'vevent', dtstart: { value: { year: 2019, month: 7, day: 19, hours: 12, minutes: 0, seconds: 0, isUTC: false }, parameters: { tzid: 'America/New_York' }, }, summary: { value: 'asd', }, rrule: { value: { freq: 'WEEKLY', byday: ['MO'], interval: 2, wkst: 'SU', }, }, }); }); it('should apply a wkst if it is relevant (yearly)', () => { const vevent = { component: 'vevent', rrule: { value: { freq: 'YEARLY', byweekno: 1, }, }, }; const newVevent = withVeventRruleWkst(vevent, 0); expect(newVevent).toEqual({ component: 'vevent', rrule: { value: { freq: 'YEARLY', byweekno: 1, wkst: 'SU', }, }, }); }); it('should not apply a wkst if it is the default value', () => { const vevent = { component: 'vevent', rrule: { value: { freq: 'WEEKLY', byday: ['MO'], interval: 2, }, }, }; const newVevent = withVeventRruleWkst(vevent, 1); expect(newVevent.rrule.value).toEqual({ freq: 'WEEKLY', byday: ['MO'], interval: 2, }); }); it('should not apply a wkst if it is not needed', () => { const vevent = { component: 'vevent', rrule: { value: { freq: 'WEEKLY', interval: 2, }, }, }; const newVevent = withVeventRruleWkst(vevent, 0); expect(newVevent.rrule.value.wkst).toBeUndefined(); }); it('should not apply a wkst if it is not needed #2', () => { const vevent = { component: 'vevent', rrule: { value: { freq: 'WEEKLY', }, }, }; const newVevent = withVeventRruleWkst(vevent, 0); expect(newVevent.rrule.value.wkst).toBeUndefined(); }); it('should remove wkst if it is not relevant', () => { const vevent = { component: 'vevent', rrule: { value: { freq: 'WEEKLY', byday: ['MO'], interval: 2, wkst: 'SU', }, }, }; const newVevent = withVeventRruleWkst(vevent, 1); expect(newVevent.rrule.value).toEqual({ freq: 'WEEKLY', byday: ['MO'], interval: 2, }); }); });
8,810
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/shareUrl/purpose.spec.ts
import { CryptoProxy } from '@proton/crypto'; import { MAX_CHARS_CLEARTEXT } from '@proton/shared/lib/calendar/constants'; import { disableRandomMock, initRandomMock } from '@proton/testing/lib/mockRandomValues'; import { generateEncryptedPurpose } from '../../../lib/calendar/sharing/shareUrl/shareUrl'; import { DecryptableKey } from '../../keys/keys.data'; const generateAsciiString = (n: number) => { const char = 'a'; let result = ''; for (let i = 0; i < n; i++) { result += char; } return result; }; const generateUcsString = (n: number) => { const emoji = '😊'; let result = ''; for (let i = 0; i < n; i++) { result += emoji; } return result; }; describe('getEncryptedPurpose', () => { beforeAll(() => initRandomMock()); afterAll(() => disableRandomMock()); it('Generates an encrypted purpose within the API bounds', async () => { const calendarKey = await CryptoProxy.importPrivateKey({ armoredKey: DecryptableKey.PrivateKey, passphrase: '123', }); const { PURPOSE: maxChars } = MAX_CHARS_CLEARTEXT; const purpose = generateUcsString(maxChars / 2); // JS uses UTF-16 expect(purpose.length).toEqual(maxChars); // API limit on the encrypted purpose is 2000 characters expect((await generateEncryptedPurpose({ purpose, publicKey: calendarKey })).length).toBeLessThan(2000); // On ASCII characters we could encode longer strings expect( ( await generateEncryptedPurpose({ purpose: generateAsciiString(maxChars * 2), publicKey: calendarKey, }) ).length ).toBeLessThan(2000); }); });
8,811
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/sharing
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/sharing/shareProton/shareProton.spec.ts
import { MEMBER_PERMISSIONS } from '@proton/shared/lib/calendar/permissions'; import { getSharedCalendarSubHeaderText } from '@proton/shared/lib/calendar/sharing/shareProton/shareProton'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; describe('shareProton', () => { describe('getSharedCalendarSubHeaderText', () => { const baseCalendar = { Name: 'Testing calendar', Type: 0, Owner: { Email: '[email protected]', }, Members: [ { Email: '[email protected]', Name: 'My calendar', }, ], Email: '[email protected]', } as VisualCalendar; it('should return undefined when calendar is not a shared one', () => { expect( getSharedCalendarSubHeaderText( { ...baseCalendar, Owner: { Email: '[email protected]', }, }, {} ) ).toBeUndefined(); }); it('should return good sub header when calendar is writable', () => { expect( getSharedCalendarSubHeaderText( { ...baseCalendar, Permissions: MEMBER_PERMISSIONS.EDIT, }, {} ) ).toEqual('Shared by [email protected]'); }); it('should return good sub header when calendar is only readable', () => { expect( getSharedCalendarSubHeaderText( { ...baseCalendar, Permissions: MEMBER_PERMISSIONS.FULL_VIEW, }, {} ) ).toEqual('Shared by [email protected]'); }); }); });
8,812
0
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/test/calendar/subscribe/helpers.spec.ts
import { CALENDAR_TYPE } from '../../../lib/calendar/constants'; import { getCalendarIsNotSyncedInfo, getNotSyncedInfo, getSyncingInfo } from '../../../lib/calendar/subscribe/helpers'; import { HOUR } from '../../../lib/constants'; import { CALENDAR_SUBSCRIPTION_STATUS, VisualCalendar } from '../../../lib/interfaces/calendar'; const { OK, INVALID_ICS, ICS_SIZE_EXCEED_LIMIT, SYNCHRONIZING, HTTP_REQUEST_FAILED_BAD_REQUEST, HTTP_REQUEST_FAILED_UNAUTHORIZED, HTTP_REQUEST_FAILED_FORBIDDEN, HTTP_REQUEST_FAILED_NOT_FOUND, HTTP_REQUEST_FAILED_GENERIC, HTTP_REQUEST_FAILED_INTERNAL_SERVER_ERROR, HTTP_REQUEST_FAILED_TIMEOUT, CALENDAR_MISSING_PRIMARY_KEY, INTERNAL_CALENDAR_URL_NOT_FOUND, INTERNAL_CALENDAR_UNDECRYPTABLE, } = CALENDAR_SUBSCRIPTION_STATUS; describe('getSyncingInfo', () => { it('passes an object with the correct label and text', () => { expect(getSyncingInfo('dog')).toEqual({ label: 'Syncing', text: 'dog', longText: 'dog.', isSyncing: true }); }); }); describe('getNotSyncedInfo', () => { it('passes an object with the correct label and text', () => { expect(getNotSyncedInfo('dog')).toEqual({ label: 'Not synced', text: 'dog', longText: 'dog.', isSyncing: false, }); }); }); describe('getCalendarIsNotSyncedInfo', () => { beforeEach(() => { jasmine.clock().install(); }); afterEach(() => { jasmine.clock().uninstall(); }); it('returns the correct message based on the status', () => { const mockDate = new Date(2020, 11, 11, 0, 0, 0); jasmine.clock().mockDate(mockDate); const calendarCommon: VisualCalendar = { ID: 'calendarID', Name: 'calendarName', Description: 'calendarDescription', Email: 'calendarEmail', Display: 1, Color: '#f00', Flags: 1, Permissions: 127, Type: CALENDAR_TYPE.SUBSCRIPTION, Owner: { Email: 'calendarEmail' }, Priority: 1, Members: [], }; const calendarSubscriptionCommon = { CalendarID: calendarCommon.ID, CreateTime: 0, LastUpdateTime: mockDate.getTime() / 1000 + 1000, URL: 'okCalendarURL', }; const getCommonCalendarWithStatus = (status: CALENDAR_SUBSCRIPTION_STATUS) => ({ ...calendarCommon, SubscriptionParameters: { ...calendarSubscriptionCommon, Status: status, }, }); const notSyncedYetCalendar = { ...calendarCommon, SubscriptionParameters: { ...calendarSubscriptionCommon, LastUpdateTime: 0, Status: OK, }, }; const syncPeriodTooLongCalendar = { ...calendarCommon, SubscriptionParameters: { ...calendarSubscriptionCommon, LastUpdateTime: calendarSubscriptionCommon.LastUpdateTime - 12 * HOUR, Status: OK, }, }; expect(getCalendarIsNotSyncedInfo(notSyncedYetCalendar)).toEqual( getSyncingInfo( 'Calendar is syncing', 'Calendar is syncing: it may take several minutes for all of its events to show up.' ) ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(OK))).toBe(undefined); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(9999 as unknown as any))).toEqual( getNotSyncedInfo('Failed to sync calendar') ); [ OK, INVALID_ICS, ICS_SIZE_EXCEED_LIMIT, SYNCHRONIZING, HTTP_REQUEST_FAILED_BAD_REQUEST, HTTP_REQUEST_FAILED_UNAUTHORIZED, HTTP_REQUEST_FAILED_FORBIDDEN, HTTP_REQUEST_FAILED_NOT_FOUND, HTTP_REQUEST_FAILED_GENERIC, HTTP_REQUEST_FAILED_INTERNAL_SERVER_ERROR, HTTP_REQUEST_FAILED_TIMEOUT, INTERNAL_CALENDAR_URL_NOT_FOUND, INTERNAL_CALENDAR_UNDECRYPTABLE, CALENDAR_MISSING_PRIMARY_KEY, ].forEach((status) => expect( getCalendarIsNotSyncedInfo({ ...syncPeriodTooLongCalendar, SubscriptionParameters: { ...syncPeriodTooLongCalendar.SubscriptionParameters, Status: status, }, }) ).toEqual( getNotSyncedInfo( 'More than 12 hours passed since last update', 'More than 12 hours passed since last update — Proton Calendar will try to update the calendar in a few hours.' ) ) ); expect( getCalendarIsNotSyncedInfo({ ...syncPeriodTooLongCalendar, SubscriptionParameters: { ...syncPeriodTooLongCalendar.SubscriptionParameters, LastUpdateTime: syncPeriodTooLongCalendar.SubscriptionParameters.LastUpdateTime + 12 * HOUR + 1, }, }) ).toBe(undefined); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(INVALID_ICS))).toEqual( getNotSyncedInfo('Unsupported calendar format') ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(ICS_SIZE_EXCEED_LIMIT))).toEqual( getNotSyncedInfo('Calendar is too big') ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(SYNCHRONIZING))).toEqual( getSyncingInfo( 'Calendar is syncing', 'Calendar is syncing: it may take several minutes for all of its events to show up.' ) ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(HTTP_REQUEST_FAILED_BAD_REQUEST))).toEqual( getNotSyncedInfo( 'Calendar link is not accessible', "Calendar link is not accessible from outside the calendar provider's ecosystem." ) ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(HTTP_REQUEST_FAILED_UNAUTHORIZED))).toEqual( getNotSyncedInfo( 'Calendar link is not accessible', "Calendar link is not accessible from outside the calendar provider's ecosystem." ) ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(HTTP_REQUEST_FAILED_FORBIDDEN))).toEqual( getNotSyncedInfo( 'Calendar link is not accessible', "Calendar link is not accessible from outside the calendar provider's ecosystem." ) ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(HTTP_REQUEST_FAILED_NOT_FOUND))).toEqual( getNotSyncedInfo( 'Calendar link is not accessible', "Calendar link is not accessible from outside the calendar provider's ecosystem." ) ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(INTERNAL_CALENDAR_URL_NOT_FOUND))).toEqual( getNotSyncedInfo( 'Calendar link is not accessible', "Calendar link is not accessible from outside the calendar provider's ecosystem." ) ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(HTTP_REQUEST_FAILED_GENERIC))).toEqual( getNotSyncedInfo( 'Calendar link is temporarily inaccessible', 'Calendar link is temporarily inaccessible. Please verify that the link from the calendar provider is still valid.' ) ); expect( getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(HTTP_REQUEST_FAILED_INTERNAL_SERVER_ERROR)) ).toEqual( getNotSyncedInfo( 'Calendar link is temporarily inaccessible', 'Calendar link is temporarily inaccessible. Please verify that the link from the calendar provider is still valid.' ) ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(HTTP_REQUEST_FAILED_TIMEOUT))).toEqual( getNotSyncedInfo( 'Calendar link is temporarily inaccessible', 'Calendar link is temporarily inaccessible. Please verify that the link from the calendar provider is still valid.' ) ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(INTERNAL_CALENDAR_UNDECRYPTABLE))).toEqual( getNotSyncedInfo('Calendar could not be decrypted') ); expect(getCalendarIsNotSyncedInfo(getCommonCalendarWithStatus(CALENDAR_MISSING_PRIMARY_KEY))).toEqual( getNotSyncedInfo('Failed to sync calendar') ); }); });
8,813
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/contacts/address.spec.ts
import { cleanAddressFromCommas } from '@proton/shared/lib/contacts/helpers/address'; import { VCardAddress } from '@proton/shared/lib/interfaces/contacts/VCard'; describe('contact address helpers', () => { describe('cleanAddressFromCommas', () => { it('should clean commas from address fields', () => { const address: VCardAddress = { streetAddress: 'streetAddress', extendedAddress: ',,,something, somewhere,,', postalCode: '000', postOfficeBox: ',,something,somewhere,Geneva,000,,,,,,', locality: ',locality,', region: ',,,Geneva', country: 'Switzerland,,,', }; const expectedAddress: VCardAddress = { streetAddress: 'streetAddress', extendedAddress: 'something, somewhere', postalCode: '000', postOfficeBox: 'something,somewhere,Geneva,000', locality: 'locality', region: 'Geneva', country: 'Switzerland', }; expect(cleanAddressFromCommas(address)).toEqual(expectedAddress); }); }); });
8,814
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/contacts/contactEmail.spec.ts
import { getContactDisplayNameEmail } from '@proton/shared/lib/contacts/contactEmail'; describe('getContactDisplayNameEmail', () => { it('displays the email when no name is passed', () => { expect(getContactDisplayNameEmail({ email: '[email protected]' })).toEqual({ nameEmail: '[email protected]', displayOnlyEmail: true, }); }); it('displays name and email for a "typical" contact', () => { expect(getContactDisplayNameEmail({ name: 'My dummy friend', email: '[email protected]' })).toEqual({ nameEmail: 'My dummy friend <[email protected]>', displayOnlyEmail: false, }); }); it('should use different delimiters', () => { expect( getContactDisplayNameEmail({ name: 'My dummy friend', email: '[email protected]', emailDelimiters: ['(', ')'], }) ).toEqual({ nameEmail: 'My dummy friend ([email protected])', displayOnlyEmail: false, }); }); it('should not repeat name and email', () => { expect(getContactDisplayNameEmail({ name: '[email protected]', email: '[email protected]' })).toEqual({ nameEmail: '[email protected]', displayOnlyEmail: true, }); }); it('should normalize when comparing name and email', () => { expect(getContactDisplayNameEmail({ name: '[email protected] ', email: '[email protected]' })).toEqual( { nameEmail: '[email protected]', displayOnlyEmail: true, } ); }); });
8,815
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/contacts/contactGroups.spec.ts
import { getContactGroupsDelayedSaveChanges } from '@proton/shared/lib/contacts/helpers/contactGroup'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { MAX_RECIPIENTS } from '@proton/shared/lib/mail/mailSettings'; const group1 = 'group1'; const getUserContactEmails = (numberOfContacts: number) => { const contactEmails: ContactEmail[] = []; for (let i = 0; i < numberOfContacts; i++) { const contact = { ID: `contact${i}`, Email: `email${i}@pm.me`, LabelIDs: [group1] } as ContactEmail; contactEmails.push(contact); } return contactEmails; }; const initialModel = { group1: 0, }; const model = { group1: 1, }; const changes = { group1: true, }; const onLimitReached = jasmine.createSpy(); describe('contactGroups', () => { describe('getContactGroupsDelayedSaveChanges', () => { it('should be possible to add the contact to the contact group', () => { const userContactEmails = getUserContactEmails(99); const updatedChanges = getContactGroupsDelayedSaveChanges({ userContactEmails, changes, initialModel, model, onLimitReached, mailSettings: { RecipientLimit: MAX_RECIPIENTS } as MailSettings, }); expect(updatedChanges).toEqual(changes); }); }); describe('getContactGroupsDelayedSaveChanges', () => { it('should not be possible to add the contact to the contact group', () => { const userContactEmails = getUserContactEmails(100); const updatedChanges = getContactGroupsDelayedSaveChanges({ userContactEmails, changes, initialModel, model, onLimitReached, mailSettings: {} as MailSettings, }); expect(updatedChanges).toEqual({}); expect(onLimitReached).toHaveBeenCalled(); }); }); });
8,816
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/contacts/csv.spec.ts
import { toVCardContacts } from '@proton/shared/lib/contacts/helpers/csv'; import { fromVCardProperties, getVCardProperties } from '@proton/shared/lib/contacts/properties'; import { PreVcardProperty, PreVcardsContact } from '@proton/shared/lib/interfaces/contacts'; import { VCardContact, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; const excludeFieldsForVerification = (contacts: VCardContact[]) => { return contacts.map((contact) => { const properties = getVCardProperties(contact).map(({ uid, params, ...property }) => property); return fromVCardProperties(properties as VCardProperty[]); }); }; describe('csv', () => { describe('toVCardContacts', () => { it('should convert to a vCardContact', () => { const contact1: PreVcardsContact = [ [{ header: 'Given name', value: 'Contact Name', field: 'fn', checked: true } as PreVcardProperty], [{ header: 'Email', value: '[email protected]', field: 'email', checked: true } as PreVcardProperty], ]; const contact2: PreVcardsContact = [ [{ header: 'Given name', value: 'Contact Name 2', field: 'fn', checked: true } as PreVcardProperty], [{ header: 'Email', value: '[email protected]', field: 'email', checked: true } as PreVcardProperty], ]; const prevCardsContacts: PreVcardsContact[] = [contact1, contact2]; const expected: VCardContact[] = [ { fn: [{ field: 'fn', value: 'Contact Name', uid: '' }], email: [{ field: 'email', value: '[email protected]', group: 'item1', uid: '' }], }, { fn: [{ field: 'fn', value: 'Contact Name 2', uid: '' }], email: [{ field: 'email', value: '[email protected]', group: 'item1', uid: '' }], }, ]; const res = excludeFieldsForVerification(toVCardContacts(prevCardsContacts).rest); expect(res).toEqual(excludeFieldsForVerification(expected)); }); it('should convert to a vCardContact and add email as FN when no FN', () => { const contact1: PreVcardsContact = [ [{ header: 'Email', value: '[email protected]', field: 'email', checked: true } as PreVcardProperty], ]; const contact2: PreVcardsContact = [ [{ header: 'Given name', value: 'Contact Name 2', field: 'fn', checked: true } as PreVcardProperty], [{ header: 'Email', value: '[email protected]', field: 'email', checked: true } as PreVcardProperty], ]; const prevCardsContacts: PreVcardsContact[] = [contact1, contact2]; const expected: VCardContact[] = [ { fn: [{ field: 'fn', value: '[email protected]', uid: '' }], email: [{ field: 'email', value: '[email protected]', group: 'item1', uid: '' }], }, { fn: [{ field: 'fn', value: 'Contact Name 2', uid: '' }], email: [{ field: 'email', value: '[email protected]', group: 'item1', uid: '' }], }, ]; const res = excludeFieldsForVerification(toVCardContacts(prevCardsContacts).rest); expect(res).toEqual(excludeFieldsForVerification(expected)); }); it('should throw an error when contact has no FN and no email, and import the rest', () => { const contact1: PreVcardsContact = []; const contact2: PreVcardsContact = [ [{ header: 'Given name', value: 'Contact Name 2', field: 'fn', checked: true } as PreVcardProperty], [{ header: 'Email', value: '[email protected]', field: 'email', checked: true } as PreVcardProperty], ]; const prevCardsContacts: PreVcardsContact[] = [contact1, contact2]; const expected: VCardContact[] = [ { fn: [{ field: 'fn', value: 'Contact Name 2', uid: '' }], email: [{ field: 'email', value: '[email protected]', group: 'item1', uid: '' }], }, ]; const { errors, rest } = toVCardContacts(prevCardsContacts); const res = excludeFieldsForVerification(rest); expect(res).toEqual(excludeFieldsForVerification(expected)); expect(errors.length).toEqual(1); }); }); });
8,817
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/contacts/import.spec.ts
import { parseISO } from 'date-fns'; import { ImportContactError } from '../../lib/contacts/errors/ImportContactError'; import { extractContactImportCategories, getContactId, getImportCategories, getSupportedContact, naiveExtractPropertyValue, } from '../../lib/contacts/helpers/import'; import { fromVCardProperties, getVCardProperties } from '../../lib/contacts/properties'; import { extractVcards } from '../../lib/contacts/vcard'; import { toCRLF } from '../../lib/helpers/string'; import { ContactMetadata, EncryptedContact, ImportedContact } from '../../lib/interfaces/contacts'; import { VCardContact, VCardProperty } from '../../lib/interfaces/contacts/VCard'; const excludeUids = (contact: VCardContact | ImportContactError) => { if (contact instanceof ImportContactError) { return undefined; } const properties = getVCardProperties(contact).map(({ uid, ...property }) => property); return fromVCardProperties(properties as VCardProperty[]); }; describe('import', () => { describe('extract vcards', () => { it('should keep the line separator used in the vcard', () => { const vcardsPlain = `BEGIN:VCARD VERSION:4.0 FN:One END:VCARD BEGIN:VCARD VERSION:4.0 FN:Two END:VCARD`; const vcardsCRLF = toCRLF(vcardsPlain); expect(extractVcards(vcardsPlain)).toEqual([ 'BEGIN:VCARD\nVERSION:4.0\nFN:One\nEND:VCARD', 'BEGIN:VCARD\nVERSION:4.0\nFN:Two\nEND:VCARD', ]); expect(extractVcards(vcardsCRLF)).toEqual([ 'BEGIN:VCARD\r\nVERSION:4.0\r\nFN:One\r\nEND:VCARD', 'BEGIN:VCARD\r\nVERSION:4.0\r\nFN:Two\r\nEND:VCARD', ]); }); it('extracts vcards separated by empty lines', () => { const vcardsPlain = `BEGIN:VCARD VERSION:4.0 FN:One END:VCARD BEGIN:VCARD VERSION:4.0 FN:Two END:VCARD `; expect(extractVcards(vcardsPlain)).toEqual([ 'BEGIN:VCARD\nVERSION:4.0\nFN:One\nEND:VCARD', 'BEGIN:VCARD\nVERSION:4.0\nFN:Two\nEND:VCARD', ]); }); }); describe('naiveExtractPropertyValue', () => { const vcard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN;PID=1.1:J. Doe N:Doe;J.;;; BDAY: EMAIL;PID=1.1:[email protected] CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556 NOTE:This is a long descrip tion that exists o n a long line. END:VCARD`; it('should return undefined when the property is not present', () => { expect(naiveExtractPropertyValue(vcard, 'CATEGORIES')).toBeUndefined(); }); it('should return the empty string when the property has no value', () => { expect(naiveExtractPropertyValue(vcard, 'BDAY')).toEqual(''); }); it('should extract values as expected with and without parameters', () => { expect(naiveExtractPropertyValue(vcard, 'UID')).toEqual('urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1'); expect(naiveExtractPropertyValue(vcard, 'email')).toEqual('[email protected]'); expect(naiveExtractPropertyValue(vcard, 'version')).toEqual('4.0'); }); it('should extract folded values', () => { expect(naiveExtractPropertyValue(vcard, 'NOTE')).toEqual( 'This is a long description that exists on a long line.' ); }); }); describe('getContactId', () => { it('should retrieve FN value whenever present', () => { expect( getContactId(`BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN;PID=1.1:J. Doe N:Doe;J.;;; EMAIL;PID=1.1:[email protected] CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556 END:VCARD`) ).toEqual('J. Doe'); expect( getContactId(`BEGIN:VCARD VERSION:4.0 FN:Simon Perreault N:Perreault;Simon;;;ing. jr,M.Sc. BDAY:--0203 ANNIVERSARY:20090808T1430-0500 GENDER:M LANG;PREF=1:fr LANG;PREF=2:en ORG;TYPE=work:Viagenie ADR;TYPE=work:;Suite D2-630;2875 Laurier; Quebec;QC;G1V 2M2;Canada TEL;VALUE=uri;TYPE="work,voice";PREF=1:tel:+1-418-656-9254;ext=102 TEL;VALUE=uri;TYPE="work,cell,voice,video,text":tel:+1-418-262-6501 EMAIL;TYPE=work:[email protected] GEO;TYPE=work:geo:46.772673,-71.282945 KEY;TYPE=work;VALUE=uri: http://www.viagenie.ca/simon.perreault/simon.asc TZ:-0500 URL;TYPE=home:http://nomis80.org END:VCARD`) ).toEqual('Simon Perreault'); }); it('should retrieve FN when multiple lines are present', () => { expect( getContactId(`BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3 -424c-9c26-36 c3e1eff6b1 FN;PID=1.1:Joh nnie Do e N:Doe;J.;;; EMAIL;PID=1.1:[email protected] CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556 END:VCARD`) ).toEqual('Johnnie Doe'); }); it('should crop FN when too long', () => { expect( getContactId(`BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3 -424c-9c26-36 c3e1eff6b1 FN;PID=1.1:This contact has a very loo ong name, but that's a pity since no one will remember such a long one N:Doe;J.;;; EMAIL;PID=1.1:[email protected] CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556 END:VCARD`) ).toEqual('This contact has a very looong name, bu…'); }); }); describe('extractCategories', () => { it('should pick the right contactEmail ids for a contact with categories', () => { const contact = { ID: 'contact', ContactEmails: [ { ID: 'one', Email: '[email protected]', }, { ID: 'two', Email: '[email protected]', }, { ID: 'three', Email: '[email protected]', }, ], } as ContactMetadata; const encryptedContact = { contactEmails: [ { email: '[email protected]', group: 'item1' }, { email: '[email protected]', group: 'item2' }, { email: '[email protected]', group: 'item3' }, ], categories: [ { name: 'dogs', group: 'item1' }, { name: 'cats', group: 'item2' }, { name: 'cats', group: 'item3' }, { name: 'pets', group: 'item2' }, { name: 'all' }, ], } as EncryptedContact; const result = [ { name: 'dogs', contactEmailIDs: ['one'] }, { name: 'cats', contactEmailIDs: ['two', 'three'] }, { name: 'pets', contactEmailIDs: ['two'] }, { name: 'all', contactEmailIDs: ['one', 'two', 'three'] }, ]; expect(extractContactImportCategories(contact, encryptedContact)).toEqual(result); }); }); it('should pick the right contactEmail ids for a contact with categories', () => { const contact = { ID: 'contact', ContactEmails: [ { ID: 'one', Email: '[email protected]', }, { ID: 'two', Email: '[email protected]', }, { ID: 'three', Email: '[email protected]', }, ], } as ContactMetadata; const encryptedContact = { contactEmails: [ { email: '[email protected]', group: 'item1' }, { email: '[email protected]', group: 'item2' }, { email: '[email protected]', group: 'item3' }, ], categories: [], } as unknown as EncryptedContact; expect(extractContactImportCategories(contact, encryptedContact)).toEqual([]); }); describe('getImportCategories', () => { it('should combine contact email ids and contact ids from different contacts', () => { const contacts: ImportedContact[] = [ { contactID: 'contact1', contactEmailIDs: ['contactemail1-1', 'contactemail1-2'], categories: [ { name: 'cats', contactEmailIDs: ['contactemail1-1', 'contactemail1-2'] }, { name: 'dogs', contactEmailIDs: ['contactemail1-1'] }, { name: 'pets' }, ], }, { contactID: 'contact2', contactEmailIDs: [], categories: [{ name: 'dogs' }, { name: 'birds' }], }, { contactID: 'contact3', contactEmailIDs: ['contactemail3-1', 'contactemail3-2'], categories: [ { name: 'all' }, { name: 'dogs', contactEmailIDs: ['contactemail3-1'] }, { name: 'pets', contactEmailIDs: ['contactemail3-2'] }, ], }, ]; const result = [ { name: 'cats', contactEmailIDs: [], contactIDs: ['contact1'], totalContacts: 1, }, { name: 'dogs', contactEmailIDs: ['contactemail1-1', 'contactemail3-1'], contactIDs: [], totalContacts: 2, }, { name: 'pets', contactEmailIDs: ['contactemail3-2'], contactIDs: [], totalContacts: 1 }, ]; expect(getImportCategories(contacts)).toEqual(result); }); }); describe('getSupportedContacts', () => { const getExpectedProperties = (withLineBreaks = false): VCardContact => { return { fn: [{ field: 'fn', value: 'Name', params: { pref: '1' }, uid: '' }], version: { field: 'version', value: '4.0', uid: '' }, adr: [ { field: 'adr', value: { postOfficeBox: '', extendedAddress: '', streetAddress: withLineBreaks ? 'street with line breaks' : 'street', locality: 'city', region: '', postalCode: '00000', country: 'FR', }, uid: '', }, ], org: [{ field: 'org', value: { organizationalName: 'company' }, uid: '' }], bday: { field: 'bday', value: { date: parseISO('1999-01-01') }, uid: '' }, note: [{ field: 'note', value: 'Notes', uid: '' }], email: [ { field: 'email', value: '[email protected]', params: { pref: '1' }, group: 'item1', uid: '' }, ], tel: [{ field: 'tel', value: '00 00000000', params: { pref: '1' }, uid: '' }], title: [{ field: 'title', value: 'title', uid: '' }], }; }; it('should import normal vCard correctly', () => { const vCard = `BEGIN:VCARD VERSION:4.0 ADR:;;street;city;;00000;FR ORG:company BDAY:19990101 NOTE:Notes TEL;PREF=1:00 00000000 TITLE:title FN;PREF=1:Name ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`; const expected = getExpectedProperties(); const contact = getSupportedContact(vCard); expect(excludeUids(contact)).toEqual(excludeUids(expected)); }); it('should import vCard with address containing \\r\\n correctly', () => { const vCard = `BEGIN:VCARD VERSION:4.0 ADR:;;street\\r\\nwith\\r\\nline\\r\\nbreaks;city;;00000;FR ORG:company BDAY:19990101 NOTE:Notes TEL;PREF=1:00 00000000 TITLE:title FN;PREF=1:Name ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`; const expected = getExpectedProperties(true); const contact = getSupportedContact(vCard); expect(excludeUids(contact)).toEqual(excludeUids(expected)); }); it('should import vCard with address containing \\\\n correctly', () => { const vCard = `BEGIN:VCARD VERSION:4.0 ADR:;;street\\nwith\\nline\\nbreaks;city;;00000;FR ORG:company BDAY:19990101 NOTE:Notes TEL;PREF=1:00 00000000 TITLE:title FN;PREF=1:Name ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`; const expected = getExpectedProperties(true); const contact = getSupportedContact(vCard); expect(excludeUids(contact)).toEqual(excludeUids(expected)); }); }); it('should import BDAY and ANNIVERSARY', () => { const vCard = `BEGIN:VCARD VERSION:4.0 FN:Name BDAY:19990101 ANNIVERSARY:19990101 END:VCARD`; const expected: VCardContact = { fn: [{ field: 'fn', value: 'Name', uid: '' }], version: { field: 'version', value: '4.0', uid: '' }, bday: { field: 'bday', value: { date: parseISO('1999-01-01') }, uid: '' }, anniversary: { field: 'anniversary', value: { date: parseISO('1999-01-01') }, uid: '' }, }; const contact = getSupportedContact(vCard); expect(excludeUids(contact)).toEqual(excludeUids(expected)); }); it('should import BDAY and ANNIVERSARY with text format', () => { const vCard = `BEGIN:VCARD VERSION:4.0 FN:Name BDAY;VALUE=text:bidet ANNIVERSARY;VALUE=text:annie END:VCARD`; const expected: VCardContact = { fn: [{ field: 'fn', value: 'Name', uid: '' }], version: { field: 'version', value: '4.0', uid: '' }, bday: { field: 'bday', value: { text: 'bidet' }, params: { type: 'text' }, uid: '' }, anniversary: { field: 'anniversary', value: { text: 'annie' }, params: { type: 'text' }, uid: '' }, }; const contact = getSupportedContact(vCard); expect(excludeUids(contact)).toEqual(excludeUids(expected)); }); it('should import the contact using email as FN when no FN specified', () => { const vCard = `BEGIN:VCARD VERSION:4.0 ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`; const expected: VCardContact = { fn: [{ field: 'fn', value: '[email protected]', uid: '' }], version: { field: 'version', value: '4.0', uid: '' }, email: [{ field: 'email', value: '[email protected]', params: { pref: '1' }, group: 'item1', uid: '' }], }; const contact = getSupportedContact(vCard); expect(excludeUids(contact)).toEqual(excludeUids(expected)); }); it(`should not import a contact with a missing FN for which we can't find an alternative`, () => { const vCard = `BEGIN:VCARD VERSION:4.0 CATEGORIES:MISSING_FN,MISSING_EMAIL BDAY:20000505 END:VCARD`; expect(() => getSupportedContact(vCard)).toThrowError('Missing FN property'); }); it(`should not import a contact with version 2.1`, () => { const vCard = `BEGIN:VCARD VERSION:2.1 N:Gump;Forrest;;Mr. FN:Forrest Gump ORG:Bubba Gump Shrimp Co. TITLE:Shrimp Man TEL;WORK;VOICE:(111) 555-1212 TEL;HOME;VOICE:(404) 555-1212 ADR;WORK;PREF:;;100 Waters Edge;Baytown;LA;30314;United States of America LABEL;WORK;PREF;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:100 Waters Edge=0D= =0ABaytown\\, LA 30314=0D=0AUnited States of America ADR;HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America LABEL;HOME;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:42 Plantation St.=0D=0A= Baytown, LA 30314=0D=0AUnited States of America PHOTO;GIF:http://www.example.com/dir_photos/my_photo.gif EMAIL:[email protected] REV:20080424T195243Z END:VCARD`; expect(() => getSupportedContact(vCard)).toThrowError('vCard versions < 3.0 not supported'); }); });
8,818
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/contacts/merge.spec.ts
import { extractMergeable } from '@proton/shared/lib/contacts/helpers/merge'; import { FormattedContact } from '@proton/shared/lib/interfaces/contacts/FormattedContact'; type TestContact = Pick<FormattedContact, 'Name' | 'emails'>; /** * Check if two contacts match * @dev For this test, for contact equality it's enough to check that the 'Name' and 'emails' properties match */ const doContactsMatch = (contactLeft: TestContact, contactRight: TestContact) => { const { Name: nameLeft, emails: emailsLeft } = contactLeft; const { Name: nameRight, emails: emailsRight } = contactRight; if (nameLeft !== nameRight) { return false; } return emailsLeft.length === emailsRight.length && emailsLeft.every((email, i) => email === emailsRight[i]); }; /** * Check if two arrays of contacts contain the same list of contacts, possibly in a different order */ const doContactListsMatch = (contactsLeft: TestContact[], contactsRight: TestContact[]) => { const differentContactsRight = [...contactsRight]; for (const contactLeft of contactsLeft) { const index = differentContactsRight.findIndex((contact) => doContactsMatch(contact, contactLeft)); if (index === -1) { return false; } differentContactsRight.splice(index, 1); } return !differentContactsRight.length; }; /** * Check if two arrays of contacts lists match, possibly in a different order */ const doContactListArraysMatch = (contactListsLeft: TestContact[][], contactListsRight: TestContact[][]) => { const differentContactListsRight = [...contactListsRight]; for (const contactListLeft of contactListsLeft) { const index = differentContactListsRight.findIndex((contactList) => doContactListsMatch(contactList, contactListLeft) ); if (index === -1) { return false; } differentContactListsRight.splice(index, 1); } return !differentContactListsRight.length; }; describe('merge', () => { describe('extractMergeable', () => { it('should detect as mergeable multiple contacts with the same normalized name and same normalized email', () => { // only names and emails are relevant for the logic of extractMergeable const contacts = [ { Name: 'TestName', emails: ['[email protected]', '[email protected]'] }, { Name: 'Someone else', emails: ['[email protected]'] }, { Name: 'TESTNAME', emails: ['[email protected]'] }, { Name: 'testname', emails: ['[email protected]'] }, { Name: 'Party crasher', emails: ['[email protected]'] }, { Name: 'TestEmail', emails: ['[email protected]', '[email protected]'] }, { Name: 'Another one', emails: ['[email protected]'] }, { Name: 'I am testing email', emails: ['[email protected]'] }, { Name: 'Party crasher friend 1', emails: ['[email protected]'] }, { Name: 'Party crasher friend 2', emails: ['[email protected]'] }, { Name: 'A final email test', emails: ['[email protected]', '[email protected]'] }, ] as FormattedContact[]; const mergeableContacts = extractMergeable(contacts); const expectedMergeableContacts = [ // mergeable by name [contacts[0], contacts[2], contacts[3]], // mergeable by email [contacts[5], contacts[7], contacts[10]], ]; expect(doContactListArraysMatch(mergeableContacts, expectedMergeableContacts)).toEqual(true); }); it('should detect as mergeable two contacts with different names and emails, but which share a name and an email with a third one', () => { // only names and emails are relevant for the logic of extractMergeable const contacts = [ { Name: 'First', emails: ['[email protected]'] }, { Name: 'Second', emails: ['[email protected]', '[email protected]'] }, { Name: 'second', emails: ['[email protected]'] }, ] as FormattedContact[]; const mergeableContacts = extractMergeable(contacts); expect(doContactListArraysMatch(mergeableContacts, [contacts])).toEqual(true); }); it('should not detect as mergeable two contacts with unknown names added by Proton', () => { // only names and emails are relevant for the logic of extractMergeable const contacts = [ { Name: 'Unknown', emails: ['[email protected]'] }, { Name: 'Unknown', emails: ['[email protected]', '[email protected]'] }, { Name: '<Unknown>', emails: ['[email protected]'] }, { Name: '<Unknown>', emails: ['[email protected]'] }, ] as FormattedContact[]; const mergeableContacts = extractMergeable(contacts); expect(doContactListArraysMatch(mergeableContacts, [])).toEqual(true); }); }); });
8,819
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/contacts/properties.spec.ts
import Papa from 'papaparse'; import { prepare, readCsv } from '../../lib/contacts/helpers/csv'; import { getContactCategories, getContactEmails, getVCardProperties } from '../../lib/contacts/properties'; import { prepareForSaving } from '../../lib/contacts/surgery'; import { parseToVCard, vCardPropertiesToICAL } from '../../lib/contacts/vcard'; import { toCRLF } from '../../lib/helpers/string'; describe('getContactEmails', () => { it('should retrieve contact emails from a vcard contact', () => { const contact = prepareForSaving( parseToVCard(`BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN;PID=1.1:J. Doe N:Doe;J.;;; EMAIL;PID=1.1:[email protected] EMAIL:[email protected] CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556 CATEGORIES:TRAVEL AGENT CATEGORIES:INTERNET,IETF,INDUSTRY,INFORMATION TECHNOLOGY END:VCARD`) ); const expected = [ { email: '[email protected]', group: 'item1' }, { email: '[email protected]', group: 'item2' }, ]; expect(getContactEmails(contact)).toEqual(expected); }); it('should not complain if contact emails properties do not contain a group', async () => { const contact = prepareForSaving( parseToVCard(`BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN;PID=1.1:J. Doe N:Doe;J.;;; EMAIL;PID=1.1:[email protected] EMAIL:[email protected] CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556 CATEGORIES:TRAVEL AGENT CATEGORIES:INTERNET,IETF,INDUSTRY,INFORMATION TECHNOLOGY END:VCARD`) ); const expected = [ { email: '[email protected]', group: 'item1' }, { email: '[email protected]', group: 'item2' }, ]; expect(getContactEmails(contact)).toEqual(expected); }); }); describe('getContactCategories', () => { it('should retrieve categories from a vcard contact without groups', () => { const contact = prepareForSaving( parseToVCard(`BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN;PID=1.1:J. Doe N:Doe;J.;;; EMAIL;PID=1.1:[email protected] EMAIL:[email protected] CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556 CATEGORIES:TRAVEL AGENT CATEGORIES:INTERNET,IETF,INDUSTRY,INFORMATION TECHNOLOGY END:VCARD`) ); const expected = [ { name: 'TRAVEL AGENT' }, { name: 'INTERNET' }, { name: 'IETF' }, { name: 'INDUSTRY' }, { name: 'INFORMATION TECHNOLOGY' }, ]; expect(getContactCategories(contact)).toEqual(expected); }); it('should retrieve categories from a vcard contact with groups', () => { const contact = prepareForSaving( parseToVCard(`BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN;PID=1.1:J. Doe N:Doe;J.;;; ITEM1.EMAIL;PID=1.1:[email protected] ITEM2.EMAIL:[email protected] ITEM3.EMAIL:[email protected] CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556 ITEM1.CATEGORIES:TRAVEL AGENT ITEM2.CATEGORIES:INTERNET,IETF,INDUSTRY,INFORMATION TECHNOLOGY ITEM3.CATEGORIES:TRAVEL AGENT,IETF END:VCARD`) ); const expected = [ { name: 'TRAVEL AGENT', group: 'item1' }, { name: 'INTERNET', group: 'item2' }, { name: 'IETF', group: 'item2' }, { name: 'INDUSTRY', group: 'item2' }, { name: 'INFORMATION TECHNOLOGY', group: 'item2' }, { name: 'TRAVEL AGENT', group: 'item3' }, { name: 'IETF', group: 'item3' }, ]; expect(getContactCategories(contact)).toEqual(expected); }); it('should return an empty array when there are no categories in the contact', () => { const contact = prepareForSaving( parseToVCard(`BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN;PID=1.1:J. Doe N:Doe;J.;;; ITEM1.EMAIL;PID=1.1:[email protected] ITEM2.EMAIL:[email protected] ITEM3.EMAIL:[email protected] CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556 END:VCARD`) ); expect(getContactCategories(contact)).toEqual([]); }); }); describe('toICAL', () => { it('should roundtrip', () => { const vcard = toCRLF(`BEGIN:VCARD VERSION:4.0 BDAY:19691203 END:VCARD`); const contact = parseToVCard(vcard); const properties = getVCardProperties(contact); expect(vCardPropertiesToICAL(properties).toString()).toEqual(vcard); }); }); describe('readCSV', () => { it('should convert unwanted fields to notes', async () => { const csvData = [{ 'first name': 'name1', nickname: 'nickname1', related: 'related1' }]; const csvColumns = ['first name', 'nickname', 'related']; const blob = new Blob([Papa.unparse({ data: csvData, fields: csvColumns })]); const csv = new File([blob], 'csvData.csv'); const parsedCsvContacts = await readCsv(csv); const preVcardsContacts = prepare(parsedCsvContacts); expect(preVcardsContacts[0][0][0].field).toEqual('n'); expect(preVcardsContacts[0][1][0].field).toEqual('fn'); expect(preVcardsContacts[0][2][0].field).toEqual('note'); expect(preVcardsContacts[0][3][0].field).toEqual('note'); expect(preVcardsContacts[0].length).toEqual(4); }); it('should map once birthday, anniversary and gender', async () => { const csvData = [ { 'first name': 'name1', birthday: '04/03/2021', birthday2: '03/01/2021', anniversary: '04/03/2021', anniversary2: '03/01/2021', gender: 'M', gender2: 'F', }, ]; const csvColumns = [ 'first name', 'nickname', 'birthday', 'birthday', 'anniversary', 'anniversary', 'gender', 'gender', ]; const blob = new Blob([Papa.unparse({ data: csvData, fields: csvColumns })]); const csv = new File([blob], 'csvData.csv'); const parsedCsvContacts = await readCsv(csv); const preVcardsContacts = prepare(parsedCsvContacts); expect(preVcardsContacts[0][0][0].field).toEqual('n'); expect(preVcardsContacts[0][1][0].field).toEqual('fn'); expect(preVcardsContacts[0][2][0].field).toEqual('bday'); expect(preVcardsContacts[0][3][0].field).toEqual('anniversary'); expect(preVcardsContacts[0][4][0].field).toEqual('gender'); expect(preVcardsContacts[0].length).toEqual(5); }); });
8,820
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/contacts/property.spec.ts
import { getDateFromVCardProperty, guessDateFromText } from '@proton/shared/lib/contacts/property'; import { VCardDateOrText, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; describe('property', () => { describe('guessDateFromText', () => { it('should give expected date when text is a valid date', () => { const text = 'Jun 9, 2022'; const text2 = '2014-02-11T11:30:30'; const text3 = '2023/12/3'; const text4 = '03/12/2023'; expect(guessDateFromText(text)).toEqual(new Date(2022, 5, 9)); expect(guessDateFromText(text2)).toEqual(new Date(2014, 1, 11, 11, 30, 30)); expect(guessDateFromText(text3)).toEqual(new Date(2023, 11, 3)); // Notice in this case, the Date constructor opts for the English format mm/dd instead of dd/mm. This may cause problems during import expect(guessDateFromText(text4)).toEqual(new Date(2023, 2, 12)); }); it('should give today date when text is not a valid date', () => { const text = 'random string to make it fail'; expect(guessDateFromText(text)).toEqual(undefined); }); }); describe('getDateFromVCardProperty', () => { it('should give the expected date when date is valid', () => { const date = new Date(2022, 1, 1); const vCardProperty = { value: { date, }, } as VCardProperty<VCardDateOrText>; expect(getDateFromVCardProperty(vCardProperty)).toEqual(date); }); it('should give today date when date is not valid', () => { const date = new Date('random string to make it fail'); const vCardProperty = { value: { date, }, } as VCardProperty<VCardDateOrText>; const fallbackDate = new Date(); expect(getDateFromVCardProperty(vCardProperty, fallbackDate)).toEqual(fallbackDate); }); it('should give expected date when text is a valid date', () => { const text = 'Jun 9, 2022'; const vCardProperty = { value: { text, }, } as VCardProperty<VCardDateOrText>; expect(getDateFromVCardProperty(vCardProperty)).toEqual(new Date(2022, 5, 9)); const text2 = '2014-02-11T11:30:30'; const vCardProperty2 = { value: { text: text2, }, } as VCardProperty<VCardDateOrText>; expect(getDateFromVCardProperty(vCardProperty2)).toEqual(new Date(2014, 1, 11, 11, 30, 30)); }); it('should give today date when text is not a valid date', () => { const vCardProperty = { value: { text: 'random string to make it fail', }, } as VCardProperty<VCardDateOrText>; const fallbackDate = new Date(); expect(getDateFromVCardProperty(vCardProperty, fallbackDate)).toEqual(fallbackDate); }); }); });
8,821
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/contacts/vcard.spec.ts
import { createContactPropertyUid } from '@proton/shared/lib/contacts/properties'; import { parseToVCard, serialize } from '@proton/shared/lib/contacts/vcard'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; describe('serialize', () => { describe('produces the expected vcf', () => { it('when there are all supported standard properties', () => { const contact: VCardContact = { version: { field: 'version', value: '4.0', uid: createContactPropertyUid() }, n: { field: 'n', value: { familyNames: ['Messi'], givenNames: ['Lionel'], additionalNames: ['Andrés'], honorificPrefixes: [''], honorificSuffixes: [''], }, uid: createContactPropertyUid(), }, fn: [{ field: 'fn', value: 'Leo Messi', uid: createContactPropertyUid() }], title: [{ field: 'title', value: 'Football ambassador', uid: createContactPropertyUid() }], nickname: [ { field: 'nickname', value: 'La Pulga', uid: createContactPropertyUid() }, { field: 'nickname', value: 'The Messiah', uid: createContactPropertyUid() }, ], email: [ { field: 'email', value: '[email protected]', params: { type: 'WORK', pref: '1' }, group: 'item1', uid: createContactPropertyUid(), }, ], adr: [ { field: 'adr', value: { postOfficeBox: '', extendedAddress: '', streetAddress: "Carrer d'Elisabeth Eidenbenz", locality: 'Barcelona', region: 'Catalunya', postalCode: '08028', country: 'Catalonia', }, uid: createContactPropertyUid(), }, ], tel: [ { field: 'tel', value: 'tel:+1-555-555-5555;ext=5555', params: { value: 'uri', type: 'voice', }, uid: createContactPropertyUid(), }, ], bday: { field: 'bday', value: { date: new Date(Date.UTC(1999, 5, 9)), }, uid: createContactPropertyUid(), }, anniversary: { field: 'anniversary', value: { text: 'ferragosto', }, uid: createContactPropertyUid(), }, impp: [ { field: 'impp', value: 'xmpp:[email protected]', params: { pref: '1' }, uid: createContactPropertyUid(), }, ], photo: [{ field: 'photo', value: 'bcspevahwseowngfs23dkl1lsxslfj', uid: createContactPropertyUid() }], lang: [ { field: 'lang', params: { type: 'home', pref: '1' }, value: 'es', uid: createContactPropertyUid(), }, { field: 'lang', params: { type: 'work', pref: '1' }, value: 'es', uid: createContactPropertyUid(), }, { field: 'lang', params: { type: 'work', pref: '2' }, value: 'en', uid: createContactPropertyUid(), }, ], geo: [{ field: 'geo', value: 'geo:37.386013,-122.082932', uid: createContactPropertyUid() }], role: [{ field: 'role', value: 'Fake 9', uid: createContactPropertyUid() }], logo: [ { field: 'logo', value: 'https://static.messi.com/wp-content/uploads/2019/10/messi-logo-01.png', uid: createContactPropertyUid(), }, ], org: [ { field: 'org', value: { organizationalName: 'Barcelona FC', organizationalUnitNames: ['Training-center'] }, uid: createContactPropertyUid(), }, { field: 'org', value: { organizationalName: 'Leo Messi Foundation' }, uid: createContactPropertyUid(), }, ], member: [{ field: 'member', value: 'tel:+1-418-555-5555', uid: createContactPropertyUid() }], related: [ { field: 'related', params: { type: 'spouse' }, value: 'Antonela Roccuzzo', uid: createContactPropertyUid(), }, { field: 'related', params: { type: 'child' }, value: 'Matteo Messi Roccuzzo', uid: createContactPropertyUid(), }, { field: 'related', params: { type: 'child' }, value: 'Thiago Messi Roccuzzo', uid: createContactPropertyUid(), }, { field: 'related', params: { type: 'child' }, value: 'Ciro Messi Roccuzzo', uid: createContactPropertyUid(), }, ], note: [{ field: 'note', value: 'Way better than Cristiano Ronaldo!', uid: createContactPropertyUid() }], url: [{ field: 'url', value: 'https://messi.com/', uid: createContactPropertyUid() }], categories: [ { field: 'categories', value: 'Tax-evading players', uid: createContactPropertyUid(), }, { field: 'categories', value: 'Best players of all time', uid: createContactPropertyUid(), }, ], }; const vcf = [ `BEGIN:VCARD`, `VERSION:4.0`, `FN:Leo Messi`, `N:Messi;Lionel;Andrés;;`, `TITLE:Football ambassador`, `NICKNAME:La Pulga`, `NICKNAME:The Messiah`, `ITEM1.EMAIL;TYPE=WORK;PREF=1:[email protected]`, `ADR:;;Carrer d'Elisabeth Eidenbenz;Barcelona;Catalunya;08028;Catalonia`, `TEL;VALUE=uri;TYPE=voice:tel:+1-555-555-5555;ext=5555`, `BDAY:19990609`, `ANNIVERSARY;VALUE=TEXT:ferragosto`, `IMPP;PREF=1:xmpp:[email protected]`, `PHOTO:bcspevahwseowngfs23dkl1lsxslfj`, `LANG;TYPE=home;PREF=1:es`, `LANG;TYPE=work;PREF=1:es`, `LANG;TYPE=work;PREF=2:en`, `GEO;VALUE=FLOAT:geo:37.386013,-122.082932`, `ROLE:Fake 9`, `LOGO:https://static.messi.com/wp-content/uploads/2019/10/messi-logo-01.png`, `ORG:Barcelona FC;Training-center`, `ORG:Leo Messi Foundation`, `MEMBER:tel:+1-418-555-5555`, `RELATED;TYPE=spouse:Antonela Roccuzzo`, `RELATED;TYPE=child:Matteo Messi Roccuzzo`, `RELATED;TYPE=child:Thiago Messi Roccuzzo`, `RELATED;TYPE=child:Ciro Messi Roccuzzo`, `NOTE:Way better than Cristiano Ronaldo!`, `URL:https://messi.com/`, `CATEGORIES:Tax-evading players`, `CATEGORIES:Best players of all time`, `END:VCARD`, ].join('\r\n'); expect(serialize(contact)).toEqual(vcf); }); it('when there are both categories with vcard group and without', () => { const contact: VCardContact = { version: { field: 'version', value: '4.0', uid: createContactPropertyUid() }, fn: [{ field: 'fn', value: 'dummy', uid: createContactPropertyUid() }], categories: [ { field: 'categories', value: 'first', uid: createContactPropertyUid() }, { field: 'categories', group: 'item1', value: 'second', uid: createContactPropertyUid(), }, { field: 'categories', group: 'item1', value: 'third', uid: createContactPropertyUid(), }, ], }; const vcf = [ `BEGIN:VCARD`, `VERSION:4.0`, `FN:dummy`, `CATEGORIES:first`, `ITEM1.CATEGORIES:second`, `ITEM1.CATEGORIES:third`, `END:VCARD`, ].join('\r\n'); expect(serialize(contact)).toEqual(vcf); }); it('unexpectedly prints FLOAT for the GEO property', () => { const contact: VCardContact = { version: { field: 'version', value: '4.0', uid: createContactPropertyUid() }, fn: [{ field: 'fn', value: 'dummy', uid: createContactPropertyUid() }], geo: [{ field: 'geo', value: 'geo:41,34', uid: createContactPropertyUid() }], }; const vcf = [`BEGIN:VCARD`, `VERSION:4.0`, `FN:dummy`, `GEO;VALUE=FLOAT:geo:41,34`, `END:VCARD`].join( '\r\n' ); expect(serialize(contact)).toEqual(vcf); }); it('no value is passed to FN field', () => { const contact = { version: { field: 'version', value: '4.0', uid: createContactPropertyUid() }, fn: [{ field: 'fn', value: '', uid: createContactPropertyUid(), params: { pref: '1' } }], }; expect(serialize(contact)).toEqual([`BEGIN:VCARD`, `VERSION:4.0`, `END:VCARD`].join('\r\n')); }); }); describe('round trips with parse', () => { it('for a simple vcard', () => { const vcf = [ `BEGIN:VCARD`, `VERSION:4.0`, // `FN;PID=1.1:J. Doe`, // `UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1`, `N:Doe;J.;;;`, // `EMAIL;PID=1.1:[email protected]`, // `EMAIL:[email protected]`, // `CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556`, // `CATEGORIES:TRAVEL AGENT`, // `CATEGORIES:INTERNET,IETF,INDUSTRY,INFORMATION TECHNOLOGY`, `END:VCARD`, ].join('\r\n'); expect(serialize(parseToVCard(vcf))).toEqual(vcf); }); it('always puts FN after version', () => { const vcf = [ `BEGIN:VCARD`, `VERSION:4.0`, `UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1`, `N:Doe;J.;;;`, `EMAIL;PID=1.1:[email protected]`, `EMAIL:[email protected]`, `CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556`, `FN;PID=1.1:J. Doe`, `CATEGORIES:TRAVEL AGENT`, `CATEGORIES:INTERNET,IETF,INDUSTRY,INFORMATION TECHNOLOGY`, `END:VCARD`, ].join('\r\n'); const expected = [ `BEGIN:VCARD`, `VERSION:4.0`, `FN;PID=1.1:J. Doe`, `UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1`, `N:Doe;J.;;;`, `EMAIL;PID=1.1:[email protected]`, `EMAIL:[email protected]`, `CLIENTPIDMAP:1;urn:uuid:53e374d9-337e-4727-8803-a1e9c14e0556`, `CATEGORIES:TRAVEL AGENT`, `CATEGORIES:INTERNET,IETF,INDUSTRY,INFORMATION TECHNOLOGY`, `END:VCARD`, ].join('\r\n'); expect(serialize(parseToVCard(vcf))).toEqual(expected); }); }); }); describe('parseToVcard', () => { describe('parses correctly the N property', () => { it('when it contains all components and single values', () => { const vcf = [`BEGIN:VCARD`, `VERSION:4.0`, `N:Public;John;Quinlan;Mr.;Esq.`, `END:VCARD`].join('\r\n'); const result = parseToVCard(vcf); expect(result.n?.value).toEqual({ familyNames: ['Public'], givenNames: ['John'], additionalNames: ['Quinlan'], honorificPrefixes: ['Mr.'], honorificSuffixes: ['Esq.'], }); }); it('when it contains all components and multiple values', () => { const vcf = [ `BEGIN:VCARD`, `VERSION:4.0`, `N:Stevenson;John;Philip,Paul;Dr.;Jr.,M.D.,A.C.P.`, `END:VCARD`, ].join('\r\n'); const result = parseToVCard(vcf); expect(result.n?.value).toEqual({ familyNames: ['Stevenson'], givenNames: ['John'], additionalNames: ['Philip', 'Paul'], honorificPrefixes: ['Dr.'], honorificSuffixes: ['Jr.', 'M.D.', 'A.C.P.'], }); }); it('when it contains all components and some are empty', () => { const vcf = [`BEGIN:VCARD`, `VERSION:4.0`, `N:Yamada;Taro;;;`, `END:VCARD`].join('\r\n'); const result = parseToVCard(vcf); expect(result.n?.value).toEqual({ familyNames: ['Yamada'], givenNames: ['Taro'], additionalNames: [''], honorificPrefixes: [''], honorificSuffixes: [''], }); }); }); describe('can parse a vcard with an invalid N property', () => { it('if the N property has no semicolon at all', () => { const vcf = [`BEGIN:VCARD`, `VERSION:4.0`, `FN:Santa Claus`, `N:Santa Claus`, `END:VCARD`].join('\r\n'); const result = parseToVCard(vcf); expect(result.fn[0].value).toBe('Santa Claus'); expect(result.n?.value).toEqual({ familyNames: ['Santa Claus'], givenNames: [''], additionalNames: [''], honorificPrefixes: [''], honorificSuffixes: [''], }); }); it('if the N property has an incorrect number of semicolons', () => { const vcf = [`BEGIN:VCARD`, `VERSION:4.0`, `FN:Santa Claus`, `N:Claus;Santa`, `END:VCARD`].join('\r\n'); const result = parseToVCard(vcf); expect(result.fn[0].value).toBe('Santa Claus'); expect(result.n?.value).toEqual({ familyNames: ['Claus'], givenNames: ['Santa'], additionalNames: [''], honorificPrefixes: [''], honorificSuffixes: [''], }); }); }); });
8,822
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/date-fns-utc/formatUTC.spec.js
import { format } from '../../lib/date-fns-utc'; describe('date-fn utc', () => { // this test is designed for Central European Time it('it should format in UTC time', () => { const utcDate = new Date(Date.UTC(2000, 0, 1, 1, 0)); expect(format(utcDate, 'Pp')).toBe('01/01/2000, 1:00 AM'); }); it('it should format properly right at DST change time, summer to winter', () => { const utcDate = new Date(Date.UTC(2019, 9, 27, 1, 0)); expect(format(utcDate, 'Pp')).toBe('10/27/2019, 1:00 AM'); }); it('it should format properly before DST change time, summer to winter', () => { const utcDate = new Date(Date.UTC(2019, 9, 27, 0, 0)); expect(format(utcDate, 'Pp')).toBe('10/27/2019, 12:00 AM'); }); it('it should format properly after DST change time, summer to winter', () => { const utcDate = new Date(Date.UTC(2019, 9, 27, 2, 0)); expect(format(utcDate, 'Pp')).toBe('10/27/2019, 2:00 AM'); }); it('it should format properly right at DST change time, winter to summer', () => { const utcDate = new Date(Date.UTC(2019, 2, 31, 1, 0)); expect(format(utcDate, 'Pp')).toBe('03/31/2019, 1:00 AM'); }); it('it should format properly before DST change time, winter to summer', () => { const utcDate = new Date(Date.UTC(2019, 2, 31, 0, 0)); expect(format(utcDate, 'Pp')).toBe('03/31/2019, 12:00 AM'); }); it('it should format properly after DST change time, winter to summer', () => { const utcDate = new Date(Date.UTC(2019, 2, 31, 2, 0)); expect(format(utcDate, 'Pp')).toBe('03/31/2019, 2:00 AM'); }); });
8,823
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/date-utc/date-utc.spec.ts
import { formatIntlUTCDate } from '../../lib/date-utc/formatIntlUTCDate'; describe('formatIntlUTCDate()', () => { it('formats UTC dates, not local dates', () => { // The following test will pass in any machine with any local time zone (try it yourself!). // Unfortunately there's no easy way of mocking local time zones with karma, so we can't make that explicit const date = new Date(Date.UTC(2023, 5, 13, 17, 44, 2)); expect(formatIntlUTCDate(date, { timeStyle: 'short', hour12: false }, 'en-US')).toEqual('17:44'); expect(formatIntlUTCDate(date, { timeStyle: 'short', hour12: true }, 'fr-FR')).toEqual('05:44 PM'); }); });
8,824
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/date/date.spec.ts
import { enUS, fr } from 'date-fns/locale'; import { getFormattedMonths, getFormattedWeekdays, getWeekStartsOn, isValidDate } from '../../lib/date/date'; describe('getFormattedWeekdays', () => { it('should get a list with the names of the days of the week according to current locale', () => { expect(getFormattedWeekdays('cccc', { locale: enUS })).toEqual([ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]); expect(getFormattedWeekdays('cccc', { locale: fr })).toEqual([ 'dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', ]); }); }); describe('getFormattedMonths', () => { it('should get a list with the names of the months of the year according to current locale', () => { expect(getFormattedMonths('MMMM', { locale: enUS })).toEqual([ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]); expect(getFormattedMonths('MMMM', { locale: fr })).toEqual([ 'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre', ]); }); }); describe('getWeekStartsOn', () => { it('should get a index from 0 (Sunday) to 6 (Saturday) of the first day of week of a given locale', () => { expect(getWeekStartsOn(enUS)).toEqual(0); expect(getWeekStartsOn(fr)).toEqual(1); }); }); describe('isValidDate', () => { it('should detect valid date', () => { expect(isValidDate(new Date())).toEqual(true); }); it('should detect invalid date', () => { expect(isValidDate(new Date('panda'))).toEqual(false); }); });
8,825
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/date/dateFnLocale.spec.ts
import { default as enGBLocale } from 'date-fns/locale/en-GB'; import { default as enUSLocale } from 'date-fns/locale/en-US'; import { default as frFRLocale } from 'date-fns/locale/fr'; import { default as frCALocale } from 'date-fns/locale/fr-CA'; import formatUTC from '@proton/shared/lib/date-fns-utc/format'; import { getDateFnLocaleWithLongFormat } from '../../lib/i18n/dateFnLocale'; describe('datefns locales', () => { const date = new Date(Date.UTC(1999, 11, 1, 1, 0, 0)); it('should merge time format from a US locale into FR', () => { expect(formatUTC(date, 'P p', { locale: getDateFnLocaleWithLongFormat(enUSLocale, frFRLocale) })).toBe( '12/01/1999 01:00' ); }); it('should merge date & time format from a US locale into US', () => { expect(formatUTC(date, 'P p', { locale: getDateFnLocaleWithLongFormat(enUSLocale, enUSLocale) })).toBe( '12/01/1999 1:00 AM' ); }); it('should merge date & time format from a US locale into GB (when languages are the same)', () => { expect(formatUTC(date, 'P p', { locale: getDateFnLocaleWithLongFormat(enUSLocale, enGBLocale) })).toBe( '01/12/1999 01:00' ); }); it('should merge date & time format from a FR locale into CA (when languages are the same)', () => { expect(formatUTC(date, 'P p', { locale: getDateFnLocaleWithLongFormat(frFRLocale, frCALocale) })).toBe( '99-12-01 01:00' ); }); });
8,826
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/date/formatIntlDate.spec.ts
import { formatIntlDate } from '../../lib/date/formatIntlDate'; describe('formatIntlDate()', () => { it('adapts order of year and month and day for different languages', () => { const date = new Date(2023, 5, 17, 11, 44, 2); expect(formatIntlDate(date, { month: 'short', year: 'numeric' }, 'en-US')).toEqual('Jun 2023'); expect(formatIntlDate(date, { month: 'short', year: 'numeric' }, 'zh-ZH')).toEqual('2023年6月'); }); it('offers four built-in date formatting options (not including time)', () => { const date = new Date(2023, 5, 17, 11, 44, 2); // en-US; expect(formatIntlDate(date, { dateStyle: 'full' }, 'en-US')).toEqual('Saturday, June 17, 2023'); expect(formatIntlDate(date, { dateStyle: 'long' }, 'en-US')).toEqual('June 17, 2023'); expect(formatIntlDate(date, { dateStyle: 'short' }, 'en-US')).toEqual('6/17/23'); expect(formatIntlDate(date, { dateStyle: 'medium' }, 'en-US')).toEqual('Jun 17, 2023'); // it; expect(formatIntlDate(date, { dateStyle: 'full' }, 'it')).toEqual('sabato 17 giugno 2023'); expect(formatIntlDate(date, { dateStyle: 'long' }, 'it')).toEqual('17 giugno 2023'); expect(formatIntlDate(date, { dateStyle: 'short' }, 'it')).toEqual('17/06/23'); expect(formatIntlDate(date, { dateStyle: 'medium' }, 'it')).toEqual('17 giu 2023'); // ko; expect(formatIntlDate(date, { dateStyle: 'full' }, 'ko')).toEqual('2023년 6월 17일 토요일'); expect(formatIntlDate(date, { dateStyle: 'long' }, 'ko')).toEqual('2023년 6월 17일'); expect(formatIntlDate(date, { dateStyle: 'short' }, 'ko')).toEqual('23. 6. 17.'); expect(formatIntlDate(date, { dateStyle: 'medium' }, 'ko')).toEqual('2023. 6. 17.'); }); it('offers four built-in time formatting options', () => { const date = new Date(2023, 5, 13, 17, 44, 2); // en-UK // timeStyle 'full' includes a full time zone name, e.g. 15:44:02 Central European Summer Time expect(formatIntlDate(date, { timeStyle: 'full' }, 'en-UK')).toContain('17:44:02'); // timeStyle 'long' includes a short time zone name, e.g. 15:44:02 CEST, or 15:44:02 GMT+2 expect(formatIntlDate(date, { timeStyle: 'long' }, 'en-UK')).toContain('17:44:02'); expect(formatIntlDate(date, { timeStyle: 'short' }, 'en-UK')).toEqual('17:44'); expect(formatIntlDate(date, { timeStyle: 'medium' }, 'en-UK')).toEqual('17:44:02'); // es-ES expect(formatIntlDate(date, { timeStyle: 'full' }, 'es-ES')).toContain('17:44:02'); expect(formatIntlDate(date, { timeStyle: 'long' }, 'es-ES')).toContain('17:44:02'); expect(formatIntlDate(date, { timeStyle: 'short' }, 'es-ES')).toEqual('17:44'); expect(formatIntlDate(date, { timeStyle: 'medium' }, 'es-ES')).toEqual('17:44:02'); // ja-JP; expect(formatIntlDate(date, { timeStyle: 'full' }, 'ja-JP')).toContain('17時44分02秒'); expect(formatIntlDate(date, { timeStyle: 'long' }, 'ja-JP')).toContain('17:44:02'); expect(formatIntlDate(date, { timeStyle: 'short' }, 'ja-JP')).toEqual('17:44'); expect(formatIntlDate(date, { timeStyle: 'medium' }, 'ja-JP')).toEqual('17:44:02'); }); it('should default to US English when locale is unknown to Javascript', () => { const date = new Date(2023, 5, 17, 11, 44, 2); expect(formatIntlDate(date, { dateStyle: 'full' }, 'not_a_locale')).toEqual('Saturday, June 17, 2023'); expect(formatIntlDate(date, { dateStyle: 'long' }, 'not_a_locale')).toEqual('June 17, 2023'); expect(formatIntlDate(date, { dateStyle: 'short' }, 'not_a_locale')).toEqual('6/17/23'); expect(formatIntlDate(date, { dateStyle: 'medium' }, 'not_a_locale')).toEqual('Jun 17, 2023'); }); });
8,827
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/date/timezone.spec.ts
import { listTimeZones } from '@protontech/timezone-support'; import { SimpleMap } from '@proton/shared/lib/interfaces'; import { convertUTCDateTimeToZone, convertZonedDateTimeToUTC, getAbbreviatedTimezoneName, getReadableCityTimezone, getSupportedTimezone, getTimezoneAndOffset, guessTimezone, } from '../../lib/date/timezone'; import { MANUAL_TIMEZONE_LINKS, unsupportedTimezoneLinks } from '../../lib/date/timezoneDatabase'; describe('convert utc', () => { const obj = (year: number, month: number, day: number, hours = 0, minutes = 0, seconds = 0) => ({ year, month, day, hours, minutes, seconds, }); it('should convert a zoned time (Australia/Sydney) to utc', () => { expect(convertZonedDateTimeToUTC(obj(2019, 1, 1), 'Australia/Sydney')).toEqual(obj(2018, 12, 31, 13)); }); it('should convert a zoned time (Europe/Zurich summer) to utc', () => { expect(convertZonedDateTimeToUTC(obj(2019, 6, 15, 1), 'Europe/Zurich')).toEqual(obj(2019, 6, 14, 23)); }); it('should convert a zoned time (Europe/Zurich winter) to utc', () => { expect(convertZonedDateTimeToUTC(obj(2019, 12, 15, 1), 'Europe/Zurich')).toEqual(obj(2019, 12, 15, 0)); }); it('should convert a zoned time to utc with winter-to-summer (Europe/Zurich 2017) dst shift', () => { expect(convertZonedDateTimeToUTC(obj(2017, 3, 26, 1), 'Europe/Zurich')).toEqual(obj(2017, 3, 26, 0)); expect(convertZonedDateTimeToUTC(obj(2017, 3, 26, 2), 'Europe/Zurich')).toEqual(obj(2017, 3, 26, 1)); expect(convertZonedDateTimeToUTC(obj(2017, 3, 26, 3), 'Europe/Zurich')).toEqual(obj(2017, 3, 26, 1)); expect(convertZonedDateTimeToUTC(obj(2017, 3, 26, 4), 'Europe/Zurich')).toEqual(obj(2017, 3, 26, 2)); }); it('should convert a zoned time to utc with summer-to-winter (Europe/Zurich 2019) dst shift', () => { expect(convertZonedDateTimeToUTC(obj(2019, 10, 27, 1), 'Europe/Zurich')).toEqual(obj(2019, 10, 26, 23)); expect(convertZonedDateTimeToUTC(obj(2019, 10, 27, 2), 'Europe/Zurich')).toEqual(obj(2019, 10, 27, 1)); expect(convertZonedDateTimeToUTC(obj(2019, 10, 27, 3), 'Europe/Zurich')).toEqual(obj(2019, 10, 27, 2)); expect(convertZonedDateTimeToUTC(obj(2019, 10, 27, 4), 'Europe/Zurich')).toEqual(obj(2019, 10, 27, 3)); }); it('should convert from utc time to a timezone (Australia/Sydney)', () => { expect(convertUTCDateTimeToZone(obj(2018, 12, 31, 13), 'Australia/Sydney')).toEqual(obj(2019, 1, 1)); }); it('should convert back from a utc to a timezone (Europe/Zurich summer)', () => { expect(convertUTCDateTimeToZone(obj(2019, 6, 14, 23), 'Europe/Zurich')).toEqual(obj(2019, 6, 15, 1)); }); it('should convert back from a utc time to a timezone (Europe/Zurich winter)', () => { expect(convertUTCDateTimeToZone(obj(2019, 12, 15, 0), 'Europe/Zurich')).toEqual(obj(2019, 12, 15, 1)); }); it('should convert back from a utc to a timezone (Europe/Zurich 2017) with summer-to-winter dst shifts', () => { expect(convertUTCDateTimeToZone(obj(2017, 3, 26, 0), 'Europe/Zurich')).toEqual(obj(2017, 3, 26, 1)); expect(convertUTCDateTimeToZone(obj(2017, 3, 26, 1), 'Europe/Zurich')).toEqual(obj(2017, 3, 26, 3)); expect(convertUTCDateTimeToZone(obj(2017, 3, 26, 2), 'Europe/Zurich')).toEqual(obj(2017, 3, 26, 4)); }); it('should convert back from a utc to a timezone (Europe/Zurich 2017) with winter-to-summer dst shifts', () => { expect(convertUTCDateTimeToZone(obj(2019, 10, 27, 0), 'Europe/Zurich')).toEqual(obj(2019, 10, 27, 2)); expect(convertUTCDateTimeToZone(obj(2019, 10, 27, 1), 'Europe/Zurich')).toEqual(obj(2019, 10, 27, 2)); expect(convertUTCDateTimeToZone(obj(2019, 10, 27, 2), 'Europe/Zurich')).toEqual(obj(2019, 10, 27, 3)); }); }); describe('getSupportedTimezone', () => { it('should remove extra slashes', () => { expect(getSupportedTimezone('/Europe/London/')).toEqual('Europe/London'); expect(getSupportedTimezone('/Africa/Freetown/')).toEqual('Africa/Abidjan'); }); it('should support the bluejeans format', () => { expect(getSupportedTimezone('/tzurl.org/2020b/America/Chicago')).toEqual('America/Chicago'); expect(getSupportedTimezone('/tzurl.org/2020b/Asia/Istanbul')).toEqual('Europe/Istanbul'); }); it('should support the mozilla format', () => { expect(getSupportedTimezone('/mozilla.org/20050126_1/America/Argentina/Ushuaia')).toEqual( 'America/Argentina/Ushuaia' ); expect(getSupportedTimezone('/mozilla.org/20050126_1/America/Argentina/ComodRivadavia')).toEqual( 'America/Argentina/Catamarca' ); }); it('should transform globally defined alias timezones according to the longest match', () => { // GB (Europe/London), Eire (Europe/Dublin) and GB-Eire (Europe/London) are all alias timezones. // getSupportedTimezone should transform according to the longest match, GB-Eire -> Europe/London expect(getSupportedTimezone('/mozilla.org/20050126_1/GB-Eire')).toEqual('Europe/London'); expect(getSupportedTimezone('/tzurl.org/2021a/Eire')).toEqual('Europe/Dublin'); expect(getSupportedTimezone('/GB/')).toEqual('Europe/London'); }); it('should be robust for capturing globally defined timezones (for which no specification exists)', () => { expect(getSupportedTimezone('/IANA-db:Asia/Seoul--custom.format')).toEqual('Asia/Seoul'); }); it('should filter non-supported canonical timezones', () => { const canonical = listTimeZones(); const results = canonical.map((tzid) => getSupportedTimezone(tzid)); const expected = canonical.map((tzid) => unsupportedTimezoneLinks[tzid] || tzid); expect(results).toEqual(expected); }); it('should return the supported canonical timezone for alias timezones', () => { const alias = [ 'Africa/Bujumbura', 'Africa/Freetown', 'America/Antigua', 'America/Indianapolis', 'Asia/Macao', 'Asia/Istanbul', 'Europe/Skopje', 'GB-Eire', ]; const canonical = [ 'Africa/Maputo', 'Africa/Abidjan', 'America/Puerto_Rico', 'America/New_York', 'Asia/Macau', 'Europe/Istanbul', 'Europe/Belgrade', 'Europe/London', ]; const results = alias.map((tzid) => getSupportedTimezone(tzid)); expect(results).toEqual(canonical); }); it('should convert manual timezones', () => { const manual = Object.keys(MANUAL_TIMEZONE_LINKS); const results = manual.map((tzid) => getSupportedTimezone(tzid)); const expected = Object.values(MANUAL_TIMEZONE_LINKS); expect(results).toEqual(expected); }); it('should convert time zones we do not support yet', () => { const expectedMap: SimpleMap<string> = { 'Pacific/Kanton': 'Pacific/Fakaofo', 'Europe/Kyiv': 'Europe/Kiev', 'America/Nuuk': 'Atlantic/Stanley', 'America/Ciudad_Juarez': 'America/Ojinaga', }; Object.keys(expectedMap).forEach((tzid) => { expect(getSupportedTimezone(tzid)).toBe(expectedMap[tzid]); }); }); it('should be robust', () => { const tzids = ['Chamorro (UTC+10)', '(GMT-01:00) Azores', 'Mountain Time (U.S. & Canada)']; const expected = ['Pacific/Saipan', 'Atlantic/Azores', 'America/Denver']; const results = tzids.map(getSupportedTimezone); expect(results).toEqual(expected); }); it('should return undefined for unknown timezones', () => { const unknown = ['Chamorro Standard Time', '(UTC+01:00) Bruxelles, Copenhague, Madrid, Paris']; const results = unknown.map((tzid) => getSupportedTimezone(tzid)); const expected = unknown.map(() => undefined); expect(results).toEqual(expected); }); }); describe('guessTimeZone', () => { const timeZoneList = listTimeZones(); describe('should guess right when the browser detects "Europe/Zurich"', () => { beforeEach(() => { spyOn<any>(Intl, 'DateTimeFormat').and.returnValue({ resolvedOptions: () => ({ timeZone: 'Europe/Zurich' }), }); }); it('guesses "Europe/Zurich"', () => { expect(guessTimezone(timeZoneList)).toBe('Europe/Zurich'); }); }); describe('should guess right when the browser detects "Europe/Kyiv"', () => { beforeEach(() => { spyOn<any>(Intl, 'DateTimeFormat').and.returnValue({ resolvedOptions: () => ({ timeZone: 'Europe/Kyiv' }), }); }); it('guesses "Europe/Kiev"', () => { expect(guessTimezone(timeZoneList)).toBe('Europe/Kiev'); }); }); describe('should guess right when the browser detects "Pacific/Kanton"', () => { beforeEach(() => { spyOn<any>(Intl, 'DateTimeFormat').and.returnValue({ resolvedOptions: () => ({ timeZone: 'Pacific/Kanton' }), }); }); it('guesses "Pacific/Fakaofo"', () => { expect(guessTimezone(timeZoneList)).toBe('Pacific/Fakaofo'); }); }); describe('should guess right when the browser detects unknown time zone with GMT+1', () => { beforeEach(() => { const baseTime = Date.UTC(2023, 2, 7, 9); spyOn<any>(Intl, 'DateTimeFormat').and.returnValue({ resolvedOptions: () => ({ timeZone: 'unknown' }), }); spyOn<any>(window, 'Date').and.returnValue({ getTime: () => baseTime, getTimezoneOffset: () => -60, getUTCFullYear: () => 2023, getUTCMonth: () => 2, getUTCDate: () => 7, getUTCDay: () => 2, getUTCHours: () => 9, getUTCMinutes: () => 0, getUTCSeconds: () => 0, getUTCMilliseconds: () => 0, }); }); it('guesses "Africa/Algiers", first in the list with that GMT offset', () => { expect(guessTimezone(timeZoneList)).toBe('Africa/Algiers'); }); }); }); describe('getReadableCityTimezone', () => { it('should return city timezone without underscores', () => { const cityTimezone = 'Los_Angeles'; expect(getReadableCityTimezone(cityTimezone)).toEqual('Los Angeles'); }); it('should return city timezone without change', () => { const cityTimezone = 'Paris'; expect(getReadableCityTimezone(cityTimezone)).toEqual('Paris'); }); }); describe('getAbbreviatedTimezoneName', () => { it('should return the expected offset timezone', () => { const timezone = 'Europe/Paris'; const result = getAbbreviatedTimezoneName('offset', timezone) || ''; expect(['GMT+1', 'GMT+2']).toContain(result); }); it('should return the expected city timezone', () => { const timezone = 'Europe/Paris'; expect(getAbbreviatedTimezoneName('city', timezone)).toEqual('Paris'); }); it('should return the expected city timezone on a readable format', () => { const timezone = 'America/Los_Angeles'; expect(getAbbreviatedTimezoneName('city', timezone)).toEqual('Los Angeles'); }); it('should return the expected city timezone for a longer timezone', () => { const timezone = 'America/North_Dakota/New_Salem'; expect(getAbbreviatedTimezoneName('city', timezone)).toEqual('New Salem'); }); }); describe('getTimezoneAndOffset', () => { it('should return the expected timezone string, containing offset and name', () => { const timezone = 'Europe/Paris'; const result = getTimezoneAndOffset(timezone); expect(['GMT+1 • Europe/Paris', 'GMT+2 • Europe/Paris']).toContain(result); }); });
8,828
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/drawer/drawer.spec.ts
import { APPS, APPS_CONFIGURATION, APP_NAMES } from '@proton/shared/lib/constants'; import { DRAWER_ACTION, DRAWER_EVENTS, DRAWER_NATIVE_APPS } from '@proton/shared/lib/drawer/interfaces'; import { addParentAppToUrl, authorizedApps, drawerAuthorizedApps, drawerIframeApps, drawerNativeApps, getDisplayContactsInDrawer, getDisplayDrawerApp, getIsAuthorizedApp, getIsDrawerPostMessage, getIsIframedDrawerApp, getIsNativeDrawerApp, isAppInView, isAuthorizedDrawerUrl, postMessageFromIframe, } from '../../lib/drawer/helpers'; import window from '../../lib/window'; import { mockWindowLocation, resetWindowLocation } from '../helpers/url.helper'; const windowHostname = 'mail.proton.me'; const tsDrawerNativeApps: string[] = [...drawerNativeApps]; const tsDrawerIframeApps: string[] = [...drawerIframeApps]; describe('drawer helpers', () => { describe('isNativeDrawerApp', () => { it('should be a drawer native app', () => { drawerNativeApps.forEach((app) => { expect(getIsNativeDrawerApp(app)).toBeTruthy(); }); }); it('should not be a drawer native app', () => { Object.values(APPS).forEach((app) => { if (!tsDrawerNativeApps.includes(app)) { expect(getIsNativeDrawerApp(app)).toBeFalsy(); } }); }); }); describe('isIframeDrawerApp', () => { it('should be a iframe drawer app', () => { drawerIframeApps.forEach((app) => { expect(getIsIframedDrawerApp(app)).toBeTruthy(); }); }); it('should not be a iframe drawer native app', () => { Object.values(APPS).forEach((app) => { if (!tsDrawerIframeApps.includes(app)) { expect(getIsIframedDrawerApp(app)).toBeFalsy(); } }); }); }); describe('isAuthorizedDrawerUrl', () => { beforeEach(() => { mockWindowLocation({ hostname: windowHostname }); }); afterEach(() => { resetWindowLocation(); }); it('should be a url from an authorized domain', () => { drawerAuthorizedApps.forEach((appDomain) => { const url = `https://${appDomain}.proton.me`; expect(isAuthorizedDrawerUrl(url)).toBeTruthy(); }); }); it('should not be a url from an authorized domain', () => { const url1 = 'https://scam.proton.me'; const url2 = 'https://mail.scam.me'; expect(isAuthorizedDrawerUrl(url1)).toBeFalsy(); expect(isAuthorizedDrawerUrl(url2)).toBeFalsy(); }); }); describe('getIsAuthorizedApp', () => { it('should be an authorized app', () => { authorizedApps.forEach((app) => { expect(getIsAuthorizedApp(app)).toBeTruthy(); }); }); it('should not be an authorized app', () => { Object.values(APPS).forEach((app) => { if (!authorizedApps.includes(app)) { expect(getIsAuthorizedApp(app)).toBeFalsy(); } }); }); }); describe('getIsDrawerPostMessage', () => { beforeEach(() => { mockWindowLocation({ hostname: windowHostname }); }); afterEach(() => { resetWindowLocation(); }); it('should be a drawer message', () => { drawerAuthorizedApps.forEach((app) => { const event = { origin: `https://${app}.proton.me`, data: { type: DRAWER_EVENTS.READY, }, } as MessageEvent; expect(getIsDrawerPostMessage(event)).toBeTruthy(); }); }); it('should not be a drawer message when app is not authorized', () => { Object.values(APPS).forEach((app) => { if (!drawerAuthorizedApps.includes(APPS_CONFIGURATION[app].subdomain)) { const appSubdomain = APPS_CONFIGURATION[app].subdomain; const event = { origin: `https://${appSubdomain}.proton.me`, data: { type: DRAWER_EVENTS.READY, }, } as MessageEvent; expect(getIsDrawerPostMessage(event)).toBeFalsy(); } }); }); it('should not be a drawer message when event type is invalid', () => { const appSubdomain = drawerAuthorizedApps[0]; const event = { origin: `https://${appSubdomain}.proton.me`, data: { type: 'something else', }, } as MessageEvent; expect(getIsDrawerPostMessage(event)).toBeFalsy(); }); }); describe('postMessageFromIframe', () => { beforeEach(() => { mockWindowLocation({ hostname: windowHostname }); }); afterEach(() => { resetWindowLocation(); }); it('should post a message from the iframe', () => { const spy = spyOn(window.parent, 'postMessage'); const message: DRAWER_ACTION = { type: DRAWER_EVENTS.READY, }; authorizedApps.forEach((app) => { const parentApp = app as APP_NAMES; postMessageFromIframe(message, parentApp); const sentMessage = { ...message, }; const targetOrigin = `http://${APPS_CONFIGURATION[parentApp].subdomain}.proton.me`; // @ts-ignore expect(spy).toHaveBeenCalledWith(sentMessage, targetOrigin); }); }); it('should not post a message from the iframe', () => { const spy = spyOn(window.parent, 'postMessage'); const message: DRAWER_ACTION = { type: DRAWER_EVENTS.READY, }; Object.values(APPS).forEach((app) => { if (!drawerAuthorizedApps.includes(APPS_CONFIGURATION[app].subdomain)) { postMessageFromIframe(message, app); expect(spy).not.toHaveBeenCalled(); } }); }); }); describe('addParentAppToUrl', () => { it('should add parent app to URL and replace path', () => { const urlParams = 'Action=VIEW&EventID=eventID&RecurrenceID=1670835600'; const url = `https://calendar.proton.pink/u/0/event?${urlParams}`; const currentApp = APPS.PROTONMAIL; const expected = `https://calendar.proton.pink/u/0/mail?${urlParams}`; expect(addParentAppToUrl(url, currentApp, true)).toEqual(expected); }); it('should add parent app to URL and not replace path', () => { const path = '/something'; const url = `https://calendar.proton.pink/u/0${path}`; const currentApp = APPS.PROTONMAIL; const expected = `https://calendar.proton.pink/u/0/mail${path}`; expect(addParentAppToUrl(url, currentApp, false)).toEqual(expected); }); }); describe('getDisplayContactsInDrawer', () => { it('should be possible to display contacts in Drawer', () => { const apps: APP_NAMES[] = [APPS.PROTONMAIL, APPS.PROTONCALENDAR, APPS.PROTONDRIVE]; apps.forEach((app) => { expect(getDisplayContactsInDrawer(app)).toBeTruthy(); }); }); it('should not be possible to display contacts in Drawer', () => { const apps: APP_NAMES[] = [APPS.PROTONACCOUNTLITE, APPS.PROTONACCOUNT]; apps.forEach((app) => { expect(getDisplayContactsInDrawer(app)).toBeFalsy(); }); }); }); describe('isAppInView', () => { it('should be the app in view', () => { const appInView = DRAWER_NATIVE_APPS.CONTACTS; const currentApp = DRAWER_NATIVE_APPS.CONTACTS; expect(isAppInView(currentApp, appInView)).toBeTruthy(); }); it('should not be the app in view', () => { const appInView = DRAWER_NATIVE_APPS.CONTACTS; const currentApp = APPS.PROTONCALENDAR; expect(isAppInView(currentApp, appInView)).toBeFalsy(); }); }); describe('getDisplayDrawerApp', () => { it('should be possible to open calendar app', () => { const apps: APP_NAMES[] = [APPS.PROTONMAIL, APPS.PROTONDRIVE]; apps.forEach((app) => { expect(getDisplayDrawerApp(app, APPS.PROTONCALENDAR)).toBeTruthy(); }); }); it('should not be possible to open calendar app', () => { const apps: APP_NAMES[] = [APPS.PROTONCALENDAR, APPS.PROTONCONTACTS, APPS.PROTONACCOUNT]; apps.forEach((app) => { expect(getDisplayDrawerApp(app, APPS.PROTONCALENDAR)).toBeFalsy(); }); }); it('should be possible to open contact app', () => { const apps: APP_NAMES[] = [APPS.PROTONMAIL, APPS.PROTONCALENDAR, APPS.PROTONDRIVE]; apps.forEach((app) => { expect(getDisplayDrawerApp(app, DRAWER_NATIVE_APPS.CONTACTS)).toBeTruthy(); }); }); it('should not be possible to open contacts app', () => { const apps: APP_NAMES[] = [APPS.PROTONCONTACTS, APPS.PROTONACCOUNT]; apps.forEach((app) => { expect(getDisplayDrawerApp(app, DRAWER_NATIVE_APPS.CONTACTS)).toBeFalsy(); }); }); }); });
8,829
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/eventManager/eventManager.spec.js
import createEventManager from '../../lib/eventManager/eventManager'; const mockApi = (responses) => { let i = 0; const cb = async () => { const response = responses[i++]; if (response instanceof Error) { throw response; } return response; }; return jasmine.createSpy('mockApi').and.callFake(cb); }; /** * TODO: More tests when https://stackoverflow.com/a/50785284 exists */ describe('event manager', () => { it('should call more and not finish until it is done', async () => { const api = mockApi([ { EventID: '1', More: 1 }, { EventID: '2', More: 1 }, { EventID: '3', More: 1 }, { EventID: '4', More: 1 }, { EventID: '5', More: 1 }, { EventID: '6', More: 0 }, { EventID: '6', More: 0 }, ]); const eventManager = createEventManager({ eventID: '1', api, interval: 1000, }); const onSuccess = jasmine.createSpy(); const unsubscribe = eventManager.subscribe(onSuccess); eventManager.start(); await eventManager.call(); expect(api.calls.all().length).toEqual(6); expect(onSuccess.calls.all().length).toEqual(6); await eventManager.call(); expect(api.calls.all().length, 7); expect(onSuccess.calls.all().length, 7); eventManager.stop(); unsubscribe(); }); });
8,830
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/eventManager/updateCollection.spec.ts
import { EVENT_ACTIONS } from '../../lib/constants'; import updateCollection from '../../lib/helpers/updateCollection'; describe('update collection', () => { it('should remove items', () => { const labels = [ { ID: '123', foo: 'bar', }, ]; const events = [ { ID: '123', Action: EVENT_ACTIONS.DELETE, }, ] as const; const newLabels = updateCollection({ model: labels, events, itemKey: 'Label', }); expect(newLabels).toEqual([]); }); it('should add items', () => { const labels = [ { ID: '123', foo: 'bar', }, ]; const events = [ { ID: '124', Action: EVENT_ACTIONS.CREATE, Label: { ID: '124', foo: 'bar2', }, }, ] as const; const newLabels = updateCollection({ model: labels, events, itemKey: 'Label' }); expect(newLabels).toEqual([ { ID: '123', foo: 'bar' }, { ID: '124', foo: 'bar2' }, ]); }); it('should update items', () => { const labels = [ { ID: '123', foo: 'bar', kept: true, }, ]; const events = [ { ID: '123', Action: EVENT_ACTIONS.UPDATE, Label: { ID: '123', foo: 'bar2', }, }, ] as const; const newLabels = updateCollection({ model: labels, events, itemKey: 'Label' }); expect(newLabels).toEqual([{ ID: '123', foo: 'bar2', kept: true }]); }); it('should delete, create and update items', () => { const labels = [ { ID: '123', foo: 'bar', }, ]; const events = [ { ID: '123', Action: EVENT_ACTIONS.UPDATE, Label: { ID: '123', foo: 'bar2', }, }, { ID: '123', Action: EVENT_ACTIONS.DELETE, }, { ID: '124', Action: EVENT_ACTIONS.UPDATE, Label: { ID: '124', foo: 'bar3', }, }, { ID: '124', Action: EVENT_ACTIONS.CREATE, Label: { ID: '124', foo: 'bar', }, }, ] as const; const newLabels = updateCollection({ model: labels, events, itemKey: 'Label', item: ({ Label }) => Label }); expect(newLabels).toEqual([{ ID: '124', foo: 'bar3' }]); }); describe('Sort collection', () => { it('should delete, create and update items and sort them', () => { const labels = [ { ID: '123', foo: 'bar', Order: 1, }, ]; const events = [ { ID: '123', Action: EVENT_ACTIONS.UPDATE, Label: { ID: '123', foo: 'bar2', }, }, { ID: '12345', Action: EVENT_ACTIONS.CREATE, Label: { ID: '12345', foo: 'monique', Order: 2, }, }, { ID: '124', Action: EVENT_ACTIONS.CREATE, Label: { ID: '124', foo: 'bar', Order: 3, }, }, ] as const; const newLabels = updateCollection({ model: labels, events, itemKey: 'Label', item: ({ Label }) => Label }); expect(newLabels).toEqual([ { ID: '123', foo: 'bar2', Order: 1 }, { ID: '12345', foo: 'monique', Order: 2 }, { ID: '124', foo: 'bar', Order: 3 }, ]); const events2 = [ { ID: '123', Action: EVENT_ACTIONS.DELETE, }, { ID: '124', Action: EVENT_ACTIONS.UPDATE, Label: { ID: '124', foo: 'bar3', Order: 1, }, }, ] as const; const newLabels2 = updateCollection({ model: newLabels, events: events2, itemKey: 'Label', item: ({ Label }) => Label, }); expect(newLabels2).toEqual([ { ID: '124', foo: 'bar3', Order: 1 }, { ID: '12345', foo: 'monique', Order: 2 }, ]); }); it('should delete, create and update items and not sort them', () => { const labels = [ { ID: '123', foo: 'bar', }, ]; const events = [ { ID: '123', Action: EVENT_ACTIONS.UPDATE, Label: { ID: '123', foo: 'bar2', }, }, { ID: '12345', Action: EVENT_ACTIONS.CREATE, Label: { ID: '12345', foo: 'monique', }, }, { ID: '124', Action: EVENT_ACTIONS.CREATE, Label: { ID: '124', foo: 'bar', }, }, ] as const; const newLabels = updateCollection({ model: labels, events, itemKey: 'Label' }); expect(newLabels).toEqual([ { ID: '123', foo: 'bar2' }, { ID: '12345', foo: 'monique' }, { ID: '124', foo: 'bar' }, ]); const events2 = [ { ID: '123', Action: EVENT_ACTIONS.DELETE, }, { ID: '124', Action: EVENT_ACTIONS.UPDATE, Label: { ID: '124', foo: 'bar3', }, }, ] as const; const newLabels2 = updateCollection({ model: newLabels, events: events2, itemKey: 'Label', item: ({ Label }) => Label, }); expect(newLabels2).toEqual([ { ID: '12345', foo: 'monique' }, { ID: '124', foo: 'bar3' }, ]); }); it('should delete, create and update items and not sort them by a custom key', () => { const labels = [ { ID: '122', foo: 'bar', counter: 3, }, { ID: '123', foo: 'bar', counter: 1, }, ]; const events = [ { ID: '123', Action: EVENT_ACTIONS.UPDATE, Label: { ID: '123', foo: 'bar2', counter: 5, }, }, { ID: '12345', Action: EVENT_ACTIONS.CREATE, Label: { ID: '12345', foo: 'monique', counter: 2, }, }, { ID: '124', Action: EVENT_ACTIONS.CREATE, Label: { ID: '124', foo: 'bar', counter: 3, }, }, ] as const; const newLabels = updateCollection({ model: labels, events, itemKey: 'Label', sortByKey: 'counter' }); expect(newLabels).toEqual([ { ID: '12345', foo: 'monique', counter: 2 }, { ID: '122', foo: 'bar', counter: 3 }, { ID: '124', foo: 'bar', counter: 3 }, { ID: '123', foo: 'bar2', counter: 5 }, ]); }); }); });
8,831
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/fetch/fetch.spec.js
import performRequest from '../../lib/fetch/fetch'; class FormDataMock { constructor() { this.data = {}; } append(name, key) { this.data[name] = key; } } const headersMock = { get: () => { return undefined; }, }; describe('fetch', () => { let preFetch; let preFormData; beforeEach(() => { preFetch = global.fetch; preFormData = global.FormData; global.FormData = FormDataMock; }); afterEach(() => { global.fetch = preFetch; global.FormData = preFormData; }); const setup = (fn) => { const spy = jasmine.createSpy('fetch').and.callFake(fn); global.fetch = spy; return spy; }; it('should be able to receive json data', async () => { setup(async () => ({ json: async () => ({ bar: 1 }), status: 200, headers: headersMock })); const config = { url: 'http://foo.com/', }; const result = await performRequest(config).then((response) => response.json()); expect(result).toEqual({ bar: 1 }); }); it('should be able to receive blob data', async () => { setup(async () => ({ blob: async () => 123, status: 200, headers: headersMock })); const config = { url: 'http://foo.com/', output: 'blob', }; const result = await performRequest(config).then((response) => response.blob()); expect(result).toEqual(123); }); it('should be able to send json data', async () => { const spy = setup(async () => ({ json: async () => ({ bar: 1 }), status: 200, headers: headersMock })); const config = { url: 'http://foo.com/', data: { foo: 'bar', }, }; await performRequest(config).then((response) => response.json()); expect(spy.calls.all()[0].args).toEqual([ new URL(config.url), jasmine.objectContaining({ mode: 'cors', credentials: 'include', redirect: 'follow', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(config.data), }), ]); }); it('should be able to send form data', async () => { const spy = setup(async () => ({ json: async () => ({ bar: 1 }), status: 200, headers: headersMock })); const config = { url: 'http://foo.com/', input: 'form', data: { foo: 'bar', }, }; await performRequest(config).then((response) => response.json()); const fd = new FormData(); fd.append('foo', 'bar'); expect(spy.calls.all()[0].args).toEqual([ new URL(config.url), jasmine.objectContaining({ mode: 'cors', credentials: 'include', redirect: 'follow', headers: {}, body: fd, }), ]); }); it('should throw on 400 error and include the config, data and status', async () => { setup(async () => ({ json: async () => ({ bar: 1 }), status: 400, headers: headersMock })); const config = { url: 'http://foo.com/', suppress: [123], }; await expectAsync(performRequest(config)).toBeRejectedWith( jasmine.objectContaining({ name: 'StatusCodeError', message: '', status: 400, data: { bar: 1 }, config: jasmine.objectContaining({ suppress: [123], mode: 'cors', credentials: 'include', redirect: 'follow', headers: {}, body: undefined, }), }) ); }); });
8,832
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/bitset.spec.js
import { clearBit, hasBit, setBit, toggleBit } from '../../lib/helpers/bitset'; describe('bitset', () => { describe('setBit', () => { it('should handle empty parameter', () => { expect(setBit()).toEqual(0); expect(setBit({}, 0b1)).toEqual(0b1); }); it('should add a new flag', () => { expect(setBit(0b01, 0b10)).toEqual(0b11); }); it('should add a new flag if possible', () => { expect(setBit(0b1, 0b1)).toEqual(0b1); }); }); describe('hasBit', () => { it('should handle empty parameter', () => { expect(hasBit()).toEqual(false); expect(hasBit({}, 0b1)).toEqual(false); }); it('should handle first bit', () => { expect(hasBit(0b1, 0b1)).toEqual(true); expect(hasBit(0b0, 0b1)).toEqual(false); }); it('should handle multiple bits', () => { expect(hasBit(0b11, 0b10)).toEqual(true); expect(hasBit(0b11, 0b01)).toEqual(true); expect(hasBit(0b01, 0b10)).toEqual(false); expect(hasBit(0b11, 0b11)).toEqual(true); }); }); describe('toggleBit', () => { it('should handle empty parameter', () => { expect(toggleBit()).toEqual(0); expect(toggleBit({}, 0b1)).toEqual(0b1); }); it('should toggle a flag', () => { expect(toggleBit(0b1, 0b1)).toEqual(0b0); }); it('should remove a flag', () => { expect(toggleBit(0b10, 0b10)).toEqual(0b00); }); it('should remove a flag and keep the other', () => { expect(toggleBit(0b11, 0b10)).toEqual(0b01); }); it('should add a new flag if possible', () => { expect(toggleBit(0b10, 0b01)).toEqual(0b11); }); }); describe('clearBit', () => { it('should handle empty parameter', () => { expect(clearBit()).toEqual(0); }); it('should remove the flag', () => { expect(clearBit(0b11, 0b10)).toEqual(0b01); }); it('should remove the flag only if it exists', () => { expect(clearBit(0b1, 0b1)).toEqual(0); expect(clearBit(0b1, 0b10)).toEqual(0b1); }); }); });
8,833
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/card.spec.ts
import { SavedCardDetails, isExpired } from '@proton/components/payments/core'; describe('card helpers', () => { it('should return false if card not expired', () => { const currentYear = new Date().getFullYear(); const ExpYear = '' + (currentYear + 10); const cardDetails: SavedCardDetails = { Name: 'Arthur Morgan', ExpMonth: '01', ExpYear, ZIP: '11111', Country: 'US', Last4: '4242', Brand: 'Visa', }; expect(isExpired(cardDetails)).toEqual(false); }); it('should return true if card expired', () => { const currentYear = new Date().getFullYear(); const ExpYear = '' + (currentYear - 1); const cardDetails: SavedCardDetails = { Name: 'Arthur Morgan', ExpMonth: '01', ExpYear, ZIP: '11111', Country: 'US', Last4: '4242', Brand: 'Visa', }; expect(isExpired(cardDetails)).toEqual(true); }); it('should return false if there is no card details', () => { expect(isExpired({})).toEqual(false); }); });
8,834
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/checkout.spec.ts
import { ADDON_NAMES, CYCLE, PLANS, PLAN_TYPES } from '@proton/shared/lib/constants'; import { getCheckout, getUsersAndAddons } from '@proton/shared/lib/helpers/checkout'; import { PLANS_MAP } from '@proton/testing/data'; import { Plan } from '../../lib/interfaces'; const getPlan = (data: Partial<Plan>) => { return { ...data, Type: PLAN_TYPES.PLAN } as Plan; }; const getAddon = (data: Partial<Plan>) => { return { ...data, Type: PLAN_TYPES.ADDON } as Plan; }; const vpnPlan: Partial<Plan> = { Name: PLANS.VPN, Title: 'VPN', Pricing: { [CYCLE.MONTHLY]: 999, [CYCLE.YEARLY]: 7188, [CYCLE.FIFTEEN]: 14985, [CYCLE.TWO_YEARS]: 11976, [CYCLE.THIRTY]: 29970, }, DefaultPricing: { [CYCLE.MONTHLY]: 999, [CYCLE.YEARLY]: 7188, [CYCLE.FIFTEEN]: 14985, [CYCLE.TWO_YEARS]: 11976, [CYCLE.THIRTY]: 29970, }, }; const visionaryPlan: Partial<Plan> = { Name: PLANS.NEW_VISIONARY, Title: 'VIS', MaxMembers: 6, Pricing: { [CYCLE.MONTHLY]: 2999, [CYCLE.YEARLY]: 28788, [CYCLE.TWO_YEARS]: 47976, }, DefaultPricing: { [CYCLE.MONTHLY]: 2999, [CYCLE.YEARLY]: 28788, [CYCLE.TWO_YEARS]: 47976, }, }; const bundleProPlan: Partial<Plan> = { Name: PLANS.BUNDLE_PRO, Title: 'BUS', MaxMembers: 1, Pricing: { [CYCLE.MONTHLY]: 1299, [CYCLE.YEARLY]: 13188, [CYCLE.TWO_YEARS]: 23976, }, DefaultPricing: { [CYCLE.MONTHLY]: 1299, [CYCLE.YEARLY]: 13188, [CYCLE.TWO_YEARS]: 23976, }, }; const bundleProMember: Partial<Plan> = { Name: ADDON_NAMES.MEMBER_BUNDLE_PRO, MaxMembers: 1, Pricing: { [CYCLE.MONTHLY]: 1299, [CYCLE.YEARLY]: 13188, [CYCLE.TWO_YEARS]: 23976, }, DefaultPricing: { [CYCLE.MONTHLY]: 1299, [CYCLE.YEARLY]: 13188, [CYCLE.TWO_YEARS]: 23976, }, }; const bundleProDomain: Partial<Plan> = { Name: ADDON_NAMES.DOMAIN_BUNDLE_PRO, MaxDomains: 1, Pricing: { [CYCLE.MONTHLY]: 150, [CYCLE.YEARLY]: 1680, [CYCLE.TWO_YEARS]: 3120, }, DefaultPricing: { [CYCLE.MONTHLY]: 150, [CYCLE.YEARLY]: 1680, [CYCLE.TWO_YEARS]: 3120, }, }; const vpnProPlan = PLANS_MAP[PLANS.VPN_PRO] as Plan; const vpnProMember = PLANS_MAP[ADDON_NAMES.MEMBER_VPN_PRO] as Plan; const vpnBusinessPlan = PLANS_MAP[PLANS.VPN_BUSINESS] as Plan; const vpnBusinessMember = PLANS_MAP[ADDON_NAMES.MEMBER_VPN_BUSINESS] as Plan; describe('should get checkout result', () => { it('should calculate vpn plus', () => { expect( getCheckout({ planIDs: { [PLANS.VPN]: 1, }, checkResult: { Amount: 999, AmountDue: 999, Cycle: CYCLE.MONTHLY, Coupon: null, }, plansMap: { [PLANS.VPN]: getPlan(vpnPlan), }, }) ).toEqual({ couponDiscount: undefined, planTitle: 'VPN', planName: PLANS.VPN, usersTitle: '1 user', users: 1, addons: [], withDiscountPerCycle: 999, withDiscountPerMonth: 999, withoutDiscountPerMonth: 999, discountPerCycle: 0, discountPercent: 0, membersPerMonth: 999, addonsPerMonth: 0, }); }); it('should correctly handle the price increases', () => { expect( getCheckout({ planIDs: { [PLANS.VPN]: 1, }, checkResult: { Amount: 1199, AmountDue: 1199, Cycle: CYCLE.MONTHLY, Coupon: null, }, plansMap: { [PLANS.VPN]: { ...getPlan(vpnPlan), Pricing: { // It's possible to create an offer that would INCREASE the price [CYCLE.MONTHLY]: 1199, [CYCLE.YEARLY]: 7188, [CYCLE.FIFTEEN]: 14985, [CYCLE.TWO_YEARS]: 11976, [CYCLE.THIRTY]: 29970, }, DefaultPricing: { // And then the default price would be lower than the current price [CYCLE.MONTHLY]: 999, [CYCLE.YEARLY]: 7188, [CYCLE.FIFTEEN]: 14985, [CYCLE.TWO_YEARS]: 11976, [CYCLE.THIRTY]: 29970, }, }, }, }) ).toEqual({ couponDiscount: undefined, planTitle: 'VPN', planName: PLANS.VPN, usersTitle: '1 user', users: 1, addons: [], // We don't want to show the price increase to the user, so we use the maximum of Pricing and // DefaultPricing as basis for the calculation. We go with Pricing in this case. withDiscountPerCycle: 1199, withDiscountPerMonth: 1199, withoutDiscountPerMonth: 1199, discountPerCycle: 0, discountPercent: 0, membersPerMonth: 1199, addonsPerMonth: 0, }); }); it('should correctly handle the price decrease', () => { expect( getCheckout({ planIDs: { [PLANS.VPN]: 1, }, checkResult: { Amount: 799, AmountDue: 799, Cycle: CYCLE.MONTHLY, Coupon: null, }, plansMap: { [PLANS.VPN]: { ...getPlan(vpnPlan), Pricing: { // It's possible to create an offer that would decrease the price [CYCLE.MONTHLY]: 799, [CYCLE.YEARLY]: 7188, [CYCLE.FIFTEEN]: 14985, [CYCLE.TWO_YEARS]: 11976, [CYCLE.THIRTY]: 29970, }, DefaultPricing: { // And then the default price would be higher than the current price [CYCLE.MONTHLY]: 999, [CYCLE.YEARLY]: 7188, [CYCLE.FIFTEEN]: 14985, [CYCLE.TWO_YEARS]: 11976, [CYCLE.THIRTY]: 29970, }, }, }, }) ).toEqual({ couponDiscount: undefined, planTitle: 'VPN', planName: PLANS.VPN, usersTitle: '1 user', users: 1, addons: [], withDiscountPerCycle: 799, withDiscountPerMonth: 799, withoutDiscountPerMonth: 999, discountPerCycle: 200, discountPercent: 20, membersPerMonth: 799, addonsPerMonth: 0, }); }); it('should calculate bf 24 month visionary', () => { expect( getCheckout({ planIDs: { [PLANS.NEW_VISIONARY]: 1, }, checkResult: { Amount: 47976, AmountDue: 47976, CouponDiscount: -4776, Cycle: CYCLE.TWO_YEARS, Coupon: { Code: 'TEST', Description: '', }, }, plansMap: { [PLANS.NEW_VISIONARY]: getPlan(visionaryPlan), }, }) ).toEqual({ couponDiscount: -4776, planTitle: 'VIS', planName: PLANS.NEW_VISIONARY, usersTitle: '6 users', users: 6, addons: [], withDiscountPerCycle: 43200, withDiscountPerMonth: 1800, withoutDiscountPerMonth: 2999, discountPerCycle: 28776, discountPercent: 40, membersPerMonth: 11994, addonsPerMonth: 0, }); }); it('should calculate bf 30 month vpn plus', () => { expect( getCheckout({ planIDs: { [PLANS.VPN]: 1, }, checkResult: { Amount: 29970, AmountDue: 29970, CouponDiscount: -17994, Cycle: CYCLE.THIRTY, Coupon: { Code: 'TEST', Description: '', }, }, plansMap: { [PLANS.VPN]: getPlan(vpnPlan), }, }) ).toEqual({ couponDiscount: -17994, planTitle: 'VPN', planName: PLANS.VPN, usersTitle: '1 user', users: 1, addons: [], withDiscountPerCycle: 11976, withDiscountPerMonth: 399.2, withoutDiscountPerMonth: 999, discountPerCycle: 17994, discountPercent: 60, membersPerMonth: 999, addonsPerMonth: 0, }); }); it('should calculate business with addons', () => { expect( getCheckout({ planIDs: { [PLANS.BUNDLE_PRO]: 1, [ADDON_NAMES.MEMBER_BUNDLE_PRO]: 2, [ADDON_NAMES.DOMAIN_BUNDLE_PRO]: 3, }, checkResult: { Amount: 81288, AmountDue: 81288, CouponDiscount: 0, Cycle: CYCLE.TWO_YEARS, Coupon: null, }, plansMap: { [PLANS.BUNDLE_PRO]: getPlan(bundleProPlan), [ADDON_NAMES.MEMBER_BUNDLE_PRO]: getAddon(bundleProMember), [ADDON_NAMES.DOMAIN_BUNDLE_PRO]: getAddon(bundleProDomain), }, }) ).toEqual({ couponDiscount: 0, planTitle: 'BUS', planName: PLANS.BUNDLE_PRO, usersTitle: '3 users', users: 3, addons: [ { name: ADDON_NAMES.DOMAIN_BUNDLE_PRO, quantity: 3, title: '3 custom domains', pricing: { [CYCLE.MONTHLY]: 150, [CYCLE.YEARLY]: 1680, [CYCLE.TWO_YEARS]: 3120, }, }, ], withDiscountPerCycle: 81288, withDiscountPerMonth: 3387, withoutDiscountPerMonth: 4347, discountPerCycle: 23040, discountPercent: 22, membersPerMonth: 2997, addonsPerMonth: 390, }); }); it('should calculate VPN PRO with addons', () => { const twoYearPrice3Members = (vpnProPlan.Pricing?.[CYCLE.TWO_YEARS] || 0) + (vpnProMember.Pricing?.[CYCLE.TWO_YEARS] || 0) * 2; const cost24MonthlyCycles3Members = (vpnProPlan.Pricing?.[CYCLE.MONTHLY] || 0) * 24 + (vpnProMember.Pricing?.[CYCLE.MONTHLY] || 0) * 24 * 2; expect( getCheckout({ planIDs: { [PLANS.VPN_PRO]: 1, [ADDON_NAMES.MEMBER_VPN_PRO]: 2, }, checkResult: { Amount: twoYearPrice3Members, AmountDue: twoYearPrice3Members, CouponDiscount: 0, Cycle: CYCLE.TWO_YEARS, Coupon: null, }, plansMap: { [PLANS.VPN_PRO]: getPlan(vpnProPlan), [ADDON_NAMES.MEMBER_VPN_PRO]: getAddon(vpnProMember), }, }) ).toEqual({ couponDiscount: 0, planTitle: 'VPN Essentials', planName: PLANS.VPN_PRO, usersTitle: '4 users', users: 4, addons: [], withDiscountPerCycle: twoYearPrice3Members, withDiscountPerMonth: twoYearPrice3Members / 24, withoutDiscountPerMonth: 3594, discountPerCycle: cost24MonthlyCycles3Members - twoYearPrice3Members, discountPercent: 33, membersPerMonth: twoYearPrice3Members / 24, addonsPerMonth: 0, }); }); xit('should calculate VPN Business with addons', () => { const twoYearPrice3Members = (vpnBusinessPlan.Pricing?.[CYCLE.TWO_YEARS] || 0) + (vpnBusinessMember.Pricing?.[CYCLE.TWO_YEARS] || 0) * 2; const cost24MonthlyCycles3Members = (vpnBusinessPlan.Pricing?.[CYCLE.MONTHLY] || 0) * 24 + (vpnBusinessMember.Pricing?.[CYCLE.MONTHLY] || 0) * 24 * 2; expect( getCheckout({ planIDs: { [PLANS.VPN_BUSINESS]: 1, [ADDON_NAMES.MEMBER_VPN_BUSINESS]: 2, }, checkResult: { Amount: twoYearPrice3Members, AmountDue: twoYearPrice3Members, CouponDiscount: 0, Cycle: CYCLE.TWO_YEARS, Coupon: null, }, plansMap: { [PLANS.VPN_BUSINESS]: getPlan(vpnBusinessPlan), [ADDON_NAMES.MEMBER_VPN_BUSINESS]: getAddon(vpnBusinessMember), }, }) ).toEqual({ couponDiscount: 0, planTitle: 'VPN Business', planName: PLANS.VPN_BUSINESS, usersTitle: '3 users', users: 3, addons: [ { name: ADDON_NAMES.IP_VPN_BUSINESS, quantity: 1, pricing: { 1: 4999, 12: 47988, 24: 86376 }, title: '1 server', }, ], withDiscountPerCycle: twoYearPrice3Members, withDiscountPerMonth: twoYearPrice3Members / 24, withoutDiscountPerMonth: 1800, discountPerCycle: cost24MonthlyCycles3Members - twoYearPrice3Members, discountPercent: 17, membersPerMonth: twoYearPrice3Members / 24, addonsPerMonth: 3599, }); }); it('should calculate 100% discount', () => { expect( getCheckout({ planIDs: { [PLANS.NEW_VISIONARY]: 1, }, checkResult: { Amount: 47976, AmountDue: 0, CouponDiscount: -47976, Cycle: CYCLE.TWO_YEARS, Coupon: { Code: 'TEST', Description: '', }, }, plansMap: { [PLANS.NEW_VISIONARY]: getPlan(visionaryPlan), }, }) ).toEqual({ couponDiscount: -47976, planTitle: 'VIS', planName: PLANS.NEW_VISIONARY, usersTitle: '6 users', users: 6, addons: [], withDiscountPerCycle: 0, withDiscountPerMonth: 0, withoutDiscountPerMonth: 2999, discountPerCycle: 71976, discountPercent: 100, membersPerMonth: 11994, addonsPerMonth: 0, }); }); }); describe('getUsersAndAddons()', () => { it('should return plan name and number of users', () => { expect( getUsersAndAddons( { [PLANS.VPN]: 1, }, { [PLANS.VPN]: getPlan(vpnPlan), } ) ).toEqual({ planName: PLANS.VPN, planTitle: 'VPN', users: 1, usersPricing: { [CYCLE.MONTHLY]: 999, [CYCLE.YEARLY]: 7188, [CYCLE.FIFTEEN]: 14985, [CYCLE.TWO_YEARS]: 11976, [CYCLE.THIRTY]: 29970, }, addons: [], }); }); it('should return plan name and number of users - family plan', () => { expect( getUsersAndAddons( { [PLANS.FAMILY]: 1, }, { [PLANS.FAMILY]: PLANS_MAP[PLANS.FAMILY], } ) ).toEqual({ planName: PLANS.FAMILY, planTitle: 'Proton Family', users: 6, // even though there are 6 users, we don't divide the price by 6 for family plan. That's intentional. usersPricing: { [CYCLE.MONTHLY]: 2999, [CYCLE.YEARLY]: 28788, [CYCLE.TWO_YEARS]: 47976, }, addons: [], }); }); it('should return plan name and number of users - VPN Essentials', () => { expect( getUsersAndAddons( { [PLANS.VPN_PRO]: 1, }, { [PLANS.VPN_PRO]: PLANS_MAP[PLANS.VPN_PRO], [ADDON_NAMES.MEMBER_VPN_PRO]: PLANS_MAP[ADDON_NAMES.MEMBER_VPN_PRO], } ) ).toEqual({ planName: PLANS.VPN_PRO, planTitle: 'VPN Essentials', // VPN Essentials has 2 users by default users: 2, usersPricing: { [CYCLE.MONTHLY]: 899, [CYCLE.YEARLY]: 8388, [CYCLE.TWO_YEARS]: 14376, }, addons: [], }); }); it('should return plan name and number of users - VPN Essentials with addons', () => { expect( getUsersAndAddons( { [PLANS.VPN_PRO]: 1, [ADDON_NAMES.MEMBER_VPN_PRO]: 4, }, { [PLANS.VPN_PRO]: PLANS_MAP[PLANS.VPN_PRO], [ADDON_NAMES.MEMBER_VPN_PRO]: PLANS_MAP[ADDON_NAMES.MEMBER_VPN_PRO], } ) ).toEqual({ planName: PLANS.VPN_PRO, planTitle: 'VPN Essentials', // VPN Essentials has 2 users by default + 4 addons selected by user users: 6, usersPricing: { [CYCLE.MONTHLY]: 899, [CYCLE.YEARLY]: 8388, [CYCLE.TWO_YEARS]: 14376, }, addons: [], }); }); it('should return plan name and number of users - VPN Business', () => { expect( getUsersAndAddons( { [PLANS.VPN_BUSINESS]: 1, }, { [PLANS.VPN_BUSINESS]: PLANS_MAP[PLANS.VPN_BUSINESS], [ADDON_NAMES.MEMBER_VPN_BUSINESS]: PLANS_MAP[ADDON_NAMES.MEMBER_VPN_BUSINESS], [ADDON_NAMES.IP_VPN_BUSINESS]: PLANS_MAP[ADDON_NAMES.IP_VPN_BUSINESS], } ) ).toEqual({ planName: PLANS.VPN_BUSINESS, planTitle: 'VPN Business', // VPN Business has 2 users by default users: 2, usersPricing: { [CYCLE.MONTHLY]: 1199, [CYCLE.YEARLY]: 11988, [CYCLE.TWO_YEARS]: 21576, }, addons: [ // Yes, there must be addon even though the user didn't specify them. Because for price calculation // purposes we must take into account the fact that VPN Business has 2 members + 1 server by default { name: ADDON_NAMES.IP_VPN_BUSINESS, title: '1 server', quantity: 1, pricing: { 1: 4999, 12: 47988, 24: 86376 }, }, ], }); }); it('should return plan name and number of users - VPN Business with users', () => { expect( getUsersAndAddons( { [PLANS.VPN_BUSINESS]: 1, [ADDON_NAMES.MEMBER_VPN_BUSINESS]: 4, }, { [PLANS.VPN_BUSINESS]: PLANS_MAP[PLANS.VPN_BUSINESS], [ADDON_NAMES.MEMBER_VPN_BUSINESS]: PLANS_MAP[ADDON_NAMES.MEMBER_VPN_BUSINESS], [ADDON_NAMES.IP_VPN_BUSINESS]: PLANS_MAP[ADDON_NAMES.IP_VPN_BUSINESS], } ) ).toEqual({ planName: PLANS.VPN_BUSINESS, planTitle: 'VPN Business', // VPN Business has 2 users by default + 4 addons selected by user users: 6, usersPricing: { [CYCLE.MONTHLY]: 1199, [CYCLE.YEARLY]: 11988, [CYCLE.TWO_YEARS]: 21576, }, addons: [ // Yes, there must be addon even though the user didn't specify them. Because for price calculation // purposes we must take into account the fact that VPN Business has 2 members + 1 server by default { name: ADDON_NAMES.IP_VPN_BUSINESS, title: '1 server', quantity: 1, pricing: { 1: 4999, 12: 47988, 24: 86376 }, }, ], }); }); it('should return plan name and number of users - VPN Business with IPs', () => { expect( getUsersAndAddons( { [PLANS.VPN_BUSINESS]: 1, [ADDON_NAMES.IP_VPN_BUSINESS]: 4, }, { [PLANS.VPN_BUSINESS]: PLANS_MAP[PLANS.VPN_BUSINESS], [ADDON_NAMES.MEMBER_VPN_BUSINESS]: PLANS_MAP[ADDON_NAMES.MEMBER_VPN_BUSINESS], [ADDON_NAMES.IP_VPN_BUSINESS]: PLANS_MAP[ADDON_NAMES.IP_VPN_BUSINESS], } ) ).toEqual({ planName: PLANS.VPN_BUSINESS, planTitle: 'VPN Business', // VPN Business has 2 users by default users: 2, usersPricing: { [CYCLE.MONTHLY]: 1199, [CYCLE.YEARLY]: 11988, [CYCLE.TWO_YEARS]: 21576, }, addons: [ { // Yes, there must be 5 addons instead of 4 that were specified by user. // See the comments in the other tests. name: ADDON_NAMES.IP_VPN_BUSINESS, quantity: 5, pricing: { 1: 4999, 12: 47988, 24: 86376 }, title: '5 servers', }, ], }); }); it('should return plan name and number of users - VPN Business with users and IPs', () => { expect( getUsersAndAddons( { [PLANS.VPN_BUSINESS]: 1, [ADDON_NAMES.MEMBER_VPN_BUSINESS]: 4, [ADDON_NAMES.IP_VPN_BUSINESS]: 4, }, { [PLANS.VPN_BUSINESS]: PLANS_MAP[PLANS.VPN_BUSINESS], [ADDON_NAMES.MEMBER_VPN_BUSINESS]: PLANS_MAP[ADDON_NAMES.MEMBER_VPN_BUSINESS], [ADDON_NAMES.IP_VPN_BUSINESS]: PLANS_MAP[ADDON_NAMES.IP_VPN_BUSINESS], } ) ).toEqual({ planName: PLANS.VPN_BUSINESS, planTitle: 'VPN Business', // VPN Business has 2 users by default + 4 addons selected by user users: 6, usersPricing: { [CYCLE.MONTHLY]: 1199, [CYCLE.YEARLY]: 11988, [CYCLE.TWO_YEARS]: 21576, }, addons: [ { // Yes, there must be 5 addons instead of 4 that were specified by user. // See the comments in the other tests. name: ADDON_NAMES.IP_VPN_BUSINESS, quantity: 5, pricing: { 1: 4999, 12: 47988, 24: 86376 }, title: '5 servers', }, ], }); }); });
8,835
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/contacts.spec.ts
import { getContactImageSource } from '../../lib/helpers/contacts'; import { mockWindowLocation, resetWindowLocation } from './url.helper'; const uid = 'uid'; const originalURL = 'https://originalURL.com'; const windowOrigin = 'https://mail.proton.pink'; describe('getContactImageSource', () => { beforeEach(() => { mockWindowLocation({ origin: windowOrigin }); }); afterEach(() => { resetWindowLocation(); }); it('should return the original url of the image', () => { const result = getContactImageSource('api', originalURL, uid, false); const expected = originalURL; expect(result).toEqual(expected); }); it('should return the forged url of the image to load it through Proton proxy', () => { const result = getContactImageSource('api', originalURL, uid, true); const expected = `${windowOrigin}/api/core/v4/images?Url=${encodeURIComponent( originalURL )}&DryRun=0&UID=${uid}`; expect(result).toEqual(expected); }); it('should load the image from base64', () => { const base64 = 'data:image/jpeg;base64, DATA'; const result = getContactImageSource('api', base64, uid, false); const expected = base64; expect(result).toEqual(expected); }); });
8,836
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/cookie.spec.js
import { getCookie, setCookie } from '../../lib/helpers/cookies'; describe('cookie helper', () => { afterEach(() => { document.cookie.split(';').forEach((c) => { document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`); }); }); it('should set cookie', () => { setCookie({ cookieName: 'name', cookieValue: '123', }); expect(document.cookie).toEqual('name=123'); }); it('should clear cookies', () => { setCookie({ cookieName: 'name', cookieValue: '121', }); expect(document.cookie).toEqual('name=121'); setCookie({ cookieName: 'name', cookieValue: undefined, }); expect(document.cookie).toEqual(''); }); it('should expire cookies', () => { setCookie({ cookieName: 'name', cookieValue: '125', expirationDate: new Date(2025, 0).toUTCString(), }); // Can't actually check expires expect(document.cookie).toEqual('name=125'); }); it('should get cookie', () => { document.cookie = 'name=124'; expect(getCookie('name')).toEqual('124'); }); it('should get first cookie if there are multiple', () => { expect(getCookie('0d938947', 'a=1; 0d938947=1; 0d938947=1; b=1')).toEqual('1'); }); it('should return undefined cookie if there is no match', () => { expect(getCookie('0d938947', 'a=1; b=1')).toBeUndefined(); }); it('should get first cookie if there is one', () => { expect(getCookie('0d938947', '0d938947=1')).toEqual('1'); }); });
8,837
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/crypto.spec.ts
import { xorEncryptDecrypt } from '../../lib/helpers/crypto'; describe('Crypto helpers', () => { describe('xorEncryptDecrypt', () => { it('encrypts and decrypts', () => { const key = 'dog'; const data = 'cat'; const xored = xorEncryptDecrypt({ key, data }); expect(xorEncryptDecrypt({ key, data: xored })).toEqual(data); }); it('does not strip trailing zeros when encrypting or decrypting', () => { const key = 'dogs'; const data = 'cats'; const xored = xorEncryptDecrypt({ key, data }); // because the last letter of 'dogs' and 'cats' is the same, // xored will have a trailing 0 in its Uint8Array representation expect(xorEncryptDecrypt({ key, data: xored })).toEqual(data); }); }); });
8,838
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/dom.spec.ts
import { getMaxDepth, hasChildren } from '../../lib/helpers/dom'; describe('hasChildren', () => { it('should return false for text node', () => { expect(hasChildren(document.createTextNode('text'))).toBe(false); }); it('should return false for element', () => { expect(hasChildren(document.createElement('div'))).toBe(false); }); it('should return true for element with children', () => { const div = document.createElement('div'); div.appendChild(document.createElement('div')); expect(hasChildren(div)).toBe(true); }); }); describe('getMaxDepth', () => { beforeEach(() => { document.body.innerHTML = ` <div id="parent"> <div id="child"> <div id="grandchild"> <div id="greatgrandchild"> </div> </div> </div> <div></div> </div> `; }); it('should return 1 for text node', () => { expect(getMaxDepth(document.createTextNode('text'))).toBe(1); }); it('should return 1 for element', () => { expect(getMaxDepth(document.createElement('div'))).toBe(1); }); it('should return 4 for parent with children', () => { const div = document.getElementById('parent'); expect(getMaxDepth(div as HTMLDivElement)).toBe(4); }); it('should return 3 for element with children', () => { const div = document.getElementById('child'); expect(getMaxDepth(div as HTMLDivElement)).toBe(3); }); it('should return 2 for element with grandchildren', () => { const div = document.getElementById('grandchild'); expect(getMaxDepth(div as HTMLDivElement)).toBe(2); }); it('should return 1 for element with greatgrandchildren', () => { const div = document.getElementById('greatgrandchild'); expect(getMaxDepth(div as HTMLDivElement)).toBe(1); }); });
8,839
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/email.spec.ts
import { CANONICALIZE_SCHEME, canonicalizeEmail, canonicalizeEmailByGuess, canonicalizeInternalEmail, getEmailTo, parseMailtoURL, validateDomain, validateEmailAddress, } from '../../lib/helpers/email'; describe('email', () => { describe('validateDomain', () => { it('should accept valid domains', () => { const domains = [ 'protonmail.com', 'mail.proton.me.', 'vpn.at.proton.me', 'pro-ton.mail.com', 'xn--80ak6aa92e.com', '_dnslink.ipfs.io', 'n.mk', 'a-1234567890-1234567890-1234567890-1234567890-1234567890-1234-z.eu.us', 'external.asd1230-123.asd_internal.asd.gm-_ail.com', ]; const results = domains.map((domain) => validateDomain(domain)); const expected = domains.map(() => true); expect(results).toEqual(expected); }); it('should accept Web3 domains', () => { const domains = ['alice.eth.x', 'bob.888']; const results = domains.map((domain) => validateDomain(domain)); const expected = domains.map(() => true); expect(results).toEqual(expected); }); it('should reject invalid domains', () => { const domains = [ 'protonmail', '-mail.proton.me.', '1234', '[123.32]', 'pro*ton.mail.com', 'protonmail.com/', ]; const results = domains.map((domain) => validateDomain(domain)); const expected = domains.map(() => false); expect(results).toEqual(expected); }); }); describe('validateEmailAddress', () => { it('should validate good email addresses', () => { const emails = [ '[email protected]', '(comment)test+test(ot@" her)@pm.me', 'test@[192.168.1.1]', 'test(rare)@[192.168.12.23]', '(comment)"te@ st"(rare)@[192.168.12.23]', "weird!#$%&'*+-/=?^_`{|}[email protected]", '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '" "@example.org', '"john..doe"@example.org', '"john\\"doe"@example.org', '"john\\\\doe"@example.org', '[email protected]', 'user%[email protected]', 'customer/[email protected]', '[email protected]', '[email protected]', '!def!xyz%[email protected]', '1234567890123456789012345678901234567890123456789012345678901234+x@a.example.com', ]; expect(emails.map((email) => validateEmailAddress(email)).filter(Boolean).length).toBe(emails.length); }); it('should not validate malformed email addresses', () => { const emails = [ 'hello', '[email protected]', '[email protected]', '[email protected]', 'test@[192.168.1.1.2]', 'test(rare)@[19245.168.12.23]', 'test@domain', '[email protected]', '[email protected]', 'test@[email protected]', 'franç[email protected]', 'asd,@asd.com', 'ezpañ[email protected]', 'Abc.example.com', 'A@b@[email protected]', 'a"b(c)d,e:f;g<h>i[j\\k][email protected]', 'just"not"[email protected]', 'this is"not\\[email protected]', 'this\\ still\\"not\\\\[email protected]', ]; expect(emails.map((email) => validateEmailAddress(email)).filter(Boolean).length).toBe(0); }); }); describe('canonicalize', () => { it('should canonicalize internal emails properly', () => { const emails = [ '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'no-DOM.a.in+one', 'NO_DOMAIN+two@', ]; const canonicalized = [ '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'nodomain', 'nodomain@', ]; expect(emails.map((email) => canonicalizeInternalEmail(email))).toEqual(canonicalized); }); it('should canonicalize with the gmail scheme', () => { const emails = [ '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'no-DOM.a.in+one', 'NO_DOMAIN+two@', ]; const canonicalized = [ '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'no-domain', 'no_domain@', ]; expect(emails.map((email) => canonicalizeEmail(email, CANONICALIZE_SCHEME.GMAIL))).toEqual(canonicalized); }); it('should canonicalize with the plus scheme', () => { const emails = [ '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'no-DOM.a.in+one', 'NO_DOMAIN+two@', ]; const canonicalized = [ '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'no-dom.a.in', 'no_domain@', ]; expect(emails.map((email) => canonicalizeEmail(email, CANONICALIZE_SCHEME.PLUS))).toEqual(canonicalized); }); it('should canonicalize guessing the scheme', () => { const emails = [ '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'no-DOM.a.in+one', 'NO_DOMAIN+two@', ]; const canonicalized = [ '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'no-dom.a.in+one', 'no_domain+two@', ]; expect(emails.map((email) => canonicalizeEmailByGuess(email))).toEqual(canonicalized); }); }); describe('parseMailtoURL', () => { it('should extract all "to emails" from the mailtoURL', () => { const mailtoURLs = [ 'mailTo:[email protected]', 'mailTo:gr%C3%[email protected]', 'mailto:[email protected]?body=send%20current-issue', 'mailto:[email protected],[email protected]', 'mailto:[email protected]?In-Reply-To=%[email protected]%3E', 'mailto:[email protected],[email protected][email protected],[email protected]', ]; const expected = [ ['[email protected]'], ['gró[email protected]'], ['[email protected]'], ['[email protected]', '[email protected]'], ['[email protected]'], ['[email protected]', '[email protected]', '[email protected]', '[email protected]'], ]; expect(mailtoURLs.map((to) => parseMailtoURL(to))).toEqual(expected.map((to) => ({ to }))); }); }); describe('getEmailTo', () => { it('should always return a string', () => { expect(getEmailTo('mailto:')).toBeInstanceOf(String); }); }); });
8,840
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/encoding.spec.ts
import { decodeBase64URL, encodeBase64URL, validateBase64string } from '../../lib/helpers/encoding'; describe('encoding', () => { describe('encodeBase64URL', () => { const validChars = '_-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; const strings = ['', 'The quick brown fox jumps over the lazy dog', '@#N{}|*sdgOnf&çÇéöªº', 'foobar']; it('should only use valid characters', () => { const filterEncode = (str: string) => encodeBase64URL(str) .split('') .filter((char) => validChars.includes(char)) .join(''); expect(strings.map((string) => encodeBase64URL(string))).toEqual(strings.map(filterEncode)); }); it('should roundtrip strings', () => { strings.forEach((string) => { expect(decodeBase64URL(encodeBase64URL(string))).toEqual(string); }); }); it('should keep padding when told to', () => { const string = 'dogs'; expect(encodeBase64URL(string)).toEqual('ZG9ncw'); expect(encodeBase64URL(string, false)).toEqual('ZG9ncw=='); }); }); describe('validateBase64', () => { it('should accept valid base64 strings', () => { const strings = ['u6eqY7+WQ29/NFIM', 'xpppt/D1BgxgJR=', '+++==', 'kZyjUaHmEp+aZG65nBuyxno===', 'A', '']; expect(strings.map((string) => validateBase64string(string))).toEqual(strings.map(() => true)); }); it('should refuse invalid base64 strings', () => { const strings = ['u6_qY7+WQ29/NFIM', 'xp-pt/D1BgxgJR=', 'kZyjUaHmEp+aZG65nBuyxno====', 'français']; expect(strings.map((string) => validateBase64string(string))).toEqual(strings.map(() => false)); }); it('should accept valid base64 strings with the variant alphabet', () => { const strings = [ 'LOtmC6pJ20mWneQs-8kE6', 'Wls6U2lgOn_3e4L9TUTedbmy26O4vZ6Yiw6iL_bI0qE1bHZtg=', '-DiyDdiBg5fAAiamijSA47AG9jZ-eIp4lFZ4inQQeKvdUGBJB66h1q65CHa_qicib0OkaC8W8ZUOq8icLzKiKw==', 'A', '', ]; expect(strings.map((string) => validateBase64string(string, true))).toEqual(strings.map(() => true)); }); it('should refuse invalid base64 strings with variant alphabet', () => { const strings = ['u6eqY7+WQ29/NFIM', 'xpppt/D1BgxgJR=', '+++==', 'kZyjUaHmEp_aZG65nBuyxno====', 'français']; expect(strings.map((string) => validateBase64string(string, true))).toEqual(strings.map(() => false)); }); }); });
8,841
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/file.data.js
// Filesize: 10.77 KB // Encoded: 14.36 KB // Width: 300 px // Height: 200 px export const img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAADICAIAAADdvUsCAAAgAElEQVR42u2deZRcRb3Hq3qZyQYBYghkYfNBEGSJEV5ejMhhMyjnPTRuR5+gIEuEEJYD6ANFDSiKnshOMAGiuESMwnMBjCKLgubImhjZHomJAbMIiSSTmZ7urvdHZ+7Urfr9fvWr23dm+t6ue3Jyum/f7umuW5/6fn+/2uTUqWeLcIQjHEN3FEIRhCMcQ3uUQhG0+CGlFEIZ5+i3KKWk1J+GUgwQhoPL205mpJRe1EHcmh8bIdk4pwKaAcJwxAmRCDPp/0EDVKWUlIHJAGE7Oszk/PDx5qDV+DKN/xs+NvAYIGx3/KSUSgkhlGxaE41P6KNLuYDsjy3DLQsQtgV7Der0SxosDLT1VUoJIZ1MBhoDhPlkrxGGRRc4NQ+5QMZ0TtmXUcFe31+Xmk4q8soAY4AwG+DRItYPJoaonappBnn9bF/XBUxm9M3xVI1kxpnhCBC2In58VRwEZdb+FsCUnqqxrwgeNUCYJfx87Ch2Jdevgkdf1EdkSg2lRL8q9s6AYoAwY/jp5+1r7AxNikFpXMHAfIzsGy1gdlRo7zXjxhAuBghbCz8Oe/SL2IXQ4DVjbI2ClJD4e2hnvdZRYaKFh5QhXAwQDr36AaAlYnInb5zBa8boNOSrxqi0yTQ66zFt5ISFwaAGCAeHQCZ+HjoJXS8JSWRUckVEmHpfPKiBTVIXUAwQDjl+qXhUatwMZ9QN4ksVUwNdNCo7YoSuDCQGCAc3/AOh8jppdFQw+jwUJw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lWXL2MdGuE3ZBR1rXQWJxU9DPgFCFsERYGsrm9nU9DBovbLWOWOLxjl/SvwbkMiZ+ORywlHgHAwUMSFzradqDaCcwg54sev+uDa++w0DP1SADBA2IqxIh4vxl8Cuy6QDj0/RwotM+PlNx3SF+ALELamQaV4w15C5vKi0Z3PV6JaDZogErBAX4CwhSUxUiEsNYrYUUGuNSqb+Ur0GqS+hAX+AoSZF0aeHTU4wbIyOqUoHa4OespwBvAChLkRRklcEM/HKH5vhJNS4o3kwqSBvQBhzmkkAj9sT0KRrJswPrWCu9FKYC9A2A40KjBuJGBoggvmHHyqsz4cAcI8x42a6KkmhsUkhxNc0z4cAcI2VUhr9fsmB6zZyAWtCxCGw0MkUYGC1psRvHgvEBggDEeagWU4cnL8P8uWy0ft+LVnAAAAAElFTkSuQmCC'; export const emojis = `abc🧠👀🎂🎲🕌📣☣️`;
8,842
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/file.spec.js
import { readFileAsBinaryString, readFileAsBuffer, readFileAsString, splitExtension, toBase64, } from '../../lib/helpers/file'; import { toFile } from '../../lib/helpers/image'; import { emojis, img } from './file.data'; describe('toBase64', () => { const type = 'image/png'; const filename = 'image'; let file; beforeAll(async () => { file = await toFile(img, filename); }); it('should be a string', async () => { const base64str = await toBase64(file); expect(typeof base64str).toBe('string'); expect(base64str).toMatch(/^data:\w+/); }); it('should be an empty base64 on undefined file', async () => { const base64str = await toBase64(await toFile(null, filename)); expect(base64str).toBe('data:application/octet-stream;base64,'); }); it('should be a 64 string encoded', async () => { const base64str = await toBase64(file); expect(typeof window.atob(base64str.replace('data:image/png;base64,', ''))).toBe('string'); }); it('should be equals to the original', async () => { const str1 = await toBase64(file); const f = await toFile(str1, filename); const str2 = await toBase64(f); expect(str1).toBe(str2); }); it('should keep the type', async () => { const base64str = await toBase64(file); const f = await toFile(base64str); expect(f.type).toBe(type); }); }); describe('readFile', () => { const filename = 'image'; let file; beforeAll(async () => { file = await toFile(img, filename); }); it('should be a an array buffer', async () => { const output = await readFileAsBuffer(file); expect(output instanceof ArrayBuffer).toBeTruthy(); }); it('should be a string !base 64', async () => { const output = await readFileAsBinaryString(file); expect(typeof output).toBe('string'); expect(output.startsWith('data:')).toBe(false); }); it('should throw an error if the file is not defined', async () => { try { await readFileAsBinaryString(null); } catch (e) { expect(typeof e.stack).toBe('string'); } }); const toTextFile = (text, filename, mime = 'text/plain') => { return new File([new Blob([text])], filename, { type: mime }); }; it('should read a utf-8 encoded file as a string', async () => { const output = await readFileAsString(toTextFile(emojis, 'emojis.txt')); expect(typeof output).toBe('string'); expect(output).toBe('abc🧠👀🎂🎲🕌📣☣️'); }); it('should read a utf-8 encoded file as a binary string', async () => { const output = await readFileAsBinaryString(toTextFile(emojis, 'emojis.txt')); expect(typeof output).toBe('string'); expect(output).toBe('abc🧠👀🎂🎲🕌📣☣️'); }); }); describe('splitExtension', () => { it('should return array with two empty strings for empty filename', () => { const split = splitExtension(''); expect(split).toEqual(['', '']); }); it('should split files with no extension', () => { const split = splitExtension('myFile'); expect(split).toEqual(['myFile', '']); }); it('should split files with no extension and a dot', () => { const split = splitExtension('myFile.'); expect(split).toEqual(['myFile', '']); }); it('should split properly files with strange characters', () => { const split = splitExtension('a-terrible.name/for_a.File.txt'); expect(split).toEqual(['a-terrible.name/for_a.File', 'txt']); }); it('should split files as expected', () => { const fileNames = ['myFile0.c', 'myFile1.py', 'myFile2.txt', 'myFile3.jpeg']; const expected = [ ['myFile0', 'c'], ['myFile1', 'py'], ['myFile2', 'txt'], ['myFile3', 'jpeg'], ]; expect(fileNames.map(splitExtension)).toEqual(expected); }); });
8,843
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/filters.spec.ts
import { Filter } from '@proton/components/containers/filters/interfaces'; import { FILTER_STATUS } from '@proton/shared/lib/constants'; import { hasReachedFiltersLimit } from '@proton/shared/lib/helpers/filters'; import { UserModel } from '@proton/shared/lib/interfaces'; describe('filters helpers', () => { it('should have reached filters limit on free user', () => { const user = { hasPaidMail: false } as UserModel; const filters: Filter[] = [{ Status: FILTER_STATUS.ENABLED } as Filter]; expect(hasReachedFiltersLimit(user, filters)).toBeTruthy(); }); it('should not have reached filters limit on free user when no filters', () => { const user = { hasPaidMail: false } as UserModel; const filters: Filter[] = []; expect(hasReachedFiltersLimit(user, filters)).toBeFalsy(); }); it('should not have reached filters limit on free user when filters are disabled', () => { const user = { hasPaidMail: false } as UserModel; const filters: Filter[] = [ { Status: FILTER_STATUS.DISABLED } as Filter, { Status: FILTER_STATUS.DISABLED } as Filter, ]; expect(hasReachedFiltersLimit(user, filters)).toBeFalsy(); }); it('should not have reached filters limit on paid user', () => { const user = { hasPaidMail: true } as UserModel; const filters: Filter[] = [ { Status: FILTER_STATUS.ENABLED } as Filter, { Status: FILTER_STATUS.ENABLED } as Filter, { Status: FILTER_STATUS.ENABLED } as Filter, { Status: FILTER_STATUS.DISABLED } as Filter, ]; expect(hasReachedFiltersLimit(user, filters)).toBeFalsy(); }); });
8,844
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/folders.spec.ts
import { hasReachedFolderLimit, hasReachedLabelLimit } from '@proton/shared/lib/helpers/folder'; import { Label, UserModel } from '@proton/shared/lib/interfaces'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; describe('folders helpers', () => { describe('hasReachedFolderLimit', () => { it('should have reached folders limit on free user', () => { const user = { hasPaidMail: false } as UserModel; const folders: Folder[] = [ { ID: 'folder1' } as Folder, { ID: 'folder2' } as Folder, { ID: 'folder3' } as Folder, ]; expect(hasReachedFolderLimit(user, folders)).toBeTruthy(); }); it('should not have reached folders limit on free user when no filters', () => { const user = { hasPaidMail: false } as UserModel; const folders: Folder[] = []; expect(hasReachedFolderLimit(user, folders)).toBeFalsy(); }); it('should not have reached folders limit on paid user', () => { const user = { hasPaidMail: true } as UserModel; const folders: Folder[] = [ { ID: 'folder1' } as Folder, { ID: 'folder2' } as Folder, { ID: 'folder3' } as Folder, { ID: 'folder4' } as Folder, ]; expect(hasReachedFolderLimit(user, folders)).toBeFalsy(); }); }); describe('hasReachedLabelsLimit', () => { it('should have reached labels limit on free user', () => { const user = { hasPaidMail: false } as UserModel; const labels: Label[] = [{ ID: 'label1' } as Label, { ID: 'label2' } as Label, { ID: 'label3' } as Label]; expect(hasReachedLabelLimit(user, labels)).toBeTruthy(); }); it('should not have reached labels limit on free user when no filters', () => { const user = { hasPaidMail: false } as UserModel; const labels: Label[] = []; expect(hasReachedLabelLimit(user, labels)).toBeFalsy(); }); it('should not have reached labels limit on paid user', () => { const user = { hasPaidMail: true } as UserModel; const labels: Label[] = [ { ID: 'label1' } as Label, { ID: 'label2' } as Label, { ID: 'label3' } as Label, { ID: 'label4' } as Label, ]; expect(hasReachedLabelLimit(user, labels)).toBeFalsy(); }); }); });
8,845
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/humanPrice.spec.ts
import humanPrice, { humanPriceWithCurrency } from '../../lib/helpers/humanPrice'; describe('humanPrice', () => { it('should return a String', () => { expect(humanPrice(111)).toBe('1.11'); }); it('should support divisor', () => { expect(humanPrice(100, 1)).toBe('100'); }); it('should support empty parameters', () => { expect(humanPrice()).toBe('0'); }); it('should remove .00 when needed', () => { expect(humanPrice(100)).toBe('1'); expect(humanPrice(120)).toBe('1.20'); expect(humanPrice(123)).toBe('1.23'); }); it('should return positive amount', () => { expect(humanPrice(-100)).toBe('1'); expect(humanPrice(-123)).toBe('1.23'); }); }); describe('humanPriceWithCurrency', () => { it('should return a String', () => { expect(humanPriceWithCurrency(111, 'EUR')).toBe('1.11 €'); }); it('should support divisor', () => { expect(humanPriceWithCurrency(100, 'EUR', 1)).toBe('100 €'); }); it('should throw an error if empty parameters', () => { // @ts-expect-error expect(() => humanPriceWithCurrency()).toThrow(); }); it('should remove .00 when needed', () => { expect(humanPriceWithCurrency(100, 'EUR')).toBe('1 €'); expect(humanPriceWithCurrency(120, 'EUR')).toBe('1.20 €'); expect(humanPriceWithCurrency(123, 'EUR')).toBe('1.23 €'); }); it('should support CHF', () => { expect(humanPriceWithCurrency(111, 'CHF')).toBe('CHF 1.11'); }); it('should support USD', () => { expect(humanPriceWithCurrency(111, 'USD')).toBe('$1.11'); }); it('should return negative amount', () => { expect(humanPriceWithCurrency(-123, 'EUR')).toBe('-1.23 €'); expect(humanPriceWithCurrency(-111, 'CHF')).toBe('-CHF 1.11'); expect(humanPriceWithCurrency(-111, 'USD')).toBe('-$1.11'); }); });
8,846
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/image.spec.js
import { encodeImageUri, forgeImageURL, formatImage, resizeImage, toBlob, toFile } from '../../lib/helpers/image'; import { img } from './file.data'; import { mockWindowLocation, resetWindowLocation } from './url.helper'; // width: 300 px, height: 200 px const MIMETYPE_REGEX = /data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/; const fileName = 'proton'; describe('encodeImageUri', () => { const domain = 'https://test.com'; [ { url: `${domain}/a space.png`, expected: `${domain}/a%20space.png` }, { url: `${domain}/a%20space.png`, expected: `${domain}/a%20space.png` }, { url: `${domain}/logo.png%22`, expected: `${domain}/logo.png%22` }, { url: `${domain}/logo.png&quot`, expected: `${domain}/logo.png&quot` }, ].forEach(({ url, expected }) => { it(`should encode image URI "${url}"`, () => { expect(encodeImageUri(url)).toEqual(expected); }); }); }); describe('forgeImageURL', () => { const windowOrigin = 'https://mail.proton.pink'; beforeEach(() => { mockWindowLocation({ origin: windowOrigin }); }); afterEach(() => { resetWindowLocation(); }); it('should forge the expected image URL', () => { const imageURL = 'https://example.com/image1.png'; const uid = 'uid'; const forgedURL = forgeImageURL('api', imageURL, uid); const expectedURL = `${windowOrigin}/api/core/v4/images?Url=${encodeURIComponent( imageURL )}&DryRun=0&UID=${uid}`; expect(forgedURL).toEqual(expectedURL); }); }); describe('toBlob', () => { it('it should be an instance of an Object', () => { expect(toBlob(img) instanceof Object).toBeTruthy(); }); it('it should be an instance of a Blob', () => { expect(toBlob(img) instanceof Blob).toBeTruthy(); }); }); describe('toFile', () => { it('it should be an instance of an Object', () => { expect(toFile(img) instanceof Object).toBeTruthy(); }); it('it should be an instance of a File', () => { expect(toFile(img) instanceof File).toBeTruthy(); }); it('it should have the correct name', () => { expect(toFile(img, fileName).name).toBe(fileName); }); }); describe('resizeImage', () => { it('it should be a string', async () => { const base64str = await resizeImage({ original: img, maxWidth: 100, maxHeight: 100 }); expect(typeof base64str).toBe('string'); }); it('it should be shorter than the original if resized', async () => { const base64str = await resizeImage({ original: img, maxWidth: 100, maxHeight: 100 }); expect(base64str.length).toBeLessThan(img.length); }); it('it should not be resized if the resize parameters coincide with the original image size', async () => { const base64str = await resizeImage({ original: img, maxWidth: 300, maxHeight: 200 }); expect(base64str.length).toBe(img.length); }); it('it should not be resized if the width resize parameters is bigger than the original and the height is ignored', async () => { const base64str = await resizeImage({ original: img, maxWidth: 900 }); expect(base64str.length).toBe(img.length); }); it('it should not be resized if the height resize parameters is bigger than the original and the width is ignored', async () => { const base64str = await resizeImage({ original: img, maxHeight: 400 }); expect(base64str.length).toBe(img.length); }); it('it should be a 64 string encoded', async () => { const base64str = await resizeImage({ original: img, maxWidth: 100, maxHeight: 100 }); expect(typeof window.atob(base64str.replace('data:image/jpeg;base64,', ''))).toBe('string'); }); it('it should be respect the MIMEType set', async () => { const base64str = await resizeImage({ original: img, maxWidth: 100, finalMimeType: 'image/png' }); expect(base64str.match(MIMETYPE_REGEX)[1]).toBe('image/png'); }); it('it should have a difference on image quality', async () => { const [base64str1, base64str2] = await Promise.all([ resizeImage({ original: img, maxWidth: 100, finalMimeType: 'image/jpeg', encoderOptions: 1 }), resizeImage({ original: img, maxWidth: 100, finalMimeType: 'image/jpeg', encoderOptions: 0.1 }), ]); expect(base64str1.length).toBeGreaterThan(base64str2.length); }); it('it should resize to the bigger possibility when biggerResize is true', async () => { const [base64str1, base64str2] = await Promise.all([ resizeImage({ original: img, maxWidth: 100, maxHeight: 100, bigResize: true }), resizeImage({ original: img, maxWidth: 100, maxHeight: 100 }), ]); expect(base64str1.length).toBeGreaterThan(base64str2.length); }); it('it should be lighter than the original', async () => { const base64str = await resizeImage({ original: img, maxWidth: 100 }); const resizedFile = toFile(base64str, 'file1'); const originalFile = toFile(img, 'file2'); expect(resizedFile.size).toBeLessThan(originalFile.size); }); }); describe('formatImage', () => { [ { output: '', name: 'return an empty string if no input', }, { input: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', output: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', name: 'return the input if it is a well-formed base64', }, { input: 'https://i.imgur.com/WScAnHr.jpg', output: 'https://i.imgur.com/WScAnHr.jpg', name: 'return the URL if it is an URL', }, { input: '/9j/4AAQSkZJRgABAQAAkACQAAD/4QB0RXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAIdpAAQAAAABAAAATgAAAAAAAACQAAAAAQAAAJAA', output: 'data:image/png;base64,/9j/4AAQSkZJRgABAQAAkACQAAD/4QB0RXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAIdpAAQAAAABAAAATgAAAAAAAACQAAAAAQAAAJAA', name: 'return a base64 if the input is not an URL nor a base64', }, ].forEach(({ name, input, output }) => { it(`should ${name}`, () => { expect(formatImage(input)).toBe(output); }); }); });
8,847
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/lru.spec.js
import createLRU from '../../lib/helpers/lru'; describe('lru', () => { [ { entries: [ ['a', '1'], ['b', '2'], ['c', '3'], ], max: 1, result: [['c', '3']], }, { entries: [ ['a', '1'], ['b', '2'], ], max: 2, result: [ ['a', '1'], ['b', '2'], ], }, { entries: [ ['a', '1'], ['b', '2'], ['c', '3'], ], max: 2, result: [ ['b', '2'], ['c', '3'], ], }, { entries: [], max: 2, result: [], }, { entries: [['a', '1']], max: 2, result: [['a', '1']], }, ].forEach(({ entries, max, result }, i) => { it(`should iterate all keys ${i}`, () => { const lru = createLRU({ max }); entries.forEach(([k, v]) => { lru.set(k, v); }); expect([...lru]).toEqual(result); }); }); it('should set and dispose values', () => { const lru = createLRU({ max: 2 }); lru.set('a', 1); expect(lru.size).toEqual(1); expect(lru.get('a')).toEqual(1); expect(lru.has('a')).toEqual(true); lru.set('a', 2); expect(lru.size).toEqual(1); expect(lru.get('a')).toEqual(2); lru.set('b', 3); expect(lru.size).toEqual(2); expect(lru.get('b')).toEqual(3); expect(lru.get('a')).toEqual(2); lru.set('b', 4); expect(lru.get('b')).toEqual(4); lru.set('c', 5); expect(lru.get('c')).toEqual(5); expect(lru.get('a')).toEqual(undefined); expect([...lru.keys()]).toEqual(['b', 'c']); expect([...lru.values()]).toEqual([4, 5]); lru.delete('c'); expect(lru.get('c')).toEqual(undefined); expect(lru.get('b')).toEqual(4); lru.clear(); expect(lru.get('b')).toEqual(undefined); expect(lru.size).toEqual(0); }); });
8,848
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/newsletter.spec.ts
import { isGlobalFeatureNewsEnabled } from '@proton/shared/lib/helpers/newsletter'; describe('newsletter', () => { describe('isGlobalFeatureNewsEnabled', () => { describe('When only currentNews is provided as number', () => { it('should return correct value', () => { // 001000010001 -> Inbox News is enabled expect(isGlobalFeatureNewsEnabled(529)).toBeTrue(); // 000100100010 -> No news enabled expect(isGlobalFeatureNewsEnabled(290)).toBeFalse(); }); }); describe('When only currentNews is provided as object', () => { it('should return correct value', () => { expect(isGlobalFeatureNewsEnabled({ InboxNews: true, Beta: true, Business: true })).toBeTrue(); expect(isGlobalFeatureNewsEnabled({ Beta: true, Business: true })).toBeFalse(); }); }); describe('When both currentNews and updatedNews are provided', () => { describe('When updated value is defined', () => { it('should return true (number)', () => { expect(isGlobalFeatureNewsEnabled(17, 529)).toBeTrue(); }); it('should return true (object)', () => { expect(isGlobalFeatureNewsEnabled({ Beta: true, Business: true }, { DriveNews: true })).toBeTrue(); }); it('should return false (number)', () => { expect(isGlobalFeatureNewsEnabled(529, 17)).toBeFalse(); }); it('should return false (object)', () => { expect( isGlobalFeatureNewsEnabled( { Beta: true, Business: true, InboxNews: true }, { InboxNews: false } ) ).toBeFalse(); }); }); describe('When updated value is not defined', () => { it('should return true', () => { expect( isGlobalFeatureNewsEnabled({ Beta: true, Business: true, VpnNews: true }, { Business: false }) ).toBeTrue(); }); it('should return false', () => { expect( isGlobalFeatureNewsEnabled( { Beta: true, Business: true, InboxNews: false }, { Business: false } ) ).toBeFalse(); }); }); }); }); });
8,849
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/onceWithQueue.spec.js
import { onceWithQueue } from '../../lib/helpers/onceWithQueue'; import { wait } from '../../lib/helpers/promise'; const DELAY = 10; describe('onceWithQueue', () => { it('should only execute once if the callback is already queued', async () => { let count = 0; const cb = onceWithQueue(async () => { await wait(DELAY); count++; }); cb(); cb(); cb(); cb(); cb(); cb(); await wait(DELAY); expect(count).toEqual(1); }); it('should only execute once more if another callback is queued', async () => { let count = 0; const cb = onceWithQueue(async () => { await wait(DELAY); count++; }); cb(); cb(); cb(); cb(); cb(); cb(); await wait(DELAY); expect(count).toEqual(1); await wait(DELAY + 1); expect(count).toEqual(2); await wait(DELAY * 2); expect(count).toEqual(2); }); it('should await for its own callback', async () => { let count = 0; const cb = onceWithQueue(async () => { await wait(DELAY); count++; }); const p1 = cb().then(() => { expect(count).toEqual(1); }); const p2 = cb().then(() => { expect(count).toEqual(2); }); const p3 = cb().then(() => { expect(count).toEqual(2); }); const p4 = cb().then(() => { expect(count).toEqual(2); }); await Promise.all([p1, p2, p3, p4]); await cb().then(() => { expect(count).toEqual(3); }); }); });
8,850
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/organization.spec.ts
import { hasOrganizationSetup, hasOrganizationSetupWithKeys } from '@proton/shared/lib/helpers/organization'; import { Organization } from '@proton/shared/lib/interfaces'; describe('hasOrganizationSetup', () => { it('Should return false when RequiresKey not set', () => { const testOrg: Partial<Organization> = {}; expect(hasOrganizationSetup(testOrg)).toBe(false); }); it('Should return false when RequiresKey is 0 and no name', () => { const testOrg: Partial<Organization> = { RequiresKey: 0, }; expect(hasOrganizationSetup(testOrg)).toBe(false); }); it('Should return true when RequiresKey is not set and name', () => { const testOrg: Partial<Organization> = { Name: 'Test', }; expect(hasOrganizationSetup(testOrg)).toBe(true); }); it('Should return false when RequiresKey is 1 and no name', () => { const testOrg: Partial<Organization> = { RequiresKey: 1, }; expect(hasOrganizationSetup(testOrg)).toBe(false); }); it('Should return true when RequiresKey is 0 and name', () => { const testOrg: Partial<Organization> = { RequiresKey: 0, Name: 'Test', }; expect(hasOrganizationSetup(testOrg)).toBe(true); }); it('Should return false when RequiresKey is 1 and name', () => { const testOrg: Partial<Organization> = { RequiresKey: 1, Name: 'Test', }; expect(hasOrganizationSetup(testOrg)).toBe(false); }); }); describe('hasOrganizationSetupWithKeys', () => { it('Should return false when RequiresKey not set', () => { const testOrg: Partial<Organization> = {}; expect(hasOrganizationSetupWithKeys(testOrg)).toBe(false); }); it('Should return false when RequiresKey set and HasKeys not set', () => { const testOrg: Partial<Organization> = { RequiresKey: 1, }; expect(hasOrganizationSetupWithKeys(testOrg)).toBe(false); }); it('Should return false when RequiresKey not set and HasKeys set', () => { const testOrg: Partial<Organization> = { HasKeys: 1, }; expect(hasOrganizationSetupWithKeys(testOrg)).toBe(false); }); it('Should return false when RequiresKey is 0 and no HasKeys', () => { const testOrg: Partial<Organization> = { RequiresKey: 0, HasKeys: 0, }; expect(hasOrganizationSetupWithKeys(testOrg)).toBe(false); }); it('Should return false when RequiresKey is 1 and no HasKeys', () => { const testOrg: Partial<Organization> = { RequiresKey: 1, HasKeys: 0, }; expect(hasOrganizationSetupWithKeys(testOrg)).toBe(false); }); it('Should return false when RequiresKey is 0 and HasKeys', () => { const testOrg: Partial<Organization> = { RequiresKey: 0, HasKeys: 1, }; expect(hasOrganizationSetupWithKeys(testOrg)).toBe(false); }); it('Should return true when RequiresKey is 1 and HasKeys', () => { const testOrg: Partial<Organization> = { RequiresKey: 1, HasKeys: 1, }; expect(hasOrganizationSetupWithKeys(testOrg)).toBe(true); }); });
8,851
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/planIDs.spec.ts
import { ADDON_NAMES, PLANS, PLAN_NAMES, PLAN_SERVICES, PLAN_TYPES } from '../../lib/constants'; import { clearPlanIDs, getHasPlanType, hasPlanIDs, setQuantity, switchPlan } from '../../lib/helpers/planIDs'; import { Organization, Plan } from '../../lib/interfaces'; const MOCK_PLANS = [ { Title: PLAN_NAMES[PLANS.MAIL], ID: PLANS.MAIL, Name: PLANS.MAIL, Services: PLAN_SERVICES.MAIL, Type: PLAN_TYPES.PLAN, MaxDomains: 1, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Features: 1, State: 1, Pricing: { 1: 499, 12: 4788, 24: 8376, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { Title: PLAN_NAMES[PLANS.MAIL_PRO], ID: PLANS.MAIL_PRO, Name: PLANS.MAIL_PRO, Services: PLAN_SERVICES.MAIL, Type: PLAN_TYPES.PLAN, MaxDomains: 3, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Features: 1, State: 1, Pricing: { 1: 799, 12: 8388, 24: 15576, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { ID: PLANS.NEW_VISIONARY, Name: PLANS.NEW_VISIONARY, Type: PLAN_TYPES.PLAN, Title: PLAN_NAMES[PLANS.NEW_VISIONARY], MaxDomains: 10, MaxAddresses: 100, MaxCalendars: 120, MaxSpace: 3298534883328, MaxMembers: 6, MaxVPN: 60, MaxTier: 2, Services: 7, Features: 1, State: 0, Pricing: { 1: 2999, 12: 28788, 24: 47976, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { ID: PLANS.VPN, Name: PLANS.VPN, Type: PLAN_TYPES.PLAN, Title: PLAN_NAMES[PLANS.VPN], MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 10, MaxTier: 2, Services: 4, Features: 0, State: 1, Pricing: { 1: 999, 12: 7188, 24: 11976, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { ID: PLANS.BUNDLE, Name: PLANS.BUNDLE, Type: PLAN_TYPES.PLAN, Title: PLAN_NAMES[PLANS.BUNDLE], MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 7, Features: 1, State: 1, Pricing: { 1: 1199, 12: 11988, 24: 19176, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { ID: PLANS.BUNDLE_PRO, Name: PLANS.BUNDLE_PRO, Type: PLAN_TYPES.PLAN, Title: PLAN_NAMES[PLANS.BUNDLE_PRO], MaxDomains: 10, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 7, Features: 1, State: 1, Pricing: { 1: 1299, 12: 13188, 24: 23976, }, Currency: 'EUR', Quantity: 1, Cycle: 1, Amount: 1299, }, { ID: PLANS.ENTERPRISE, Type: PLAN_TYPES.PLAN, Name: PLANS.ENTERPRISE, Title: PLAN_NAMES[PLANS.ENTERPRISE], MaxDomains: 10, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 1099511627776, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 7, Features: 1, State: 1, Pricing: { 1: 1599, 12: 16788, 24: 31176, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { ID: ADDON_NAMES.DOMAIN_BUNDLE_PRO, Type: PLAN_TYPES.ADDON, Name: ADDON_NAMES.DOMAIN_BUNDLE_PRO, Title: '+1 Domain for Business', MaxDomains: 1, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 7, Features: 0, State: 1, Pricing: { 1: 150, 12: 1680, 24: 3120, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { ID: ADDON_NAMES.MEMBER_MAIL_PRO, Type: PLAN_TYPES.ADDON, Name: ADDON_NAMES.MEMBER_MAIL_PRO, Title: '+1 User', MaxDomains: 0, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 0, State: 1, Pricing: { 1: 799, 12: 8388, 24: 15576, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { ID: ADDON_NAMES.MEMBER_BUNDLE_PRO, Type: PLAN_TYPES.ADDON, Name: ADDON_NAMES.MEMBER_BUNDLE_PRO, Title: '+1 User for Business', MaxDomains: 0, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 0, Services: 7, Features: 0, State: 1, Pricing: { 1: 1299, 12: 13188, 24: 23976, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { ID: ADDON_NAMES.DOMAIN_ENTERPRISE, Type: PLAN_TYPES.ADDON, Name: ADDON_NAMES.DOMAIN_ENTERPRISE, Title: '+1 Domain for Enterprise', MaxDomains: 1, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 7, Features: 0, State: 1, Pricing: { 1: 1599, 12: 16788, 24: 31176, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, { ID: ADDON_NAMES.MEMBER_ENTERPRISE, Type: 0, Name: ADDON_NAMES.MEMBER_ENTERPRISE, Title: '+1 User for Enterprise', MaxDomains: 0, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 1099511627776, MaxMembers: 1, MaxVPN: 10, MaxTier: 0, Services: 7, Features: 0, State: 1, Pricing: { 1: 1599, 12: 16788, 24: 31176, }, Currency: 'EUR', Quantity: 1, Cycle: 1, }, ] as Plan[]; const MOCK_ORGANIZATION = {} as Organization; describe('hasPlanType', () => { it('should return true if plan type is set', () => { expect(getHasPlanType({ [PLANS.MAIL_PRO]: 1 }, MOCK_PLANS, PLANS.MAIL_PRO)).toBeTrue(); expect(getHasPlanType({ [PLANS.MAIL]: 1, [PLANS.MAIL_PRO]: 1 }, MOCK_PLANS, PLANS.MAIL_PRO)).toBeTrue(); expect( getHasPlanType( { [PLANS.NEW_VISIONARY]: 1, [PLANS.MAIL]: 1, [PLANS.MAIL_PRO]: 1 }, MOCK_PLANS, PLANS.NEW_VISIONARY ) ).toBeTrue(); }); it('should not return true if plan type is not set', () => { expect(getHasPlanType({ [PLANS.MAIL_PRO]: 0 }, MOCK_PLANS, PLANS.MAIL_PRO)).toBeFalse(); expect(getHasPlanType({ [PLANS.MAIL]: 1 }, MOCK_PLANS, PLANS.MAIL_PRO)).toBeFalse(); expect(getHasPlanType({ [PLANS.MAIL]: 1, [PLANS.MAIL_PRO]: 1 }, MOCK_PLANS, PLANS.NEW_VISIONARY)).toBeFalse(); }); }); describe('hasPlanIDs', () => { it('should return true if plan IDs are set', () => { expect( hasPlanIDs({ [PLANS.MAIL_PRO]: 1, [PLANS.VPNPLUS]: 0, [ADDON_NAMES.VPN]: 3, }) ).toBeTrue(); expect( hasPlanIDs({ [PLANS.MAIL_PRO]: 1, }) ).toBeTrue(); expect( hasPlanIDs({ [PLANS.MAIL_PRO]: 1, }) ).toBeTrue(); expect( hasPlanIDs({ [PLANS.MAIL_PRO]: 1, [ADDON_NAMES.VPN]: -1, }) ).toBeTrue(); expect( hasPlanIDs({ [ADDON_NAMES.VPN]: 1, }) ).toBeTrue(); }); it('should return false if plan IDs are not set', () => { expect( hasPlanIDs({ [PLANS.MAIL_PRO]: 0, }) ).toBeFalse(); expect( hasPlanIDs({ [PLANS.MAIL_PRO]: -1, }) ).toBeFalse(); expect(hasPlanIDs({})).toBeFalse(); }); }); describe('setQuantity', () => { it('should set plan id quantity', () => { expect( setQuantity( { [PLANS.MAIL_PRO]: 1, }, PLANS.MAIL_PRO, 0 ) ).toEqual({}); expect( setQuantity( { [PLANS.MAIL_PRO]: 1, [ADDON_NAMES.ADDRESS]: 1, }, ADDON_NAMES.ADDRESS, 0 ) ).toEqual({ [PLANS.MAIL_PRO]: 1, }); expect(setQuantity({}, ADDON_NAMES.ADDRESS, 0)).toEqual({}); expect(setQuantity({}, ADDON_NAMES.ADDRESS, 1)).toEqual({ [ADDON_NAMES.ADDRESS]: 1, }); }); }); describe('clearPlanIDs', () => { it('should remove useless key', () => { const planIDs = { [PLANS.MAIL_PRO]: 1, [PLANS.VPNPLUS]: 0, [ADDON_NAMES.VPN]: 3, }; expect(clearPlanIDs(planIDs)).toEqual({ [PLANS.MAIL_PRO]: 1, [ADDON_NAMES.VPN]: 3, }); }); }); describe('switchPlan', () => { it('should remove previous plan', () => { const planIDs = { [PLANS.MAIL]: 1 }; const planID = PLANS.NEW_VISIONARY; expect(switchPlan({ planIDs, planID, plans: MOCK_PLANS, organization: MOCK_ORGANIZATION })).toEqual({ [PLANS.NEW_VISIONARY]: 1, }); }); it('should transfer domain addons', () => { const planIDs = { [PLANS.BUNDLE_PRO]: 1, [ADDON_NAMES.DOMAIN_BUNDLE_PRO]: 5 }; const planID = PLANS.ENTERPRISE; expect(switchPlan({ planIDs, planID, plans: MOCK_PLANS, organization: MOCK_ORGANIZATION })).toEqual({ [PLANS.ENTERPRISE]: 1, [ADDON_NAMES.DOMAIN_ENTERPRISE]: 5, }); }); it('should transfer member addons', () => { const planIDs = { [PLANS.BUNDLE_PRO]: 1, [ADDON_NAMES.MEMBER_BUNDLE_PRO]: 5 }; const planID = PLANS.ENTERPRISE; expect(switchPlan({ planIDs, planID, plans: MOCK_PLANS, organization: MOCK_ORGANIZATION })).toEqual({ [PLANS.ENTERPRISE]: 1, [ADDON_NAMES.MEMBER_ENTERPRISE]: 5, }); }); it('should not transfer addons', () => { const planIDs = { [PLANS.BUNDLE_PRO]: 1, [ADDON_NAMES.DOMAIN_BUNDLE_PRO]: 5 }; const planID = PLANS.MAIL; expect(switchPlan({ planIDs, planID, plans: MOCK_PLANS, organization: MOCK_ORGANIZATION })).toEqual({ [PLANS.MAIL]: 1, }); }); it('should transfer addons based on organization usage', () => { const planIDs = { [PLANS.ENTERPRISE]: 1 }; const organization = { UsedAddresses: 16, UsedDomains: 11 } as Organization; const planID = PLANS.BUNDLE_PRO; expect(switchPlan({ planIDs, planID, plans: MOCK_PLANS, organization })).toEqual({ [PLANS.BUNDLE_PRO]: 1, [ADDON_NAMES.MEMBER_BUNDLE_PRO]: 1, [ADDON_NAMES.DOMAIN_BUNDLE_PRO]: 1, }); }); });
8,852
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/preview.spec.ts
import { SupportedMimeTypes } from '../../lib/drive/constants'; import { MAX_PREVIEW_FILE_SIZE, MAX_PREVIEW_TEXT_SIZE, isPreviewAvailable } from '../../lib/helpers/preview'; describe('isPreviewAvailable()', () => { const textTypes = ['text/any', 'application/json']; const supportedTypes = [SupportedMimeTypes.jpg, 'video/any', 'audio/any', ...textTypes]; const unsupportedTypes = ['image/any', 'application/any', 'any']; supportedTypes.forEach((type) => { describe(`for supported type ${type}`, () => { it('should return positive answer without size', () => { expect(isPreviewAvailable(type)).toBe(true); }); const size = textTypes.includes(type) ? MAX_PREVIEW_TEXT_SIZE : MAX_PREVIEW_FILE_SIZE; it('should return positive answer with reasonable size', () => { expect(isPreviewAvailable(type, size / 2)).toBe(true); }); it('should return negative answer with too big size', () => { expect(isPreviewAvailable(type, size + 1)).toBe(false); }); }); }); unsupportedTypes.forEach((type) => { it(`should return negative answer for unsupported ${type} without size`, () => { expect(isPreviewAvailable(type)).toBe(false); }); }); });
8,853
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/promise.spec.js
import { runChunksDelayed, wait } from '../../lib/helpers/promise'; describe('promise', () => { describe('chunks delayed', () => { it('should call chunks in a specific interval', async () => { const chunks = [ [1, 2], ['a', 'b'], ]; const resultMap = { 1: 'foo', 2: 'bar', a: 'baz', b: 'qux', }; const cb = (value) => { return resultMap[value]; }; const spy = jasmine.createSpy('result').and.callFake(cb); const promise = runChunksDelayed(chunks, spy, 100); await wait(80); expect(spy.calls.all().length).toEqual(2); const result = await promise; expect(spy.calls.all().length).toEqual(4); expect(result).toEqual(['foo', 'bar', 'baz', 'qux']); }); }); });
8,854
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/regex.spec.ts
import { getMatches } from '../../lib/helpers/regex'; describe('getMatches', () => { const regex = /foo/g; it('should return an empty array if the regex does not match', () => { const b = 'bar'; const matches = getMatches(regex, b); expect(matches).toEqual([]); }); it('should return an array of MatchChunk objects', () => { const b = 'foo bar'; const matches = getMatches(regex, b); expect(matches).toEqual([{ start: 0, end: 3 }]); }); it('should return an array of MatchChunk objects', () => { const b = 'foo bar foo'; const matches = getMatches(regex, b); expect(matches).toEqual([ { start: 0, end: 3 }, { start: 8, end: 11 }, ]); }); });
8,855
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/runInQueue.spec.ts
import { wait } from '../../lib/helpers/promise'; import runInQueue from '../../lib/helpers/runInQueue'; describe('runInQueue', () => { it('should execute every function', async () => { const executors = [ jasmine.createSpy().and.resolveTo(1), jasmine.createSpy().and.resolveTo(2), jasmine.createSpy().and.resolveTo(3), ]; await runInQueue(executors); executors.forEach((executor) => { expect(executor).toHaveBeenCalledTimes(1); }); }); it('should execute functions using several threads and return results in original order', async () => { const maxThreads = 3; const getExecutor = (delay: number) => jasmine.createSpy().and.callFake(() => { return new Promise<number>((resolve) => setTimeout(() => resolve(delay), delay)); }); const executors = [ getExecutor(200), getExecutor(300), getExecutor(400), getExecutor(500), getExecutor(100), getExecutor(600), ]; const expectToHaveExecuted = (count: number) => expect(executors.filter((fn) => fn.calls.all().length === 1).length).toEqual(count); const promises = runInQueue<number>(executors, maxThreads); expectToHaveExecuted(3); const executedOnStepOf100ms = [3, 3, 4, 5, 6]; for (const executionCount of executedOnStepOf100ms) { expectToHaveExecuted(executionCount); await wait(100); } const results = await promises; expect(results).toEqual([200, 300, 400, 500, 100, 600]); }); });
8,856
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/secureSessionStorage.spec.js
import { disableRandomMock, initRandomMock } from '@proton/testing/lib/mockRandomValues'; import { load, mergeParts, save, separateParts } from '../../lib/helpers/secureSessionStorage'; describe('secureSessionStorage', () => { beforeAll(() => initRandomMock()); afterAll(() => disableRandomMock()); it('should be able to save and load data in window.name and sessionStorage', () => { const data = { foo: 'bar' }; save(data); expect(window.name).toEqual( '"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+AA=="' ); expect(window.sessionStorage.getItem('proton:storage')).toEqual( 'eyNkbGsnPCVqaHgpcQ0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+AA==' ); const loadedData = load(); expect(loadedData).toEqual(data); }); it('should allow undefined values', () => { const data = { foo: undefined }; save(data); expect(window.name).toEqual( '"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+AA=="' ); expect(window.sessionStorage.getItem('proton:storage')).toEqual( 'e3wCAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+AA==' ); const loadedData = load(); expect(loadedData).toEqual({}); }); it('should allow values and undefined values', () => { const data = { foo: undefined, bar: '123' }; save(data); const loadedData = load(); expect(loadedData).toEqual({ bar: '123' }); }); it('should separate parts in two shares', () => { const { share1, share2 } = separateParts({ a: '123', b: '456', }); expect(share1).toEqual({ a: 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+AA==', b: 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+AA==', }); expect(share2).toEqual({ a: 'MTMxAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ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toEqual('456'); }); });
8,857
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/string.spec.ts
import { DEFAULT_TRUNCATE_OMISSION, findLongestMatchingIndex, getInitials, removeHTMLComments, truncateMore, truncatePossiblyQuotedString, } from '../../lib/helpers/string'; describe('string', () => { describe('longest match', () => { it('should get the longest matching string', () => { const x = ['14:00', '14:30']; expect(findLongestMatchingIndex(x, '14')).toBe(0); expect(findLongestMatchingIndex(x, '14:35')).toBe(1); expect(findLongestMatchingIndex(x, '14:30')).toBe(1); expect(findLongestMatchingIndex(x, '13:35')).toBe(0); expect(findLongestMatchingIndex(x, '23:35')).toBe(-1); expect(findLongestMatchingIndex()).toBe(-1); }); }); describe('getInitials', () => { it('should handle empty parameter', () => { expect(getInitials()).toEqual('?'); }); it('should handle single character', () => { expect(getInitials('q')).toEqual('Q'); }); it('should handle unique word', () => { expect(getInitials('熊猫')).toEqual('熊'); }); it('should return 2 first initials and capitalize it', () => { expect(getInitials('Lorem ipsum dolor sit amet')).toEqual('LA'); }); it('should handle emoji', () => { expect(getInitials('🐼 Dog')).toEqual('🐼D'); }); it('should keep only character and number', () => { expect(getInitials('22 - Name Mame')).toEqual('2M'); }); it('should remove undesired characters', () => { expect(getInitials('Thomas Anderson (@neo)')).toEqual('TA'); }); }); describe('truncateMore', () => { it('should truncate', () => { expect(truncateMore({ string: '', charsToDisplayStart: 1 })).toEqual(''); expect(truncateMore({ string: 'a', charsToDisplayStart: 1 })).toEqual('a'); expect(truncateMore({ string: 'ab', charsToDisplayStart: 1 })).toEqual('ab'); expect(truncateMore({ string: 'abc', charsToDisplayStart: 4 })).toEqual('abc'); expect(truncateMore({ string: 'abcd', charsToDisplayStart: 1 })).toEqual(`a${DEFAULT_TRUNCATE_OMISSION}`); expect(truncateMore({ string: 'abcde', charsToDisplayStart: 1 })).toEqual(`a${DEFAULT_TRUNCATE_OMISSION}`); expect(truncateMore({ string: '', charsToDisplayEnd: 1 })).toEqual(''); expect(truncateMore({ string: 'a', charsToDisplayEnd: 1 })).toEqual('a'); expect(truncateMore({ string: 'ab', charsToDisplayEnd: 1 })).toEqual('ab'); expect(truncateMore({ string: 'abc', charsToDisplayEnd: 4 })).toEqual('abc'); expect(truncateMore({ string: 'abcd', charsToDisplayEnd: 1 })).toEqual(`${DEFAULT_TRUNCATE_OMISSION}d`); expect(truncateMore({ string: 'abcde', charsToDisplayEnd: 1 })).toEqual(`${DEFAULT_TRUNCATE_OMISSION}e`); expect(truncateMore({ string: '12345', charsToDisplayStart: 2, charsToDisplayEnd: 2 })).toEqual('12345'); expect(truncateMore({ string: '123456789', charsToDisplayStart: 2, charsToDisplayEnd: 3 })).toEqual( '12…789' ); }); it('should truncate in the middle', () => { expect(truncateMore({ string: '', charsToDisplay: 1 })).toEqual(''); expect(truncateMore({ string: 'a', charsToDisplay: 1 })).toEqual('a'); expect(truncateMore({ string: 'ab', charsToDisplay: 1 })).toEqual(DEFAULT_TRUNCATE_OMISSION); expect(truncateMore({ string: 'ab', charsToDisplay: 2 })).toEqual('ab'); expect(truncateMore({ string: 'abc', charsToDisplay: 4, charsToDisplayStart: 1 })).toEqual('abc'); expect(truncateMore({ string: 'abc', charsToDisplay: 2 })).toEqual(`a${DEFAULT_TRUNCATE_OMISSION}`); expect(truncateMore({ string: 'abc', charsToDisplay: 2, skewEnd: true })).toEqual( `${DEFAULT_TRUNCATE_OMISSION}c` ); expect(truncateMore({ string: 'abcde', charsToDisplay: 5, charsToDisplayEnd: 4 })).toEqual('abcde'); expect(truncateMore({ string: '12345', charsToDisplay: 4, skewEnd: true })).toEqual( `1${DEFAULT_TRUNCATE_OMISSION}45` ); expect(truncateMore({ string: '123456789', charsToDisplay: 5 })).toEqual( `12${DEFAULT_TRUNCATE_OMISSION}89` ); }); }); describe('truncatePossiblyQuotedString', () => { it('should truncate', () => { expect(truncatePossiblyQuotedString('', 1)).toEqual(''); expect(truncatePossiblyQuotedString('a', 1)).toEqual('a'); expect(truncatePossiblyQuotedString('ab', 1)).toEqual(DEFAULT_TRUNCATE_OMISSION); expect(truncatePossiblyQuotedString('abc', 4)).toEqual('abc'); expect(truncatePossiblyQuotedString('"abc"', 4)).toEqual(`"a${DEFAULT_TRUNCATE_OMISSION}"`); expect(truncatePossiblyQuotedString('abcd', 3)).toEqual(`a${DEFAULT_TRUNCATE_OMISSION}d`); expect(truncatePossiblyQuotedString('abcde', 4)).toEqual(`ab${DEFAULT_TRUNCATE_OMISSION}e`); expect(truncatePossiblyQuotedString('"abcde"', 4)).toEqual(`"a${DEFAULT_TRUNCATE_OMISSION}"`); }); }); describe('removeHTMLComments', () => { it('should remove comments', () => { expect(removeHTMLComments('')).toEqual(''); expect(removeHTMLComments('a')).toEqual('a'); expect(removeHTMLComments('<!-- a -->')).toEqual(''); expect(removeHTMLComments('<!-- a -->b')).toEqual('b'); expect(removeHTMLComments('a<!-- b -->')).toEqual('a'); expect(removeHTMLComments('a<!-- b -->c')).toEqual('ac'); expect(removeHTMLComments('a<!-- b -->c<!-- d -->')).toEqual('ac'); expect(removeHTMLComments('a<!-- b -->c<!-- d -->e')).toEqual('ace'); expect(removeHTMLComments('a<!-- b -->c<!-- d -->e<!-- f -->')).toEqual('ace'); expect(removeHTMLComments('a<!-- b -->c<!-- d -->e<!-- f -->g')).toEqual('aceg'); expect(removeHTMLComments('a<!-- b -->c<!-- d -->e<!-- f -->g<!-- h -->')).toEqual('aceg'); expect(removeHTMLComments('a<!-- b -->c<!-- d -->e<!-- f -->g<!-- h -->i')).toEqual('acegi'); expect(removeHTMLComments('<a href="#">a<!-- b -->c<!-- d -->e<!-- f -->g<!-- h --></a>')).toEqual( '<a href="#">aceg</a>' ); expect(removeHTMLComments('<a href="#">a<!-- b -->c<!-- d -->e<!-- f -->g<!-- h -->i</a>')).toEqual( '<a href="#">acegi</a>' ); }); }); });
8,858
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/subscription.spec.ts
import { addWeeks } from 'date-fns'; import { pick } from '@proton/shared/lib/helpers/object'; import { External, Plan, PlanIDs, PlansMap, Renew, Subscription } from '@proton/shared/lib/interfaces'; // that has to be a very granular import, because in general @proton/testing depends on jest while @proton/shared // still uses Karma. The payments data specifically don't need jest, so it's safe to impoet it directly import { PLANS_MAP } from '@proton/testing/data'; import { ADDON_NAMES, COUPON_CODES, CYCLE, PLANS } from '../../lib/constants'; import { AggregatedPricing, getPlanIDs, getPricingFromPlanIDs, getTotalFromPricing, hasLifetime, isManagedExternally, isTrial, isTrialExpired, willTrialExpire, } from '../../lib/helpers/subscription'; let subscription: Subscription; let defaultPlan: Plan; beforeEach(() => { subscription = { ID: 'id-123', InvoiceID: 'invoice-id-123', Cycle: CYCLE.MONTHLY, PeriodStart: 123, PeriodEnd: 777, CreateTime: 123, CouponCode: null, Currency: 'EUR', Amount: 123, RenewAmount: 123, Discount: 123, Plans: [], External: External.Default, Renew: Renew.Enabled, }; defaultPlan = { ID: 'plan-id-123', Type: 0, Cycle: CYCLE.MONTHLY, Name: PLANS.BUNDLE, Title: 'Bundle', Currency: 'EUR', Amount: 123, MaxDomains: 123, MaxAddresses: 123, MaxSpace: 123, MaxCalendars: 123, MaxMembers: 123, MaxVPN: 123, MaxTier: 123, Services: 123, Features: 123, Quantity: 123, Pricing: { [CYCLE.MONTHLY]: 123, [CYCLE.YEARLY]: 123, [CYCLE.TWO_YEARS]: 123, }, State: 123, Offers: [], }; }); describe('getPlanIDs', () => { it('should extract plans properly', () => { expect( getPlanIDs({ ...subscription, Plans: [ { ...defaultPlan, Name: PLANS.BUNDLE_PRO, Quantity: 1 }, { ...defaultPlan, Name: PLANS.BUNDLE_PRO, Quantity: 1 }, { ...defaultPlan, Name: ADDON_NAMES.MEMBER_BUNDLE_PRO, Quantity: 3 }, ], }) ).toEqual({ [PLANS.BUNDLE_PRO]: 2, [ADDON_NAMES.MEMBER_BUNDLE_PRO]: 3, }); }); }); describe('hasLifetime', () => { it('should have LIFETIME', () => { subscription = { ...subscription, CouponCode: COUPON_CODES.LIFETIME, }; expect(hasLifetime(subscription)).toBe(true); }); it('should not have LIFETIME', () => { subscription = { ...subscription, CouponCode: 'PANDA', }; expect(hasLifetime(subscription)).toBe(false); }); }); describe('isTrial', () => { it('should be a trial', () => { expect(isTrial({ ...subscription, CouponCode: COUPON_CODES.REFERRAL })).toBe(true); }); it('should not be a trial', () => { expect(isTrial({ ...subscription, CouponCode: 'PANDA' })).toBe(false); }); }); describe('isTrialExpired', () => { it('should detect expired subscription', () => { const ts = Math.round((new Date().getTime() - 1000) / 1000); expect(isTrialExpired({ ...subscription, PeriodEnd: ts })).toBe(true); }); it('should detect non-expired subscription', () => { const ts = Math.round((new Date().getTime() + 1000) / 1000); expect(isTrialExpired({ ...subscription, PeriodEnd: ts })).toBe(false); }); }); describe('willTrialExpire', () => { it('should detect close expiration', () => { const ts = Math.round((addWeeks(new Date(), 1).getTime() - 1000) / 1000); expect(willTrialExpire({ ...subscription, PeriodEnd: ts })).toBe(true); }); it('should detect far expiration', () => { // Add 2 weeks from now and convert Date to unix timestamp const ts = Math.round(addWeeks(new Date(), 2).getTime() / 1000); expect(willTrialExpire({ ...subscription, PeriodEnd: ts })).toBe(false); }); }); describe('isManagedExternally', () => { it('should return true if managed by Android', () => { const result = isManagedExternally({ ID: 'id-123', InvoiceID: 'invoice-id-123', Cycle: CYCLE.MONTHLY, PeriodStart: 123, PeriodEnd: 777, CreateTime: 123, CouponCode: null, Currency: 'CHF', Amount: 1199, RenewAmount: 1199, Discount: 0, Plans: [], External: External.Android, }); expect(result).toEqual(true); }); it('should return true if managed by Apple', () => { const result = isManagedExternally({ ID: 'id-123', InvoiceID: 'invoice-id-123', Cycle: CYCLE.MONTHLY, PeriodStart: 123, PeriodEnd: 777, CreateTime: 123, CouponCode: null, Currency: 'CHF', Amount: 1199, RenewAmount: 1199, Discount: 0, Plans: [], External: External.iOS, }); expect(result).toEqual(true); }); it('should return false if managed by us', () => { const result = isManagedExternally({ ID: 'id-123', InvoiceID: 'invoice-id-123', Cycle: CYCLE.MONTHLY, PeriodStart: 123, PeriodEnd: 777, CreateTime: 123, CouponCode: null, Currency: 'CHF', Amount: 1199, RenewAmount: 1199, Discount: 0, Plans: [], External: External.Default, }); expect(result).toEqual(false); }); }); describe('getPricingFromPlanIDs', () => { it('returns the correct pricing for a single plan ID', () => { const planIDs: PlanIDs = { pass2023: 1 }; const plansMap: PlansMap = { pass2023: { ID: 'id123', Type: 1, Name: PLANS.PASS_PLUS, Title: 'Pass Plus', MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 8, Features: 0, State: 1, Pricing: { '1': 499, '12': 1200, '24': 7176, }, Currency: 'CHF', Quantity: 1, Offers: [ { Name: 'passlaunch', StartTime: 1684758588, EndTime: 1688110913, Pricing: { '12': 1200, }, }, ], Cycle: 1, Amount: 499, }, }; const expected = { defaultMonthlyPrice: 499, all: { '1': 499, '12': 1200, '15': 0, '24': 7176, '30': 0, }, membersNumber: 1, members: { '1': 499, '12': 1200, '15': 0, '24': 7176, '30': 0, }, plans: { '1': 499, '12': 1200, '15': 0, '24': 7176, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); it('should return correct pricing for Mail Pro: no addons', () => { const planIDs: PlanIDs = { [PLANS.MAIL_PRO]: 1, }; const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.MAIL_PRO]); const expected = { defaultMonthlyPrice: 799, all: { '1': 799, '12': 8388, '15': 0, '24': 15576, '30': 0, }, membersNumber: 1, members: { '1': 799, '12': 8388, '15': 0, '24': 15576, '30': 0, }, plans: { '1': 799, '12': 8388, '15': 0, '24': 15576, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); it('should return correct pricing for Mail Pro: with addons', () => { const planIDs: PlanIDs = { [PLANS.MAIL_PRO]: 1, [ADDON_NAMES.MEMBER_MAIL_PRO]: 7, }; const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.MAIL_PRO, ADDON_NAMES.MEMBER_MAIL_PRO]); const expected = { defaultMonthlyPrice: 6392, all: { '1': 6392, '12': 67104, '15': 0, '24': 124608, '30': 0, }, membersNumber: 8, members: { '1': 6392, '12': 67104, '15': 0, '24': 124608, '30': 0, }, plans: { '1': 799, '12': 8388, '15': 0, '24': 15576, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); it('should return correct pricing for Bundle Pro: no addons', () => { const planIDs: PlanIDs = { [PLANS.BUNDLE_PRO]: 1, }; const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.BUNDLE_PRO]); const expected = { defaultMonthlyPrice: 1299, all: { '1': 1299, '12': 13188, '15': 0, '24': 23976, '30': 0, }, membersNumber: 1, members: { '1': 1299, '12': 13188, '15': 0, '24': 23976, '30': 0, }, plans: { '1': 1299, '12': 13188, '15': 0, '24': 23976, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); it('should return correct pricing for Bundle Pro: with addons', () => { const planIDs: PlanIDs = { [PLANS.BUNDLE_PRO]: 1, [ADDON_NAMES.MEMBER_BUNDLE_PRO]: 7, [ADDON_NAMES.DOMAIN_BUNDLE_PRO]: 9, }; const plansMap: PlansMap = pick(PLANS_MAP, [ PLANS.BUNDLE_PRO, ADDON_NAMES.MEMBER_BUNDLE_PRO, ADDON_NAMES.DOMAIN_BUNDLE_PRO, ]); const expected = { defaultMonthlyPrice: 11742, all: { '1': 11742, '12': 120624, '15': 0, '24': 219888, '30': 0, }, membersNumber: 8, members: { '1': 10392, '12': 105504, '15': 0, '24': 191808, '30': 0, }, plans: { '1': 1299, '12': 13188, '15': 0, '24': 23976, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); it('should return correct pricing for Family', () => { const planIDs: PlanIDs = { [PLANS.FAMILY]: 1, }; const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.FAMILY]); const expected = { defaultMonthlyPrice: 2999, all: { '1': 2999, '12': 28788, '15': 0, '24': 47976, '30': 0, }, // Even though Family Plan does have up to 6 users, we still count as 1 member for price displaying // purposes membersNumber: 1, members: { '1': 2999, '12': 28788, '15': 0, '24': 47976, '30': 0, }, plans: { '1': 2999, '12': 28788, '15': 0, '24': 47976, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); it('should return correct pricing for VPN Essentials: no addons', () => { const planIDs: PlanIDs = { [PLANS.VPN_PRO]: 1, }; const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.VPN_PRO]); const expected = { defaultMonthlyPrice: 1798, all: { '1': 1798, '12': 16776, '15': 0, '24': 28752, '30': 0, }, membersNumber: 2, members: { '1': 1798, '12': 16776, '15': 0, '24': 28752, '30': 0, }, plans: { '1': 1798, '12': 16776, '15': 0, '24': 28752, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); it('should return correct pricing for VPN Essentials: with addons', () => { const planIDs: PlanIDs = { // be default VPN Pro has 2 members, so overall there's 9 members for the price calculation purposes [PLANS.VPN_PRO]: 1, [ADDON_NAMES.MEMBER_VPN_PRO]: 7, }; const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.VPN_PRO, ADDON_NAMES.MEMBER_VPN_PRO]); const expected = { defaultMonthlyPrice: 8084, all: { '1': 8084, '12': 75492, '15': 0, '24': 129384, '30': 0, }, membersNumber: 9, members: { '1': 8084, '12': 75492, '15': 0, '24': 129384, '30': 0, }, plans: { '1': 1798, '12': 16776, '15': 0, '24': 28752, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); it('should return correct pricing for VPN Business: no addons', () => { const planIDs: PlanIDs = { [PLANS.VPN_BUSINESS]: 1, }; const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.VPN_BUSINESS]); // VPN Business has 2 members and 1 IP by default. // monthly: each user currently costs 11.99 and IP 49.99. // yearly: (2*9.99 + 39.99) * 12 // 2 years: (2*8.99 + 35.99) * 24 const expected = { defaultMonthlyPrice: 7397, all: { '1': 7397, '12': 71964, '15': 0, '24': 129528, '30': 0, }, membersNumber: 2, members: { '1': 2398, '12': 23976, '15': 0, '24': 43152, '30': 0, }, plans: { '1': 7397, '12': 71964, '15': 0, '24': 129528, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); it('should return correct pricing for VPN Business: with addons', () => { const planIDs: PlanIDs = { [PLANS.VPN_BUSINESS]: 1, [ADDON_NAMES.MEMBER_VPN_BUSINESS]: 7, [ADDON_NAMES.IP_VPN_BUSINESS]: 3, }; const plansMap: PlansMap = pick(PLANS_MAP, [ PLANS.VPN_BUSINESS, ADDON_NAMES.MEMBER_VPN_BUSINESS, ADDON_NAMES.IP_VPN_BUSINESS, ]); // VPN Business has 2 members and 1 IP by default. // monthly: each user currently costs 11.99 and IP 49.99. // yearly: (2*9.99 + 39.99) * 12 // 2 years: (2*8.99 + 35.99) * 24 const expected = { defaultMonthlyPrice: 30787, all: { '1': 30787, '12': 299844, '15': 0, '24': 539688, '30': 0, }, // Pricing for 9 members membersNumber: 9, members: { '1': 10791, '12': 107892, '15': 0, '24': 194184, '30': 0, }, plans: { '1': 7397, '12': 71964, '15': 0, '24': 129528, '30': 0, }, }; const result = getPricingFromPlanIDs(planIDs, plansMap); expect(result).toEqual(expected); }); }); describe('getTotalFromPricing', () => { it('should calculate the prices correctly', () => { const pricing: AggregatedPricing = { defaultMonthlyPrice: 8596, all: { '1': 8596, '12': 83952, '15': 0, '24': 151104, '30': 0, }, members: { '1': 3597, '12': 35964, '15': 0, '24': 64728, '30': 0, }, membersNumber: 3, plans: { '1': 7397, '12': 71964, '15': 0, '24': 129528, '30': 0, }, }; expect(getTotalFromPricing(pricing, 1)).toEqual({ discount: 0, discountPercentage: 0, total: 8596, totalPerMonth: 8596, totalNoDiscountPerMonth: 8596, perUserPerMonth: 1199, }); expect(getTotalFromPricing(pricing, 12)).toEqual({ discount: 19200, discountPercentage: 19, total: 83952, totalPerMonth: 6996, totalNoDiscountPerMonth: 8596, perUserPerMonth: 999, }); expect(getTotalFromPricing(pricing, 24)).toEqual({ discount: 55200, discountPercentage: 27, total: 151104, totalPerMonth: 6296, totalNoDiscountPerMonth: 8596, perUserPerMonth: 899, }); }); it('should calculate the prices correctly from a different monthly price', () => { const pricing: AggregatedPricing = { defaultMonthlyPrice: 999, all: { '1': 899, '12': 7188, '15': 14985, '24': 11976, '30': 29970, }, members: { '1': 899, '12': 7188, '15': 14985, '24': 11976, '30': 29970, }, plans: { '1': 899, '12': 7188, '15': 14985, '24': 11976, '30': 29970, }, membersNumber: 1, }; expect(getTotalFromPricing(pricing, 1)).toEqual({ discount: 0, discountPercentage: 0, total: 899, totalPerMonth: 899, totalNoDiscountPerMonth: 999, perUserPerMonth: 899, }); expect(getTotalFromPricing(pricing, 12)).toEqual({ discount: 4800, discountPercentage: 40, total: 7188, totalPerMonth: 599, totalNoDiscountPerMonth: 999, perUserPerMonth: 599, }); expect(getTotalFromPricing(pricing, 24)).toEqual({ discount: 12000, discountPercentage: 50, total: 11976, totalPerMonth: 499, totalNoDiscountPerMonth: 999, perUserPerMonth: 499, }); }); });
8,859
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/time.spec.ts
import { readableTime, readableTimeIntl } from '@proton/shared/lib/helpers/time'; import { enUSLocale } from '@proton/shared/lib/i18n/dateFnLocales'; describe('readableTime()', () => { const unixTime = 1666438769; // Sat Oct 22 2022 13:39:29 GMT+0200 (Central European Summer Time) let originalDateNow: any; let mockedTime: number; function setMockedTime(time: number) { mockedTime = time; } beforeEach(() => { originalDateNow = Date.now; setMockedTime(originalDateNow()); Date.now = () => mockedTime; }); afterEach(() => { Date.now = originalDateNow; }); it("should return formatted date if it is not today's date", () => { expect(readableTime(unixTime)).toEqual('Oct 22, 2022'); }); it('should return time if the day is today', () => { setMockedTime(unixTime * 1000); expect( readableTime(unixTime, { locale: enUSLocale, }) ).toMatch(/AM|PM/); // essentially checking that it's X:XX AM or X:XX PM. By using regex, I bypass the problem of the time zones }); it('should apply custom time format for the same day', () => { setMockedTime(unixTime * 1000); expect( readableTime(unixTime, { locale: enUSLocale, sameDayFormat: 'PP', }) ).toEqual('Oct 22, 2022'); }); it('should apply custom time format if it is different day', () => { expect( readableTime(unixTime, { format: 'p', }) ).toMatch(/AM|PM/); // essentially checking that it's X:XX AM or X:XX PM. By using regex, I bypass the problem of the time zones }); it('should use format parameter if sameDayFormat is false', () => { setMockedTime(unixTime * 1000); expect( readableTime(unixTime, { locale: enUSLocale, sameDayFormat: false, }) ).toEqual('Oct 22, 2022'); }); }); describe('readableTimeIntl()', () => { const unixTime = 1666438769; // Sat Oct 22 2022 13:39:29 GMT+0200 (Central European Summer Time) let originalDateNow: any; let mockedTime: number; function setMockedTime(time: number) { mockedTime = time; } beforeEach(() => { originalDateNow = Date.now; setMockedTime(originalDateNow()); Date.now = () => mockedTime; }); afterEach(() => { Date.now = originalDateNow; }); it("should return formatted date if it is not today's date", () => { expect(readableTimeIntl(unixTime)).toEqual('Oct 22, 2022'); }); it('should return correct time format with different localeCode', () => { expect( readableTimeIntl(unixTime, { localeCode: 'fr-ch', }) ).toEqual('22 oct. 2022'); }); it('should return time if the day is today', () => { setMockedTime(unixTime * 1000); expect( readableTimeIntl(unixTime, { localeCode: enUSLocale.code, }) ).toMatch(/AM|PM/); // essentially checking that it's X:XX AM or X:XX PM. By using regex, I bypass the problem of the time zones }); it('should apply custom time format for the same day', () => { setMockedTime(unixTime); expect( readableTimeIntl(unixTime, { localeCode: enUSLocale.code, sameDayIntlOptions: { month: 'short', day: 'numeric', year: 'numeric' }, }) ).toEqual('Oct 22, 2022'); }); it('should apply custom time format if it is different day', () => { setMockedTime(unixTime * 1000); expect( readableTimeIntl(unixTime, { intlOptions: { hour: 'numeric', minute: 'numeric', }, }) ).toMatch(/AM|PM/); // essentially checking that it's X:XX AM or X:XX PM. By using regex, I bypass the problem of the time zones }); it('should use default intl options if sameDayFormat is false', () => { setMockedTime(unixTime * 1000); let result = readableTimeIntl(unixTime, { localeCode: enUSLocale.code, sameDayIntlOptions: false, }); expect(result).toEqual('Oct 22, 2022'); }); it('should work with force 24h format', () => { expect( readableTimeIntl(unixTime, { intlOptions: { hour: 'numeric', minute: 'numeric', }, hour12: false, }) ).not.toMatch(/AM|PM/); }); });
8,860
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/url.helper.ts
import * as exports from '../../lib/window'; const initialWindow = window; const initialWindowLocation: Location = initialWindow.location; const initialExports = exports.default; export const mockWindowLocation = ({ origin = 'https://mail.proton.pink', hostname = 'mail.proton.pink', href = '', }) => { Object.defineProperty(exports, 'default', { writable: true, value: { location: { ...initialWindowLocation, hostname, origin, port: '', href }, parent: { ...initialWindow.parent }, }, }); }; export const resetWindowLocation = () => { Object.defineProperty(exports, 'default', { writable: false, value: initialExports, }); };
8,861
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/url.spec.ts
import { APPS } from '@proton/shared/lib/constants'; import { mockWindowLocation, resetWindowLocation } from '@proton/shared/test/helpers/url.helper'; import { formatURLForAjaxRequest, getApiSubdomainUrl, getAppUrlFromApiUrl, getAppUrlRelativeToOrigin, getRelativeApiHostname, getSecondLevelDomain, getStaticURL, isAppFromURL, isValidHttpUrl, stringifySearchParams, } from '../../lib/helpers/url'; const mailUrl = 'https://mail.proton.me'; const windowHostname = 'mail.proton.me'; const path = '/somePath'; describe('getSecondLevelDomain', () => { it('should return second level domain', () => { expect(getSecondLevelDomain(windowHostname)).toEqual('proton.me'); }); }); describe('getRelativeApiHostname', () => { it('should return api hostname', () => { expect(getRelativeApiHostname(mailUrl)).toEqual(`https://mail-api.proton.me`); }); }); describe('getApiSubdomainUrl', () => { afterEach(() => { resetWindowLocation(); }); it('should return api subdomain url for localhost', () => { mockWindowLocation({ origin: 'https://localhost', hostname: 'localhost' }); expect(getApiSubdomainUrl(path).href).toEqual(`https://localhost/api${path}`); }); it('should return api subdomain url for DoH', () => { mockWindowLocation({ origin: 'https://34-234.whatever.compute.amazonaws.com' }); expect(getApiSubdomainUrl(path).href).toEqual(`https://34-234.whatever.compute.amazonaws.com/api${path}`); }); it('should return api subdomain url for DoH IPv4', () => { mockWindowLocation({ origin: 'https://34.234.12.145' }); expect(getApiSubdomainUrl(path).href).toEqual(`https://34.234.12.145/api${path}`); }); it('should return api subdomain url for DoH IPv4 with port', () => { mockWindowLocation({ origin: 'https://34.234.12.145:65' }); expect(getApiSubdomainUrl(path).href).toEqual(`https://34.234.12.145:65/api${path}`); }); it('should return api subdomain url for DoH IPv6', () => { mockWindowLocation({ origin: 'https://[2001:db8::8a2e:370:7334]' }); expect(getApiSubdomainUrl(path).href).toEqual(`https://[2001:db8::8a2e:370:7334]/api${path}`); }); it('should return api subdomain url for DoH IPv6 with port', () => { mockWindowLocation({ origin: 'https://[2001:db8::8a2e:370:7334]:65' }); expect(getApiSubdomainUrl(path).href).toEqual(`https://[2001:db8::8a2e:370:7334]:65/api${path}`); }); it('should return api subdomain url', () => { mockWindowLocation({ hostname: windowHostname }); expect(getApiSubdomainUrl(path).href).toEqual(`https://mail-api.proton.pink${path}`); }); }); describe('getAppUrlFromApiUrl', () => { it('should return app Url from api url', () => { expect(getAppUrlFromApiUrl('https://mail.proton.me/api', APPS.PROTONMAIL).href).toEqual(`${mailUrl}/`); }); }); describe('getAppUrlRelativeToOrigin', () => { it('should return app url relative to origin', () => { expect(getAppUrlRelativeToOrigin(`${mailUrl}${path}`, APPS.PROTONDRIVE).href).toEqual( `https://drive.proton.me${path}` ); }); }); describe('getStaticURL', () => { afterEach(() => { resetWindowLocation(); }); it('should return the static url for localhost', () => { mockWindowLocation({ hostname: 'localhost' }); expect(getStaticURL(path)).toEqual(`https://proton.me${path}`); }); it('should return the correct static url', () => { mockWindowLocation({ hostname: windowHostname }); expect(getStaticURL(path)).toEqual(`https://proton.me${path}`); }); }); describe('isValidHttpUrl', () => { it('should be a valid HTTP url', () => { const httpsUrl = mailUrl; const httpUrl = 'http://mail.proton.me'; expect(isValidHttpUrl(httpsUrl)).toBeTruthy(); expect(isValidHttpUrl(httpUrl)).toBeTruthy(); }); it('should not be a valid HTTP url', () => { const string = 'invalid'; expect(isValidHttpUrl(string)).toBeFalsy(); }); }); describe('isAppFromURL', () => { it('should be a URL from the current app', () => { expect(isAppFromURL(mailUrl, APPS.PROTONMAIL)).toBeTruthy(); }); it('should not be a URL from the current app', () => { expect(isAppFromURL(mailUrl, APPS.PROTONCALENDAR)).toBeFalsy(); }); }); describe('formatURLForAjaxRequest', () => { const ajaxParam = 'load=ajax'; const randomParam = '?someParam=param'; afterEach(() => { resetWindowLocation(); }); it('should add the ajax params to the URL when no params', () => { mockWindowLocation({ href: mailUrl }); expect(formatURLForAjaxRequest().search).toEqual(`?${ajaxParam}`); }); it('should concatenate the ajax params to the URL when params', () => { mockWindowLocation({ href: `${mailUrl}${randomParam}` }); expect(formatURLForAjaxRequest().search).toEqual(`${randomParam}&${ajaxParam}`); }); }); describe('stringifySearchParams()', () => { it('should not stringify empty values', () => { expect( stringifySearchParams({ plan: '', currency: undefined, }) ).toBe(''); }); it('should not stringify empty values with value', () => { expect( stringifySearchParams({ plan: '', currency: undefined, coupon: 'test', }) ).toBe('coupon=test'); }); });
8,862
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/helpers/validators.spec.ts
import { isURL } from '@proton/shared/lib/helpers/validators'; describe('isURL', () => { it('should return true for valid URLs', () => { const calendarLink = 'https://calendar.proton.me/api/calendar/v1/url/mGwA0H_CF5I8hNQU-p4FqUxFCFW3AsJE7BxzMzQHe0wmCiT_dyd3G0xl0WUCQmtHSQSfQ4rhACeFIVpsVjO3Kw==/calendar.ics?CacheKey=LRO6Cif1PdTj0Ys-Ox0Idw%3D%3D&PassphraseKey=vNIxDirYWB7r3f6BpgA5JT_flDIFQs0xh0uhImvTcY0%3D'; const urls = ['https://www.proton.me', 'http://www.proton.me', 'www.proton.me', calendarLink]; const results = urls.map((url) => isURL(url)); expect(results.every((result) => result === true)).toBe(true); }); it('should return false if protocol and www are missing', () => { expect(isURL('proton.me')).toBe(false); }); it('should return false if extra text is added to valid urls', () => { const urls = [' https://www.proton.me ', 'myURL is http://www.proton.me', 'www.proton.me is my URL']; const results = urls.map((url) => isURL(url)); expect(results.every((result) => result === false)).toBe(true); }); });
8,863
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/i18n/helper.spec.js
import { format } from 'date-fns'; import cnLocale from 'date-fns/locale/zh-CN'; import { c } from 'ttag'; import { DEFAULT_LOCALE } from '../../lib/constants'; import { getDateFnLocaleWithTimeFormat } from '../../lib/i18n/dateFnLocale'; import { getClosestLocaleMatch, getIntlLocale, getLanguageCode, getNaiveCountryCode } from '../../lib/i18n/helper'; import { loadDateLocale, loadLocale } from '../../lib/i18n/loadLocale'; import { SETTINGS_TIME_FORMAT } from '../../lib/interfaces'; describe('helper', () => { it('should get the closest locale', () => { expect(getClosestLocaleMatch('en_US', { en_US: true })).toBe('en_US'); expect(getClosestLocaleMatch('kab_KAB', { kab_KAB: true })).toBe('kab_KAB'); expect(getClosestLocaleMatch('kab', { kab_KAB: true })).toBe('kab_KAB'); expect(getClosestLocaleMatch('ka', { kab_KAB: true })).toBeUndefined(); expect(getClosestLocaleMatch('en', { en_US: true })).toBe('en_US'); expect(getClosestLocaleMatch('sv', { en_US: true })).toBeUndefined(); expect(getClosestLocaleMatch('en_US', { en_US: true, sv_SE: true })).toBe('en_US'); expect(getClosestLocaleMatch('en_US', { aa_AA: true, en_US: true })).toBe('en_US'); expect(getClosestLocaleMatch('en', { aa_AA: true, en_US: true })).toBe('en_US'); expect(getClosestLocaleMatch('fr_BE', { aa_AA: true, fr_CA: true, fr_FR: true, fr: true })).toBe('fr'); expect(getClosestLocaleMatch('fr_BE', { aa_AA: true, fr_CA: true, fr_FR: true })).toBe('fr_FR'); expect(getClosestLocaleMatch('fr', { aa_AA: true, fr_CA: true, fr_FR: true })).toBe('fr_FR'); }); it('should get the language code', () => { expect(getLanguageCode('en_US')).toBe('en'); expect(getLanguageCode('kab_KAB')).toBe('kab'); expect(getLanguageCode('sv-se')).toBe('sv'); }); }); const getTranslation = (data) => { return { headers: { 'plural-forms': 'nplurals=2; plural=(n != 1);', }, contexts: { Action: { 'Hey monique': [data], }, }, }; }; describe('Load the locale', () => { afterEach(() => { void loadLocale(DEFAULT_LOCALE, {}); }); it('should load a fr_FR translation', async () => { await loadLocale('fr_FR', { fr_FR: async () => getTranslation('Salut monique') }); expect(c('Action').t`Hey monique`).toBe('Salut monique'); }); }); describe('Load date locales', () => { afterEach(() => { void loadDateLocale(DEFAULT_LOCALE); }); const zero = new Date(2000, 0, 1, 0, 0, 0); it('should load a fr_FR date locale if the translation exists', async () => { const dateFnLocale = await loadDateLocale('fr'); expect(format(zero, 'iiii', { locale: dateFnLocale })).toBe('samedi'); }); it('should use long date format from browser and other format from locale in american english', async () => { const dateFnLocale = await loadDateLocale('en_US', 'en_US'); expect(format(zero, 'Pp', { locale: dateFnLocale })).toBe('01/01/2000, 12:00 AM'); }); it('should use long date format from browser and other format from locale english', async () => { const dateFnLocale = await loadDateLocale('en_US', 'en_GB'); expect(format(zero, 'Pp', { locale: dateFnLocale })).toBe('01/01/2000, 00:00'); }); it('should use long date format from browser and other format from locale', async () => { const dateFnLocale = await loadDateLocale('en_US', 'en_US', { TimeFormat: SETTINGS_TIME_FORMAT.H24 }); expect(format(zero, 'Pp', { locale: dateFnLocale })).toBe('01/01/2000, 00:00'); }); it('should keep long date format from locale and only override time', async () => { const dateFnLocale = await loadDateLocale('fr_FR', 'en_US'); expect(format(zero, 'PPPPp', { locale: dateFnLocale })).toBe('samedi 1 janvier 2000 à 12:00 AM'); }); it('should keep long date format from locale', async () => { const dateFnLocale = await loadDateLocale('fr_FR', 'fr_FR'); expect(format(zero, 'PPPPp', { locale: dateFnLocale })).toBe('samedi 1 janvier 2000 à 00:00'); }); it('should keep short long date format from locale', async () => { const dateFnLocale = await loadDateLocale('fr_FR', 'fr_FR'); expect(format(zero, 'Pp', { locale: dateFnLocale })).toBe('01/01/2000, 00:00'); }); it('should keep short long date format from locale, and only override short time', async () => { const dateFnLocale = await loadDateLocale('fr_FR', 'en_US'); expect(format(zero, 'Pp', { locale: dateFnLocale })).toBe('01/01/2000, 12:00 AM'); }); it('should keep medium long date format from locale', async () => { const dateFnLocale = await loadDateLocale('fr_FR', 'fr_FR'); expect(format(zero, 'PPp', { locale: dateFnLocale })).toBe('1 janv. 2000, 00:00'); }); it('should keep medium long date format from locale, and only override short time', async () => { const dateFnLocale = await loadDateLocale('fr_FR', 'en_US'); expect(format(zero, 'PPp', { locale: dateFnLocale })).toBe('1 janv. 2000, 12:00 AM'); }); it('should override medium time', async () => { const dateFnLocale = await loadDateLocale('fr_FR', 'fr_FR'); expect(format(zero, 'PPpp', { locale: dateFnLocale })).toBe('1 janv. 2000, 00:00:00'); }); it('should keep medium long date format from locale, and only override medium time', async () => { const dateFnLocale = await loadDateLocale('fr_FR', 'en_US'); expect(format(zero, 'PPpp', { locale: dateFnLocale })).toBe('1 janv. 2000, 12:00:00 AM'); }); it('should override time format and date format with 12 hour format', async () => { const dateFnLocale = await loadDateLocale('en_US', 'en_US', { TimeFormat: SETTINGS_TIME_FORMAT.H24 }); expect(format(zero, 'p', { locale: getDateFnLocaleWithTimeFormat(dateFnLocale, true) })).toBe('12:00 AM'); expect( format(zero, 'p', { locale: getDateFnLocaleWithTimeFormat(dateFnLocale, false), }) ).toBe('00:00'); expect( format(zero, 'p', { locale: getDateFnLocaleWithTimeFormat(cnLocale, false), }) ).toBe('00:00'); expect( format(zero, 'p', { locale: getDateFnLocaleWithTimeFormat(cnLocale, true), }) ).toBe('上午 12:00'); }); }); describe('getNaiveCountryCode()', () => { it('should return undefined when passed the empty string', () => { expect(getNaiveCountryCode('')).toBeUndefined(); }); it('should return undefined when the country part is not present', () => { expect(getNaiveCountryCode('en')).toBeUndefined(); }); it('should return the correct country code (in lowercase) for various locale spellings', () => { expect(getNaiveCountryCode('en-US')).toEqual('us'); expect(getNaiveCountryCode('es-ar')).toEqual('ar'); expect(getNaiveCountryCode('fr_BE')).toEqual('be'); }); }); describe('getIntlLocale()', () => { it('handles the case with no country code', () => { // Kiga language expect(getIntlLocale('cgg')).toEqual('cgg'); }); it('handle the case with country code', () => { expect(getIntlLocale('zh_ZH')).toEqual('zh-zh'); }); it('should handle the case with alphabet plus country code', () => { expect(getIntlLocale('bs_Cyrl_BA')).toEqual('bs-cyrl-ba'); }); });
8,864
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/i18n/relocalize.spec.ts
import { format } from 'date-fns'; import { LocaleData, c, useLocale as ttagUseLocale } from 'ttag'; import { DEFAULT_LOCALE } from '../../lib/constants'; import { dateLocale } from '../../lib/i18n'; import { loadDateLocale, loadLocale } from '../../lib/i18n/loadLocale'; import { setTtagLocales } from '../../lib/i18n/locales'; import { relocalizeText } from '../../lib/i18n/relocalize'; import { UserSettings } from '../../lib/interfaces'; const dummyUserSettings: Pick<UserSettings, 'TimeFormat' | 'DateFormat' | 'WeekStart'> = { WeekStart: 1, DateFormat: 1, TimeFormat: 1, }; const getTranslation = (data: string) => { return { headers: { 'plural-forms': 'nplurals=2; plural=(n != 1);', }, contexts: { Info: { 'This is not a pipe': [data], }, }, } as unknown as LocaleData; // the LocaleData type is wrong. }; const getTranslationWithDate = (data: string) => { return { headers: { 'plural-forms': 'nplurals=2; plural=(n != 1);', }, contexts: { Info: { // eslint-disable-next-line no-template-curly-in-string 'December 16th 2021 was a ${ formattedDate }': [data], }, }, } as unknown as LocaleData; // the LocaleData type is wrong. }; const getLocalizedText = () => c('Info').t`This is not a pipe`; const getLocalizedTextWithDate = () => { const formattedDate = format(new Date(2021, 11, 16), 'cccc', { locale: dateLocale }); return c('Info').t`December 16th 2021 was a ${formattedDate}`; }; describe('relocalizeText', () => { afterEach(() => { setTtagLocales({}); ttagUseLocale(DEFAULT_LOCALE); void loadDateLocale(DEFAULT_LOCALE); }); it('should localize to a different locale only inside the relocalizeText context', async () => { const locales = { fr_FR: async () => getTranslation("Ceci n'est pas une pipe"), it_IT: async () => getTranslation('Questa non è una pipa'), }; setTtagLocales(locales); await loadLocale('fr_FR', locales); expect( await relocalizeText({ getLocalizedText, newLocaleCode: 'it_IT', userSettings: dummyUserSettings, }) ).toEqual('Questa non è una pipa'); expect(getLocalizedText()).toEqual("Ceci n'est pas une pipe"); }); it('should not try to load the default locale', async () => { const locales = { fr_FR: async () => getTranslation("Ceci n'est pas une pipe"), it_IT: async () => getTranslation('Questa non è una pipa'), }; setTtagLocales(locales); await loadLocale('fr_FR', locales); expect( await relocalizeText({ getLocalizedText, newLocaleCode: DEFAULT_LOCALE, userSettings: dummyUserSettings, }) ).toEqual('This is not a pipe'); // notice that if relocalizeText tried to load the default locale, it would fail // and fall in the next test (fallback to current locale if the locale passed has no data) }); it('should fallback to the current locale if the locale passed has no data', async () => { const locales = { fr_FR: async () => getTranslation("Ceci n'est pas une pipe"), it_IT: async () => getTranslation('Questa non è una pipa'), gl_ES: undefined, }; setTtagLocales(locales); await loadLocale('fr_FR', locales); expect( await relocalizeText({ getLocalizedText, newLocaleCode: 'gl_ES', userSettings: dummyUserSettings, }) ).toEqual("Ceci n'est pas une pipe"); expect(getLocalizedText()).toEqual("Ceci n'est pas une pipe"); }); it('should fallback to the current locale if no locale is passed', async () => { expect( await relocalizeText({ getLocalizedText, userSettings: dummyUserSettings, }) ).toEqual('This is not a pipe'); }); it('should relocalize without date format', async () => { setTtagLocales({ // eslint-disable-next-line no-template-curly-in-string es_ES: async () => getTranslationWithDate('El 16 de diciembre de 2021 fue un ${ formattedDate }'), }); expect( await relocalizeText({ getLocalizedText: getLocalizedTextWithDate, newLocaleCode: 'es_ES', userSettings: dummyUserSettings, }) ).toEqual('El 16 de diciembre de 2021 fue un Thursday'); }); it('should relocalize with date format', async () => { setTtagLocales({ // eslint-disable-next-line no-template-curly-in-string es_ES: async () => getTranslationWithDate('El 16 de diciembre de 2021 fue un ${ formattedDate }'), }); await loadDateLocale('es_ES', 'es_ES'); expect( await relocalizeText({ getLocalizedText: getLocalizedTextWithDate, newLocaleCode: 'es_ES', relocalizeDateFormat: true, userSettings: dummyUserSettings, }) ).toEqual('El 16 de diciembre de 2021 fue un jueves'); }); it('should fallback to current date locale if no date locale data is found', async () => { setTtagLocales({ // eslint-disable-next-line no-template-curly-in-string xx_XX: async () => getTranslationWithDate('blah blah blah ${ formattedDate }'), }); expect( await relocalizeText({ getLocalizedText: getLocalizedTextWithDate, newLocaleCode: 'xx_XX', relocalizeDateFormat: true, userSettings: dummyUserSettings, }) ).toEqual('blah blah blah Thursday'); }); });
8,865
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/addressKeys.spec.ts
import { decryptAddressKeyToken, generateAddressKeyTokens, generateUserKey } from '../../lib/keys'; describe('address keys', () => { it('should generate address key tokens', async () => { const { privateKey } = await generateUserKey({ passphrase: '123', }); const result = await generateAddressKeyTokens(privateKey); expect(result).toEqual({ token: jasmine.any(String), encryptedToken: jasmine.stringMatching(/-----BEGIN PGP MESSAGE-----.*/), signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/), }); const decryptedResult = await decryptAddressKeyToken({ Token: result.encryptedToken, Signature: result.signature, privateKeys: privateKey, publicKeys: privateKey, }); expect(decryptedResult).toEqual(result.token); }); it('should generate address key tokens with organization', async () => { const { privateKey } = await generateUserKey({ passphrase: '123', }); const { privateKey: organizationKey } = await generateUserKey({ passphrase: 'asd', }); const result = await generateAddressKeyTokens(privateKey, organizationKey); expect(result).toEqual({ token: jasmine.any(String), encryptedToken: jasmine.stringMatching(/-----BEGIN PGP MESSAGE-----.*/), signature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/), organizationSignature: jasmine.stringMatching(/-----BEGIN PGP SIGNATURE-----.*/), }); const decryptedResult = await decryptAddressKeyToken({ Token: result.encryptedToken, Signature: result.signature, privateKeys: privateKey, publicKeys: privateKey, }); expect(decryptedResult).toEqual(result.token); const decryptedResult2 = await decryptAddressKeyToken({ Token: result.encryptedToken, Signature: result.organizationSignature, privateKeys: organizationKey, publicKeys: organizationKey, }); expect(decryptedResult2).toEqual(result.token); }); });
8,866
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/calendarKeys.spec.js
import { CryptoProxy } from '@proton/crypto'; import { decryptPassphrase } from '../../lib/calendar/crypto/keys/calendarKeys'; import { DecryptableKey } from './keys.data'; const armoredPassphrase = ` -----BEGIN PGP MESSAGE----- Version: ProtonMail Comment: https://protonmail.com wV4DatuD4HBmK9ESAQdAh5aMHBZCvQYA9q2Gm4j5LJYj0N/ETwHe/+Icmt09 yl8w81ByP+wHwvShTNdKZNv7ziSuGkYloQ9Y2hReRQR0Vdacz4LtBa2T3H17 aBbI/rBs0mQB8pECtS5Mmdeh+pBh0SN5j5TqWLagXatVn37yRtct0OvyFF6j AoQtEASjLelCBOAtK3amaYeZ5mGdSOcybtepGeTcyM0zf+Y2KuzIxROpaymt m2jIMVyDowE7kRwDxVX7XvSq =9bP1 -----END PGP MESSAGE----- `.trim(); const armoredSignature = ` -----BEGIN PGP SIGNATURE----- Version: OpenPGP.js v4.5.5 Comment: https://openpgpjs.org wl4EARYKAAYFAl1JPxQACgkQuDHP9BZVsEJzkwD+MI44euNKeOxieGTFGO9u OAHrDOiPA5x8A7j1l4FaKWcBAL1Vt1x1FBxusxu7l+NNAv8J539x5s8lV+nP DYr2mrcN =A2xd -----END PGP SIGNATURE----- `.trim(); const calendarKey = ` -----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v4.5.5 Comment: https://openpgpjs.org xYYEXUk/FBYJKwYBBAHaRw8BAQdAz+rSEK/3XmhIeLQfpsmIPq96IrKYewYx sagGgYBDg5H+CQMIAAECAwQFBgdgAAECAwQFBgcICQoLDA0OD9OqXwtfZYoj JIdFbcHhUS5yJ1xROSrUnl/G6nm1hWp2Bawqhs/Enu+ZnXp78uOminXD239v V80MQ2FsZW5kYXIga2V5wncEEBYKAB8FAl1JPxQGCwkHCAMCBBUICgIDFgIB AhkBAhsDAh4BAAoJEG2YDApRSYyCRVIBAPiVZbaAfPqxjtNplhOtKiInEMju lRBfEGsA0dw4YllWAQDl5OTLUSnywGs47jbS4SpjpswmTl9e3JX19sawLEdA DceLBF1JPxQSCisGAQQBl1UBBQEBB0DTysT2EeKaVxfAN7nLXeibxVnkxrt3 No5bjB2YFVgZGQMBCAf+CQMIAAECAwQFBgdgAAECAwQFBgcICQoLDA0OD9JV 7BuCpJ7I2eelK/l9TYqQl6kquunkC7yLgps7yHxoJBywtitxiwO7xN7EawAQ sRFYHrU2NMJhBBgWCAAJBQJdST8UAhsMAAoJEG2YDApRSYyCNJgA/jUdOIP6 m8kopzHnGC4AScqWC3mZptPAots23z6lJYojAQDo35pvSA24qZgUx4ZtIpHd AHuAp3/jX0kawmQsHXK9Bg== =5JEj -----END PGP PRIVATE KEY BLOCK----- `; describe('keys', () => { it('should prepare calendar keys for owner', async () => { const decryptedPrivateKey = await CryptoProxy.importPrivateKey({ armoredKey: DecryptableKey.PrivateKey, passphrase: '123', }); const decryptedPassphrase = await decryptPassphrase({ armoredPassphrase, armoredSignature, privateKeys: decryptedPrivateKey, publicKeys: decryptedPrivateKey, }); const decryptedCalendarKey = await CryptoProxy.importPrivateKey({ armoredKey: calendarKey, passphrase: decryptedPassphrase, }); expect(decryptedCalendarKey.isPrivate()).toBeTruthy(); }); });
8,867
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/driveKeys.spec.ts
import { CryptoProxy } from '@proton/crypto'; import { decryptUnsigned } from '../../lib/keys/driveKeys'; const shareKey = '-----BEGIN PGP PRIVATE KEY BLOCK-----\r\nVersion: OpenPGP.js v4.4.7\r\nComment: https://openpgpjs.org\r\n\r\nxYYEXc5yKRYJKwYBBAHaRw8BAQdA7YwZxjkyb1yO+SbFT9fIgjIec6vjvFv8\r\nALFUUkDfFlH+CQMIlbaxxwTqxCxg2HU8LGqFPpBAD0A/TvV9kXdZwhycrEDn\r\nKy/2v6wWMSp5gzXgX1FxhOmg5uWNhW3P9/dIt32F+fRrolr+uljAvZB7zBN1\r\nWM0XSm9obiBEb2UgPGpvaG5AZG9lLmRvZT7CdwQQFgoAHwUCXc5yKQYLCQcI\r\nAwIEFQgKAgMWAgECGQECGwMCHgEACgkQ8y3YQiuJcn7Y+AEAzPynnBV2cjd2\r\nVrDtpNVXiGIk3CSSqEl5fpgRyxuD4HoBALcyYPyaJxPxNml99ZZ3p4GuJ474\r\nobF83u/7Lk6vhJ0Px4sEXc5yKRIKKwYBBAGXVQEFAQEHQPnJbOsSgJnu399H\r\niMn8iV8kMNkO65lkaofKmdwPUTQMAwEIB/4JAwjxK/aFhMu7xWCx5fIR519p\r\n3cxxTRdUo09VrK9Fm7fXKa6+GIPccTabyy53dZ9edneZ+GZRRQOos/vG+3zS\r\n3ICeUYGyVT3H5WkUqc+zl18LwmEEGBYIAAkFAl3OcikCGwwACgkQ8y3YQiuJ\r\ncn4i5gD7BQX8rl0tRIcNpY+e71mIbx+/+PANMzlGXNBxtySpXAgBAKKgI/3M\r\npNM92ezA6/XB7O5b0dhooMQvwAxSOS1W07kA\r\n=U3/f\r\n-----END PGP PRIVATE KEY BLOCK-----\r\n'.trim(); const addressKey = '-----BEGIN PGP PRIVATE KEY BLOCK-----\nVersion: ProtonMail\n\nxcMGBFSI0BMBB/9td6B5RDzVSFTlFzYOS4JxIb5agt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saFmo1qyQaQrb1rYM9U1qBW9/lr0RxEDz0ciTXR1rsOLtBsgghD95\n2vlxPwhS9ySKTOkbGonX3USthWhztQtJVqoAbXvaoZ05Uva6gOd67phmBMNS\nVaCK5KLhNgGQmH6O0gcAhDoYj5HEKEsSS6nVVbALkhHuIjXJKDpx0eBB2UkU\nUqwHsAWcsxCUreXSsr1X0AMNtmP9iMTNnUSm6/0rmnUwA6/uPtasng8MPtYQ\n7W+fRSMAVfXUqGg24pQm0PZK7mQ=\n=HFGf\n-----END PGP PRIVATE KEY BLOCK-----\n'; const passphrase = '-----BEGIN PGP MESSAGE-----\nVersion: ProtonMail\n\nwcBMA6rw6TH9oRKuAQf/dm5wc29Oi51Ieq/miflqQ4rxGvfhe4WD4L9zPxOe\nfe1nndclW0I/7zJ49bmEQGOIw3lBVnBJotupYH8We82+31lICcKdwNAhLwRD\nowCNKPHrgRwpMohz33r/vkjf/QsGLW2xstrqk+ZZqqEtANHnSfnTxU9XJIiJ\nlVkXZ/5cpTwvCGOLapSiHUG8bYhZikxr9CSM0fMCnuwlYGbhd+o9FoWOIVpg\nQZHfxioyramL6GmiXZ15FvRS3Gd3pjjATZY/wv19LQkv1NJSugyGx1X6fj5D\n8tf1Yh7OVDueY9gtYs+oV+d64czbvW/q30MKWgf5EipiS4ZA2PSEYNMP9OWo\nf9J4AVAMupTz2usGyX/3rF2r2JhsZMVLcuBlaBbi0GZcyGkiMmCl/+f7fRTc\nIVLCuzqftyh9VAQyj6T2x2fe3S0ivfJFVwEnF4QJ/K4+j9qgnkN9aGXX4UkU\nMKtBrnZ8BmtMn0FBQWicz1JeGX+YGmcT476uj2psxxJS\n=3Go2\n-----END PGP MESSAGE-----\n'; const folderName = '-----BEGIN PGP MESSAGE-----\nVersion: ProtonMail\n\nwV4D7bIbvfUVIgMSAQdAo0jDKpBeHzQDAjGPYPgMjLUFa3Rfs2U1c/XJxD69\njRow+Hz5SU5CAkSJmSHHYsctlaCcsRCfmkl62A5JIXfV/wHRDk0Usi6NIstq\n3aD+ywyr0j8BNY0gX2w08fWEyMDGAcYeqJay0zmsPRg9l59XYySAOAShlVvN\nQa/vQWCAxl/Bk1iYctxCPCDVslSMYRJeG2A=\n=Lj9p\n-----END PGP MESSAGE-----\n'.trim(); describe('drive keys', () => { it('should prepare drive keys', async () => { const decryptedPrivateKey = await CryptoProxy.importPrivateKey({ armoredKey: addressKey, passphrase: 'oXueLX2EKIM.mwS7qmU2wvfNXb3KI3i', }); const decryptedPassphrase = await decryptUnsigned({ armoredMessage: passphrase, privateKey: decryptedPrivateKey, }); const decryptedShareKey = await CryptoProxy.importPrivateKey({ armoredKey: shareKey, passphrase: decryptedPassphrase, }); const decryptedFolderName = await decryptUnsigned({ armoredMessage: folderName, privateKey: decryptedShareKey, }); expect(decryptedFolderName).toBe('folder1'); }); });
8,868
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/keyAlgorithm.spec.ts
import { getFormattedAlgorithmNames } from '../../lib/keys'; describe('key algorithm', () => { it('should aggregate same key types and sizes', async () => { const type = getFormattedAlgorithmNames([ { algorithm: 'rsa', bits: 2048 }, { algorithm: 'rsa', bits: 2048 }, { algorithm: 'ecdh', curve: 'P-521' }, { algorithm: 'ecdsa', curve: 'P-256' }, { algorithm: 'ecdh', curve: 'P-256' }, { algorithm: 'elgamal', bits: 4096 }, { algorithm: 'rsa', bits: 4096 }, ]); expect(type).toEqual('RSA (2048), ECC (P-521), ECC (P-256), ElGamal (4096), RSA (4096)'); }); it('should return same curve name for eddsa and edch over curve25519', async () => { const type = getFormattedAlgorithmNames([ { algorithm: 'ecdh', curve: 'curve25519' }, { algorithm: 'eddsa', curve: 'ed25519' }, ]); expect(type).toEqual('ECC (Curve25519)'); }); });
8,869
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/keyDataHelper.ts
import { CryptoProxy, PrivateKeyReference, toPublicKeyReference } from '@proton/crypto'; import { ENCRYPTION_CONFIGS, ENCRYPTION_TYPES } from '../../lib/constants'; import { Key } from '../../lib/interfaces'; import { generateAddressKey, generateAddressKeyTokens, generateUserKey } from '../../lib/keys'; const encryptionConfig = ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519]; export const getUserKey = async (ID: string, keyPassword: string, version = 3) => { const { privateKey, privateKeyArmored } = await generateUserKey({ passphrase: keyPassword, encryptionConfig, }); return { key: { ID, privateKey, publicKey: await toPublicKeyReference(privateKey), }, Key: { ID, PrivateKey: privateKeyArmored, Version: version, } as Key, }; }; export const getAddressKeyHelper = async ( ID: string, userKey: PrivateKeyReference, privateKey: PrivateKeyReference, version = 3 ) => { const result = await generateAddressKeyTokens(userKey); const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey, passphrase: result.token, }); return { key: { ID, privateKey, publicKey: await toPublicKeyReference(privateKey), }, Key: { ID, PrivateKey: privateKeyArmored, Signature: result.signature, Token: result.encryptedToken, Version: version, Flags: 3, } as Key, }; }; export const getAddressKey = async (ID: string, userKey: PrivateKeyReference, email: string, version?: number) => { const key = await generateAddressKey({ email, passphrase: 'tmp', encryptionConfig, }); return getAddressKeyHelper(ID, userKey, key.privateKey, version); }; export const getAddressKeyForE2EEForwarding = async ( ID: string, userKey: PrivateKeyReference, email: string, version?: number ) => { const forwarderKey = await CryptoProxy.generateKey({ userIDs: { email: '[email protected]' }, curve: 'curve25519', }); const { forwardeeKey: armoredKey } = await CryptoProxy.generateE2EEForwardingMaterial({ forwarderKey, userIDsForForwardeeKey: { email }, passphrase: '123', }); const forwardeeKey = await CryptoProxy.importPrivateKey({ armoredKey, passphrase: '123' }); return getAddressKeyHelper(ID, userKey, forwardeeKey, version); }; export const getLegacyAddressKey = async (ID: string, password: string, email: string) => { const key = await generateAddressKey({ email, passphrase: password, encryptionConfig, }); return { key: { ID, privateKey: key.privateKey, publicKey: await toPublicKeyReference(key.privateKey), }, Key: { ID, PrivateKey: key.privateKeyArmored, Version: 3, } as Key, }; };
8,870
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/keyFlags.spec.ts
import { ADDRESS_FLAGS, ADDRESS_TYPE, KEY_FLAG } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { Address } from '@proton/shared/lib/interfaces'; import { getDefaultKeyFlags } from '../../lib/keys/keyFlags'; describe('getDefaultKeyFlags', () => { it('default key flags should be not obsolete and not compromised', () => { const defaultFlags = getDefaultKeyFlags(undefined); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_NOT_OBSOLETE)).toBe(true); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_NOT_COMPROMISED)).toBe(true); }); it('should set external flags for external address', () => { const defaultFlags = getDefaultKeyFlags({ Type: ADDRESS_TYPE.TYPE_EXTERNAL } as Address); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_NOT_OBSOLETE)).toBe(true); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_NOT_COMPROMISED)).toBe(true); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT)).toBe(true); }); it('should set email no encrypt flag for address with disable e2ee flag', () => { const defaultFlags = getDefaultKeyFlags({ Flags: ADDRESS_FLAGS.FLAG_DISABLE_E2EE } as Address); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_NOT_OBSOLETE)).toBe(true); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_NOT_COMPROMISED)).toBe(true); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT)).toBe(true); }); it('should set email no sign flag for address with disable expected signed flag', () => { const defaultFlags = getDefaultKeyFlags({ Flags: ADDRESS_FLAGS.FLAG_DISABLE_EXPECTED_SIGNED } as Address); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_NOT_OBSOLETE)).toBe(true); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_NOT_COMPROMISED)).toBe(true); expect(hasBit(defaultFlags, KEY_FLAG.FLAG_EMAIL_NO_SIGN)).toBe(true); }); });
8,871
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/keyImport.spec.js
import { parseArmoredKeys, parseKeys } from '../../lib/keys'; const VALID_KEY = '-----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+WP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IasN2S2pEqXiLPgPpM5O39c0S8XVv4k+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-----'; const INVALID_KEY = `-----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v4.2.2 Comment: https://openpgpjs.org =twTO -----END PGP PRIVATE KEY BLOCK-----`; const KEY_DATA2 = `-----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v4.2.2 Comment: https://openpgpjs.org = -----END PGP PRIVATE KEY BLOCK-----`; describe('key import', () => { it('should parse key', () => { const parsedKeys = parseArmoredKeys(INVALID_KEY); expect(parsedKeys).toEqual([INVALID_KEY]); }); it('should parse multiple keys', () => { const parsedKeys = parseArmoredKeys(` ${INVALID_KEY} random data foo ${KEY_DATA2} `); expect(parsedKeys).toEqual([INVALID_KEY, KEY_DATA2]); }); it('should handle invalid keys', async () => { const parsedKeys = await parseKeys([INVALID_KEY]); expect(parsedKeys).toEqual([]); }); it('should handle valid keys', async () => { const parsedKeys = await parseKeys([VALID_KEY]); expect(parsedKeys).toEqual([jasmine.any(Object)]); }); });
8,872
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/keyMigration.spec.ts
import { Unwrap, Address as tsAddress, User as tsUser } from '../../lib/interfaces'; import { decryptAddressKeyToken, getDecryptedAddressKeysHelper, getDecryptedUserKeysHelper, getEmailFromKey, splitKeys, } from '../../lib/keys'; import { getAddressKeysMigrationPayload, migrateAddressKeys } from '../../lib/keys/keyMigration'; import { getLegacyAddressKey, getUserKey } from './keyDataHelper'; const DEFAULT_KEYPASSWORD = '123'; const getAddress = async (id: number, email: string, keyPassword: string, nKeys: number) => { const addressKeysFull = await Promise.all( Array.from({ length: nKeys }) .fill(undefined) .map((_, i) => getLegacyAddressKey(`${email}${i}`, keyPassword, email)) ); return { ID: `AddressID${id}`, Email: email, Keys: addressKeysFull.map(({ Key }) => Key), } as unknown as tsAddress; }; const getSetup1 = async () => { const keyPassword = DEFAULT_KEYPASSWORD; const OrganizationKeyFull = await getUserKey('a', keyPassword); const UserKeysFull = await Promise.all([getUserKey('1', keyPassword), getUserKey('2', keyPassword)]); const User = { Keys: UserKeysFull.map(({ Key }) => Key), } as unknown as tsUser; const userKeys = await getDecryptedUserKeysHelper(User, keyPassword); const Addresses = await Promise.all([ getAddress(1, '[email protected]', keyPassword, 3), getAddress(2, '[email protected]', keyPassword, 1), getAddress(3, '[email protected]', keyPassword, 2), ]); const addressKeys = await Promise.all( Addresses.map((address) => { return getDecryptedAddressKeysHelper(address.Keys, User, userKeys, DEFAULT_KEYPASSWORD); }) ); return { organizationKey: { Key: { PrivateKey: OrganizationKeyFull.Key.PrivateKey, PublicKey: OrganizationKeyFull.Key.PublicKey, }, key: OrganizationKeyFull.key, }, User, Addresses, userKeys, addressKeys, }; }; describe('key migration', () => { const verifyStandard = async ({ Addresses, User, result, addressKeys, userKeys, }: { result: Unwrap<ReturnType<typeof getAddressKeysMigrationPayload>>; } & Unwrap<ReturnType<typeof getSetup1>>) => { const decryptedMigratedKeys = await Promise.all( Addresses.map((address) => { const keys = result.AddressKeys.filter((x) => { return address.Keys.some(({ ID }) => ID === x.ID); }); return getDecryptedAddressKeysHelper(keys as any, User, userKeys, ''); // No longer decrypting with the old key password }) ); expect(addressKeys.flat().length).toEqual(decryptedMigratedKeys.flat().length); const { privateKeys, publicKeys } = splitKeys(userKeys); expect( await decryptAddressKeyToken({ Token: result.AddressKeys[0].Token, Signature: result.AddressKeys[0].Signature, privateKeys, publicKeys, }) ).not.toEqual( await decryptAddressKeyToken({ Token: result.AddressKeys[1].Token, Signature: result.AddressKeys[1].Signature, privateKeys, publicKeys, }) ); decryptedMigratedKeys.forEach((keys, i) => { keys.forEach((key, j) => { expect(key.privateKey.getFingerprint()).toEqual(addressKeys[i][j].privateKey.getFingerprint()); }); }); decryptedMigratedKeys.forEach((keys, i) => { keys.forEach((key) => { expect(getEmailFromKey(key.privateKey)).toEqual(Addresses[i].Email); }); }); }; it('should migrate keys in the legacy format', async () => { const { User, Addresses, userKeys, addressKeys, organizationKey } = await getSetup1(); const migratedKeys = await migrateAddressKeys({ user: User, addresses: Addresses, keyPassword: DEFAULT_KEYPASSWORD, preAuthKTVerify: () => async () => {}, keyMigrationKTVerifier: async () => {}, }); const result = await getAddressKeysMigrationPayload(migratedKeys); await verifyStandard({ organizationKey, Addresses, User, userKeys, result, addressKeys, }); expect(result.SignedKeyLists).toEqual({ [Addresses[0].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, [Addresses[1].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, [Addresses[2].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }); // @ts-ignore expect(result.AddressKeys[0].OrgSignature).not.toBeDefined(); }); it('should migrate keys in the legacy format where some addresses are missing keys', async () => { const { User, Addresses, userKeys, addressKeys, organizationKey } = await getSetup1(); Addresses[2].Keys.length = 0; addressKeys[2].length = 0; const migratedKeys = await migrateAddressKeys({ user: User, addresses: Addresses, keyPassword: DEFAULT_KEYPASSWORD, preAuthKTVerify: () => async () => {}, keyMigrationKTVerifier: async () => {}, }); const result = await getAddressKeysMigrationPayload(migratedKeys); await verifyStandard({ organizationKey, Addresses, User, userKeys, result, addressKeys, }); expect(result.SignedKeyLists).toEqual({ [Addresses[0].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, [Addresses[1].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }); // @ts-ignore expect(result.AddressKeys[0].OrgSignature).not.toBeDefined(); }); it('should migrate keys in the legacy format with organization signatures', async () => { const { User, Addresses, userKeys, addressKeys, organizationKey } = await getSetup1(); const migratedKeys = await migrateAddressKeys({ user: User, addresses: Addresses, organizationKey: organizationKey.Key, keyPassword: DEFAULT_KEYPASSWORD, preAuthKTVerify: () => async () => {}, keyMigrationKTVerifier: async () => {}, }); const result = await getAddressKeysMigrationPayload(migratedKeys); await verifyStandard({ organizationKey, Addresses, User, userKeys, result, addressKeys, }); expect(result.SignedKeyLists).toEqual({ [Addresses[0].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, [Addresses[1].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, [Addresses[2].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }); const { privateKeys } = splitKeys(userKeys); expect(result.AddressKeys[0].OrgSignature).toEqual(jasmine.stringMatching(/^-----BEGIN PGP SIGNA/)); expect( await decryptAddressKeyToken({ Token: result.AddressKeys[0].Token, Signature: result.AddressKeys[0].OrgSignature, privateKeys, publicKeys: [organizationKey.key.privateKey], }) ).toEqual(jasmine.stringMatching(/[a-z\d]+/)); }); });
8,873
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/keys.data.js
export const OrganizationPrivateKey = ` -----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v4.5.0 Comment: https://openpgpjs.org xYYEXNBCpBYJKwYBBAHaRw8BAQdAmf86hiYoankoKeecFFNpnm6m1QDlZCwZ 1dA434HNtmf+CQMIZcQElGkksCvgyRQ2KTkfsr5/j3SkAIE8Oh32X4kAS+hT 6WLMqX5gzqdztjoobsFJCd+qypomXjZ+VQZ1PsZMpOiBpeWsi6DlTHz6NAHE 980RZm9vIDxmb29AYmFyLmNvbT7CdwQQFgoAHwUCXNBCpAYLCQcIAwIEFQgK AgMWAgECGQECGwMCHgEACgkQD1Kvipcqu202vQD/Xzt5888IgKMetcbqJ1ZY 5EjHGs3QIBWNxGleqmqnEpQBAMvKQ/yZsZiwmC68T76bc6U15JNWPK6f1TTW Ha/CdnkGx4sEXNBCpBIKKwYBBAGXVQEFAQEHQK9+U3tz/Svhl1gWME1yDoXz qo0UAY5Tqs73PtJnamNCAwEIB/4JAwhYZhCs/vlLTeCw20z+9ggEXtQYsjbb fKPqIXMiwZuyFNCzaRG4+aF7BqEbp7NC0RoOnQhrHX+X4JFZ+tVzWAltNiP4 a116oyHjGz2tZCtjwmEEGBYIAAkFAlzQQqQCGwwACgkQD1Kvipcqu230JwEA z2rl2lvxW2HZVE6lJAqlkfAaWYs5YQEZZrs4wKmUvxgBAJNSZCQGl5M+EqCS UIolf5yfshTnoEb4H7P9xjhLpLQF =mI18 -----END PGP PRIVATE KEY BLOCK----- `; export const SubKey = { Token: ` -----BEGIN PGP MESSAGE----- Version: OpenPGP.js v4.5.0 Comment: https://openpgpjs.org wV4D7SU4JRI3QNgSAQdAnXBwFLjb2WvO0jmzJ7sErLDz9jS2rEgyUTTp3jPi T2cwWl7/gm2B/kKIVaKDrvw5OG9Giga1vm0hUsQylVxJf2KLsVijBbqXkv4I V38BqYlu0rgBsC92Ay2uH+dwgJTNKfXhv/FWGLIQGSv2GFqsQ/6jp9uk3fCn aTFHtx0cejHH1Akda0X8DGIpnz7igjp9wNsZJcdqkFUo+/glkE835WctVu3g aQ+nc3mHQ8Vnx8GT0YxO0Oo5Bb5wh09Ftcri0oNxr5/D/NAB80vtSM3t0k3W 5ksJZBxq8yc4QAMGaWjE178IhPAKwdsit62hGCxUq7XqNHKGKA4tTLxWOHnz cPSuuH5Ob5PtYA2O =qVhs -----END PGP MESSAGE----- `, PrivateKey: ` -----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v4.5.0 Comment: https://openpgpjs.org xYYEXNBCpRYJKwYBBAHaRw8BAQdAY+6rHgKwa75irgpNUt16Yyu8ylnd3mm4 I8+2bkzXCH7+CQMI1+FC1Jm20q/gZQW6HmVSpX8j8QW9ZwSZMFnQQa1WL1lI hsrL8II0bU/2BmcyunimPj+K6T7CyN+xoNIugBzNChBEY7HZtobhZ/yu5aV/ Ds0RZm9vIDxmb29AYmFyLmNvbT7CdwQQFgoAHwUCXNBCpQYLCQcIAwIEFQgK AgMWAgECGQECGwMCHgEACgkQ9MsrVK8BXecM/wD/XeXUdUxtcwTpXMa1ueSn zYQOL1L6LaUkt4dhdEXzXPUBALlTOlS7AJshTWO1LyhGmDAsUKVPrHp3BTZY vig2U+MKx4sEXNBCpRIKKwYBBAGXVQEFAQEHQNu9DGSy1hZ8DfPEbR8vvgWc HNwUbVLFUtQs3OU+JiQuAwEIB/4JAwgqc6iv13wBweCwqwPYuwW+FmF5EHxU ccz2szXBvlIMi2spzPt374urog8P+3EZZxBV5natpevAYSGxC9FFuxihn1fw pxRVRIQr9KjEZdMCwmEEGBYIAAkFAlzQQqUCGwwACgkQ9MsrVK8BXee+2AD/ e9OWru1lWO6Wvy7b/Gk4jsYhzXiTfn8Yvw4fLoBxqK8BAIrU/d9TDvfcoAPF tWKU9wATaF9sLKexxzQxxXhR94IN =eMnC -----END PGP PRIVATE KEY BLOCK----- `, }; export const DecryptableKey2 = `-----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v4.5.0 Comment: https://openpgpjs.org xYYEXbDAmRYJKwYBBAHaRw8BAQdAfe6ZazSNIori6Pl1XG/TXStOtE9S7esi 6jQEOX1P37b+CQMIvpEOLC1gZ3jg3Y0C550+dnNliq7WUeD8A8LIz2E4sAqI 2Njd2jD82BIz3hv2O5Scz5VD+j694M95W7NF+/uVTRM3Iqu522ix0Skk+MBa 7s0RZm9vIDxmb29AYmFyLmNvbT7CdwQQFgoAHwUCXbDAmQYLCQcIAwIEFQgK AgMWAgECGQECGwMCHgEACgkQsbOBMqG6FmkNYAEAnZxcC7HKxynN3+Hp8Kkv FQfdFVfss9312et4oZNnkY8BANBtRDQyCHXrAMdf0FGn9mqC4u94QJa+BNVX ueR/2VoDx4sEXbDAmRIKKwYBBAGXVQEFAQEHQM2oY5Tad4yplCEd9Wsy3GRN /596SBNm4xS3syBRR7UGAwEIB/4JAwjz4wPeE8Esb+BKGUcR1IGYv66fDyt7 lafR8PnkDKS0nedjYgWE7NKC29sSgQZiv+YKETpfDUurbcFvn0gGY6861kov 75Hi55k+hdG5J8PTwmEEGBYIAAkFAl2wwJkCGwwACgkQsbOBMqG6FmkOlgD/ YIlUVyxAopRF+ARkJLpfV1rLvw2u3wR6CodPq9C+G9sA+QGFbhU3OyYoromB XK12ljmqW6sNEi9HGzM/2YzJ1G4K =6vVl -----END PGP PRIVATE KEY BLOCK-----`; export const DecryptableKey = { ID: 1, PrivateKey: ` -----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v4.5.0 Comment: https://openpgpjs.org xYYEXNAvVRYJKwYBBAHaRw8BAQdAdURswxCE2cWkc3fl46sngpe4pDGya/Zz vDjJeAwl/hf+CQMIXo0uckLMAWvgTWhZsMVN0hp72MiStdcp3Adx9RC+RD+L CwQk3n0jGnpntJr1VjcENOfYi7/qSm5f6lm6TbDYSPGe9lCNC7K2zTpo95k7 kc0RZm9vIDxmb29AYmFyLmNvbT7CdwQQFgoAHwUCXNAvVQYLCQcIAwIEFQgK AgMWAgECGQECGwMCHgEACgkQuDHP9BZVsEJG2gEAh6EsGq9UjhY9tyAYyduq rZdn6msmD+IW/BnCqo8k47oA/ikNPU9FLlHdy9nKej18Amny5lnWtzSwEDnA IoZPGjIFx4sEXNAvVRIKKwYBBAGXVQEFAQEHQJm+w9npJZTQ5ndvVd8UTSyP /dl/h1KrcuexeRurnuI9AwEIB/4JAwghuHRfaVIB9OARANhlPux+daSE5cWl zZ5KGjJJtzWssmxcxaUO6KKXQS45cirIb5dV9WBNy5ukUnI4v2afQR2pMESG UIdsSknLw35C2dU2wmEEGBYIAAkFAlzQL1UCGwwACgkQuDHP9BZVsEJQdQD+ KRu38xbtYTsc0hn3eG6QdbdvzCJ5yZ1ahJTlH6riO7sBAOy8xqEI0fDEJgXq XmfLbUPJxm1UknwxQ6CVYEWSxukB =urqZ -----END PGP PRIVATE KEY BLOCK-----`, }; export const NotDecryptableKey = { ID: 2, PrivateKey: ` -----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v4.5.0 Comment: https://openpgpjs.org xYYEXNAvgxYJKwYBBAHaRw8BAQdAQRQI5R77lQHaaCJwocjNpO/kxwigLReh 148CqdZejvv+CQMIfEgyCawpESrg5v9RlZoTURzyBi18S0+CW0zti83Err41 D2dDIWWW678Hi8BwUaecFoo4WTQwJJsQKRCBdhK4+7kKn0dJYyVxm7401iF5 0s0RZm9vIDxmb29AYmFyLmNvbT7CdwQQFgoAHwUCXNAvgwYLCQcIAwIEFQgK AgMWAgECGQECGwMCHgEACgkQDSz08AMxtBbM1AD/SyogSEMCOZvjQUqsBqTu VsNuiwyEXMO6BM82IwYEu/gBAMJfbzk9ivJdEy2bltWejZPlIjWbjGA5kk1v WTFUb78Dx4sEXNAvgxIKKwYBBAGXVQEFAQEHQLxyARUOYxLox0IzUh+tD3lP XvQxO1cEAZ/0dve3SLFoAwEIB/4JAwgxg32v/Y7tIOC/Z3IqKXtZretPiZHb uPTW3AJSUv0xaOVC3JsStnCDIVg+AvMql1+KJGDwC2iW/AaTWeQFQp3Fhy9k dLGFD8fWQM/jhZM8wmEEGBYIAAkFAlzQL4MCGwwACgkQDSz08AMxtBbcMgEA 5sLgJ6H7ouCbhWskwuqaTdH1lorESv4ZBDs1VIQlitUA/jALCUOD775Ifg2V 4E3UfqMcqhDAGpwgoFh5EsrEv88L =Ml7H -----END PGP PRIVATE KEY BLOCK-----`, }; // EdDSA public key export const ValidPublicKey = ` -----BEGIN PGP PUBLIC KEY BLOCK----- xjMEYOc8RBYJKwYBBAHaRw8BAQdAxn354Rs9iCHYqLbXNoLNGl1MuEr/8tjD Lt9rMkDzttbNEHRlc3QgPHRlc3RAYS5pdD7CjAQQFgoAHQUCYOc8RAQLCQcI AxUICgQWAAIBAhkBAhsDAh4BACEJEMzGanSo2e7dFiEE7cgw0F5ZXNbQoROa zMZqdKjZ7t2CVgD/TYI9wUd9zSY7KYZavbfl8HWsJCF8aF+8WynvesXpZIUA /2jAOxt/TqazpcGTYJY21Cmwvufn5CXTApkJhjzGhb0BzjgEYOc8RBIKKwYB BAGXVQEFAQEHQPpT1Ctd1jcZJTwYEfxhY+dcXzuQZsCRK8e1evVaO6YpAwEI B8J4BBgWCAAJBQJg5zxEAhsMACEJEMzGanSo2e7dFiEE7cgw0F5ZXNbQoROa zMZqdKjZ7t0hOgEAv8m4CaGFwsvVSczpbUa73wzbWqxnuB9UEtRYhcOcYJQB AO40g98p/ZxNYm7Zegv/7DCP6W4wVvhpwtr/RZd7rjkB =U8gG -----END PGP PUBLIC KEY BLOCK-----`; // EdDSA key expired on Jan 1 1970 export const ExpiredPublicKey = ` -----BEGIN PGP PUBLIC KEY BLOCK----- xjMEAAAAABYJKwYBBAHaRw8BAQdAu08DUumuhfdyTIyoZCLcKF1/A0e6ujNd SznAHVpp9WLNEHRlc3QgPHRlc3RAYS5pdD7CkgQQFgoAIwUCAAAAAAUJAAAA AQQLCQcIAxUICgQWAAIBAhkBAhsDAh4BACEJEP7eRUYKBybyFiEEt+ZbVAWg bVJF3SdI/t5FRgoHJvK7XQEAiGbEkQ4mkINGBIYlhsBWj4MAjkCeB3zewK3e Dw78D2wBAMCGSf3ps7EcImERSKKcQuMaPoTr4J52fN46bsZUjFsDzjgEAAAA ABIKKwYBBAGXVQEFAQEHQPRnYo30IMUCGp//FpGSpO3BXbM1Ip1oUTcn7dzC 0PJIAwEIB8J+BBgWCAAPBQIAAAAABQkAAAABAhsMACEJEP7eRUYKBybyFiEE t+ZbVAWgbVJF3SdI/t5FRgoHJvJu5QEA8bGKykRUsA9ZqQX5o+fIcG43vu2A +PidNixCUHL9B94A/AvpSIhkWrc6JUrWhl/4HXKzmVq84C/5TWLno7oOdy8J =MjnA -----END PGP PUBLIC KEY BLOCK-----`; // EdDSA key without encryption capabilities (no subkey) export const SignOnlyPublicKey = ` -----BEGIN PGP PUBLIC KEY BLOCK----- xjMEYOc76RYJKwYBBAHaRw8BAQdAgV5i0XsBNosHktN+Pzosj8YvTUfgn3Gu MgCXqlKOGMHNEHRlc3QgPHRlc3RAYS5pdD7CjAQQFgoAHQUCYOc76QQLCQcI AxUICgQWAAIBAhkBAhsDAh4BACEJEHR9RR9AGNryFiEEgs2YwCo82ga8uuPp dH1FH0AY2vJqqgEAk+14CR9d0r84zwcg4Vd5SSsKZ/EZRdGGZlLS2WBq+VYB APpV+8G6W3WRsoMBcw7oMo8SqYG8G9HSO8Vcz1kdQokK =E188 -----END PGP PUBLIC KEY BLOCK-----`;
8,874
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/publicKeys.spec.ts
import { CryptoProxy, PublicKeyReference } from '@proton/crypto'; import { RECIPIENT_TYPES } from '../../lib/constants'; import { getContactPublicKeyModel, sortApiKeys, sortPinnedKeys } from '../../lib/keys/publicKeys'; import { ExpiredPublicKey, SignOnlyPublicKey, ValidPublicKey } from './keys.data'; describe('get contact public key model', () => { const publicKeyConfig = { emailAddress: '', apiKeysConfig: { Keys: [], publicKeys: [], SignedKeyList: null, }, }; it('should mark valid key as capable of encryption', async () => { const publicKey = await CryptoProxy.importPublicKey({ armoredKey: ValidPublicKey }); const contactModel = await getContactPublicKeyModel({ ...publicKeyConfig, pinnedKeysConfig: { pinnedKeys: [publicKey], isContact: true, }, }); const fingerprint = publicKey.getFingerprint(); expect(contactModel.encryptionCapableFingerprints.has(fingerprint)).toBeTrue(); }); it('should mark expired key as incapable of encryption', async () => { const publicKey = await CryptoProxy.importPublicKey({ armoredKey: ExpiredPublicKey }); const contactModel = await getContactPublicKeyModel({ ...publicKeyConfig, pinnedKeysConfig: { pinnedKeys: [publicKey], isContact: true, }, }); const fingerprint = publicKey.getFingerprint(); expect(contactModel.encryptionCapableFingerprints.has(fingerprint)).toBeFalse(); }); it('should mark sign-only as incapable of encryption', async () => { const publicKey = await CryptoProxy.importPublicKey({ armoredKey: SignOnlyPublicKey }); const contactModel = await getContactPublicKeyModel({ ...publicKeyConfig, pinnedKeysConfig: { pinnedKeys: [publicKey], isContact: true, }, }); const fingerprint = publicKey.getFingerprint(); expect(contactModel.encryptionCapableFingerprints.has(fingerprint)).toBeFalse(); }); it('should determine encryption flag based on `encryptToPinned` when pinned keys are present', async () => { const publicKey = await CryptoProxy.importPublicKey({ armoredKey: ValidPublicKey }); const contactModel = await getContactPublicKeyModel({ ...publicKeyConfig, apiKeysConfig: { publicKeys: [{ publicKey, armoredKey: '', flags: 1 }], }, pinnedKeysConfig: { pinnedKeys: [publicKey], encryptToPinned: false, encryptToUntrusted: true, isContact: true, }, }); expect(contactModel.encrypt).toBeFalse(); }); it('should determine encryption flag based on `encryptToUntrusted` when only API keys are present', async () => { const publicKey = await CryptoProxy.importPublicKey({ armoredKey: ValidPublicKey }); const contactModel = await getContactPublicKeyModel({ ...publicKeyConfig, apiKeysConfig: { publicKeys: [{ publicKey, armoredKey: '', flags: 1 }], }, pinnedKeysConfig: { pinnedKeys: [], encryptToPinned: false, encryptToUntrusted: true, isContact: true, }, }); expect(contactModel.encrypt).toBeTrue(); }); it('should set the encryption flag when pinned keys are present and `encryptToPinned` is missing', async () => { const publicKey = await CryptoProxy.importPublicKey({ armoredKey: ValidPublicKey }); const contactModel = await getContactPublicKeyModel({ ...publicKeyConfig, apiKeysConfig: { publicKeys: [{ publicKey, armoredKey: '', flags: 1 }], }, pinnedKeysConfig: { pinnedKeys: [publicKey], // encryptToPinned: undefined, encryptToUntrusted: false, isContact: true, }, }); expect(contactModel.encrypt).toBeTrue(); }); it('should not determine encryption flag based on `encryptToUntrusted` if API keys are missing', async () => { const contactModel = await getContactPublicKeyModel({ ...publicKeyConfig, apiKeysConfig: { publicKeys: [], }, pinnedKeysConfig: { pinnedKeys: [], // encryptToPinned: undefined, encryptToUntrusted: true, isContact: true, }, }); expect(contactModel.encrypt).toBeUndefined(); }); it('should not determine encryption flag based on `encryptToUntrusted` for internal users', async () => { const publicKey = await CryptoProxy.importPublicKey({ armoredKey: ValidPublicKey }); const contactModel = await getContactPublicKeyModel({ ...publicKeyConfig, apiKeysConfig: { ...publicKeyConfig, RecipientType: RECIPIENT_TYPES.TYPE_INTERNAL, publicKeys: [{ publicKey, armoredKey: '', flags: 1 }], }, pinnedKeysConfig: { pinnedKeys: [publicKey], // encryptToPinned: undefined, encryptToUntrusted: false, isContact: true, }, }); expect(contactModel.encrypt).toBeTrue(); }); }); describe('sortApiKeys', () => { const generateFakeKey = (fingerprint: string) => ({ getFingerprint() { return fingerprint; }, } as PublicKeyReference); it('sort keys as expected', () => { const fingerprints = [ 'trustedObsoleteNotCompromised', 'notTrustedObsoleteCompromised', 'trustedNotObsoleteNotCompromised', 'notTrustedNotObsoleteCompromised', 'trustedNotObsoleteCompromised', 'trustedObsoleteCompromised', 'notTrustedNotObsoleteNotCompromised', 'notTrustedObsoleteNotCompromised', ]; const sortedKeys = sortApiKeys({ keys: fingerprints.map(generateFakeKey), obsoleteFingerprints: new Set([ 'trustedObsoleteNotCompromised', 'trustedObsoleteCompromised', 'notTrustedObsoleteNotCompromised', 'notTrustedObsoleteCompromised', ]), compromisedFingerprints: new Set([ 'trustedObsoleteCompromised', 'trustedNotObsoleteCompromised', 'notTrustedObsoleteCompromised', 'notTrustedNotObsoleteCompromised', ]), trustedFingerprints: new Set([ 'trustedObsoleteCompromised', 'trustedNotObsoleteCompromised', 'trustedObsoleteNotCompromised', 'trustedNotObsoleteNotCompromised', ]), }); expect(sortedKeys.map((key) => key.getFingerprint())).toEqual([ 'trustedNotObsoleteNotCompromised', 'trustedObsoleteNotCompromised', 'trustedNotObsoleteCompromised', 'trustedObsoleteCompromised', 'notTrustedNotObsoleteNotCompromised', 'notTrustedObsoleteNotCompromised', 'notTrustedNotObsoleteCompromised', 'notTrustedObsoleteCompromised', ]); }); }); describe('sortPinnedKeys', () => { const generateFakeKey = (fingerprint: string) => ({ getFingerprint() { return fingerprint; }, } as PublicKeyReference); it('sort keys as expected', () => { const fingerprints = [ 'cannotEncryptObsoleteNotCompromised', 'canEncryptObsoleteCompromised', 'cannotEncryptNotObsoleteNotCompromised', 'canEncryptNotObsoleteCompromised', 'cannotEncryptNotObsoleteCompromised', 'cannotEncryptObsoleteCompromised', 'canEncryptNotObsoleteNotCompromised', 'canEncryptObsoleteNotCompromised', ]; const sortedKeys = sortPinnedKeys({ keys: fingerprints.map(generateFakeKey), obsoleteFingerprints: new Set([ 'canEncryptObsoleteNotCompromised', 'canEncryptObsoleteCompromised', 'cannotEncryptObsoleteNotCompromised', 'cannotEncryptObsoleteCompromised', ]), compromisedFingerprints: new Set([ 'canEncryptObsoleteCompromised', 'canEncryptNotObsoleteCompromised', 'cannotEncryptObsoleteCompromised', 'cannotEncryptNotObsoleteCompromised', ]), encryptionCapableFingerprints: new Set([ 'canEncryptObsoleteCompromised', 'canEncryptNotObsoleteCompromised', 'canEncryptObsoleteNotCompromised', 'canEncryptNotObsoleteNotCompromised', ]), }); expect(sortedKeys.map((key) => key.getFingerprint())).toEqual([ 'canEncryptNotObsoleteNotCompromised', 'canEncryptObsoleteNotCompromised', 'canEncryptNotObsoleteCompromised', 'canEncryptObsoleteCompromised', 'cannotEncryptNotObsoleteNotCompromised', 'cannotEncryptObsoleteNotCompromised', 'cannotEncryptNotObsoleteCompromised', 'cannotEncryptObsoleteCompromised', ]); }); });
8,875
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/reactivateKeysLegacy.spec.ts
import { DecryptedKey, Address as tsAddress, Key as tsKey, User as tsUser } from '../../lib/interfaces'; import { KeyReactivationRecord, getDecryptedAddressKeysHelper, getDecryptedUserKeysHelper, reactivateKeysProcess, } from '../../lib/keys'; import { getLegacyAddressKey, getUserKey } from './keyDataHelper'; const DEFAULT_KEYPASSWORD = '1'; const getKeyToReactivate = ({ key: { privateKey }, Key }: { key: DecryptedKey; Key: tsKey }) => ({ Key, id: Key.ID, privateKey, }); const getSetup1 = async () => { const keyPassword = DEFAULT_KEYPASSWORD; const oldKeyPassword = 'abc'; const userKeysFull = await Promise.all([ getUserKey('1', keyPassword), getUserKey('2', oldKeyPassword), getUserKey('3', oldKeyPassword), ]); const UserKeys = userKeysFull.map(({ Key }) => Key); const User = { Keys: UserKeys, } as unknown as tsUser; const address1 = '[email protected]'; const address2 = '[email protected]'; const address3 = '[email protected]'; const userKeys = await getDecryptedUserKeysHelper(User, keyPassword); const addressKeys1Full = await Promise.all([ getLegacyAddressKey('a', keyPassword, address1), getLegacyAddressKey('b', oldKeyPassword, address1), ]); const AddressKeys1 = addressKeys1Full.map(({ Key }) => Key); const addressKeys2Full = await Promise.all([ getLegacyAddressKey('a1', keyPassword, address2), getLegacyAddressKey('b1', 'foo', address2), ]); const AddressKeys2 = addressKeys2Full.map(({ Key }) => Key); const addressKeys3Full = await Promise.all([ getLegacyAddressKey('a2', oldKeyPassword, address3), getLegacyAddressKey('b2', oldKeyPassword, address3), getLegacyAddressKey('c2', oldKeyPassword, address3), ]); const AddressKeys3 = addressKeys3Full.map(({ Key }) => Key); const Addresses = [ { ID: 'my-address-1', Email: address1, Keys: AddressKeys1, }, { ID: 'my-address-2', Email: address2, Keys: AddressKeys2, }, { ID: 'my-address-3', Email: address3, Keys: AddressKeys3, }, ] as unknown as tsAddress[]; const keyReactivationRecords: KeyReactivationRecord[] = await Promise.all( [ { user: User, keysToReactivate: [userKeysFull[1]], }, { address: Addresses[0], keysToReactivate: [addressKeys1Full[1]], }, { address: Addresses[1], keysToReactivate: [], }, { address: Addresses[2], keysToReactivate: [addressKeys3Full[0], addressKeys3Full[1], addressKeys3Full[2]], }, ].map(async (r) => { return { ...r, keysToReactivate: r.keysToReactivate.map(getKeyToReactivate), keys: r.address ? await getDecryptedAddressKeysHelper(r.address.Keys, User, userKeys, keyPassword) : userKeys, }; }) ); return { keyPassword, oldKeyPassword, User, Addresses, userKeys, expectedAddressKeysReactivated: [ addressKeys1Full[1].key.privateKey, addressKeys3Full[0].key.privateKey, addressKeys3Full[1].key.privateKey, ], keyReactivationRecords, }; }; describe('reactivate keys', () => { it('reactivate user and address keys in legacy mode', async () => { const { keyPassword, keyReactivationRecords, User, Addresses, userKeys } = await getSetup1(); const onReactivation = jasmine.createSpy('on reactivation'); const api = jasmine.createSpy('api').and.returnValues(Promise.resolve(), Promise.resolve()); await reactivateKeysProcess({ api, user: User, userKeys, addresses: Addresses, keyReactivationRecords, keyPassword, onReactivation, keyTransparencyVerify: async () => {}, }); expect(api.calls.count()).toEqual(5); expect(onReactivation.calls.allArgs()).toEqual([ ['2', 'ok'], ['b', 'ok'], ['a2', 'ok'], ['b2', 'ok'], ['c2', 'ok'], ]); const keyReactivationCall1 = api.calls.argsFor(0)[0]; expect(keyReactivationCall1).toEqual({ url: 'core/v4/keys/2', method: 'put', data: { PrivateKey: jasmine.any(String), SignedKeyList: undefined, }, }); const keyReactivationCall2 = api.calls.argsFor(1)[0]; expect(keyReactivationCall2).toEqual({ url: 'core/v4/keys/b', method: 'put', data: { PrivateKey: jasmine.any(String), SignedKeyList: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }, }); }); });
8,876
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/reactivateKeysV2.spec.ts
import { PrivateKeyReference } from '@proton/crypto'; import { Address, DecryptedKey, Key, User, Address as tsAddress, User as tsUser } from '../../lib/interfaces'; import { getDecryptedAddressKeysHelper, getDecryptedUserKeysHelper, getHasMigratedAddressKey, reactivateKeysProcess, } from '../../lib/keys'; import { KeyReactivationData, KeyReactivationRecord } from '../../lib/keys/reactivation/interface'; import { getAddressKey, getAddressKeyHelper, getLegacyAddressKey, getUserKey } from './keyDataHelper'; const DEFAULT_KEYPASSWORD = '1'; interface FullKey { key: { privateKey: PrivateKeyReference; }; Key: Key; uploadedKey?: boolean; } const getKeyToReactivate = ({ key: { privateKey }, Key, uploadedKey = false }: FullKey) => { if (getHasMigratedAddressKey(Key) && !uploadedKey) { return { Key, id: Key.ID, } as KeyReactivationData; } return { Key, id: Key.ID, privateKey, }; }; type Record = | { address: Address; user?: undefined; keysToReactivate: FullKey[] } | { address?: undefined; user: User; keysToReactivate: FullKey[] }; const getKeyActivationRecords = async ( records: Record[], userKeys: DecryptedKey[], keyPassword: string, User: User ): Promise<KeyReactivationRecord[]> => { return Promise.all( records.map(async (record) => { if (record.user) { return { user: record.user, keysToReactivate: record.keysToReactivate.map(getKeyToReactivate), keys: userKeys, }; } return { address: record.address, keysToReactivate: record.keysToReactivate.map(getKeyToReactivate), keys: record.address ? await getDecryptedAddressKeysHelper(record.address.Keys, User, userKeys, keyPassword) : userKeys, }; }) ); }; const getSetup1 = async () => { const keyPassword = DEFAULT_KEYPASSWORD; const oldKeyPassword = 'abc'; const userKeysFull = await Promise.all([ getUserKey('1', keyPassword), getUserKey('2', oldKeyPassword), getUserKey('3', 'foo'), ]); const UserKeys = userKeysFull.map(({ Key }) => Key); const User = { Keys: UserKeys, } as unknown as tsUser; const address1 = '[email protected]'; const userKeys = await getDecryptedUserKeysHelper(User, keyPassword); const addressKeysFull = await Promise.all([ getAddressKey('a', userKeysFull[0].key.privateKey, address1), getAddressKey('b', userKeysFull[0].key.privateKey, address1), getAddressKey('c', userKeysFull[1].key.privateKey, address1), getAddressKey('d', userKeysFull[1].key.privateKey, address1), getAddressKey('e', userKeysFull[2].key.privateKey, address1), ]); const AddressKeys = addressKeysFull.map(({ Key }) => Key); const Addresses = [ { ID: 'my-address', Email: address1, Keys: AddressKeys, }, ] as unknown as tsAddress[]; const keyReactivationRecords = await getKeyActivationRecords( [ { user: User, keysToReactivate: [userKeysFull[1]], }, { address: Addresses[0], keysToReactivate: [addressKeysFull[2], addressKeysFull[3]], }, ], userKeys, keyPassword, User ); return { keyPassword, oldKeyPassword, User, Addresses, userKeys, expectedUserKeysReactivated: [userKeysFull[1].key.privateKey], expectedAddressKeysReactivated: [addressKeysFull[2].key.privateKey, addressKeysFull[3].key.privateKey], keyReactivationRecords, }; }; const getSetup2 = async () => { const keyPassword = DEFAULT_KEYPASSWORD; const oldKeyPassword = 'abc'; const userKeysFull = await Promise.all([ getUserKey('1', keyPassword), getUserKey('2', oldKeyPassword), getUserKey('3', 'foo'), ]); const UserKeys = userKeysFull.map(({ Key }) => Key); const User = { Keys: UserKeys, } as unknown as tsUser; const address1 = '[email protected]'; const address2 = '[email protected]'; const address3 = '[email protected]'; const userKeys = await getDecryptedUserKeysHelper(User, keyPassword); const addressKeys1Full = await Promise.all([ getAddressKey('a', userKeysFull[0].key.privateKey, address1), getAddressKey('b', userKeysFull[1].key.privateKey, address1), ]); const AddressKeys1 = addressKeys1Full.map(({ Key }) => Key); const addressKeys2Full = await Promise.all([ getAddressKey('a1', userKeysFull[0].key.privateKey, address2), getAddressKey('b1', userKeysFull[2].key.privateKey, address2), getAddressKey('c1', userKeysFull[2].key.privateKey, address2), ]); const AddressKeys2 = addressKeys2Full.map(({ Key }) => Key); const addressKeys3Full = await Promise.all([ getAddressKey('a2', userKeysFull[1].key.privateKey, address3), getAddressKey('b2', userKeysFull[1].key.privateKey, address3), getLegacyAddressKey('c2', oldKeyPassword, address3), ]); const AddressKeys3 = addressKeys3Full.map(({ Key }) => Key); const Addresses = [ { ID: 'my-address-1', Email: address1, Keys: AddressKeys1, }, { ID: 'my-address-2', Email: address2, Keys: AddressKeys2, }, { ID: 'my-address-3', Email: address3, Keys: AddressKeys3, }, ] as unknown as tsAddress[]; const keyReactivationRecords = await getKeyActivationRecords( [ { user: User, keysToReactivate: [userKeysFull[1]], }, { address: Addresses[0], keysToReactivate: [addressKeys1Full[1]], }, { address: Addresses[1], keysToReactivate: [addressKeys2Full[1], { ...addressKeys2Full[2], uploadedKey: true }], }, { address: Addresses[2], keysToReactivate: [addressKeys3Full[0], addressKeys3Full[1], addressKeys3Full[2]], }, ], userKeys, keyPassword, User ); return { keyPassword, oldKeyPassword, User, Addresses, userKeys, expectedAddressKeysReactivated: [ addressKeys1Full[1].key.privateKey, addressKeys3Full[0].key.privateKey, addressKeys3Full[1].key.privateKey, ], keyReactivationRecords, }; }; const getSetup3 = async () => { const keyPassword = DEFAULT_KEYPASSWORD; const oldKeyPassword = '2'; const userKeysFull = await Promise.all([getUserKey('1', keyPassword), getUserKey('2', oldKeyPassword)]); const UserKeys = userKeysFull.map(({ Key }) => Key); const User = { Keys: UserKeys, } as unknown as tsUser; const address1 = '[email protected]'; const userKeys = await getDecryptedUserKeysHelper(User, keyPassword); const addressKeys1Full = await Promise.all([ getAddressKey('a', userKeysFull[0].key.privateKey, address1), getAddressKeyHelper('b', userKeysFull[1].key.privateKey, userKeysFull[1].key.privateKey), ]); const AddressKeys1 = addressKeys1Full.map(({ Key }) => Key); const Addresses = [ { ID: 'my-address-1', Email: address1, Keys: AddressKeys1, }, ] as unknown as tsAddress[]; const keyReactivationRecords = await getKeyActivationRecords( [ { user: User, keysToReactivate: [{ ...userKeysFull[1], uploadedKey: true }], }, { address: Addresses[0], keysToReactivate: [{ ...addressKeys1Full[1], uploadedKey: true }], }, ], userKeys, keyPassword, User ); return { keyPassword, oldKeyPassword, User, Addresses, userKeys, expectedAddressKeysReactivated: [addressKeys1Full[1].key.privateKey], keyReactivationRecords, }; }; describe('reactivate keys', () => { it('reactivate user keys and the connected address keys', async () => { const { keyPassword, keyReactivationRecords, User, Addresses, userKeys, expectedAddressKeysReactivated } = await getSetup1(); const onReactivation = jasmine.createSpy('on reactivation'); const api = jasmine.createSpy('api').and.returnValues(Promise.resolve(), Promise.resolve()); await reactivateKeysProcess({ api, user: User, userKeys, addresses: Addresses, keyReactivationRecords, keyPassword, onReactivation, keyTransparencyVerify: async () => {}, }); expect(api.calls.count()).toEqual(1); expect(onReactivation.calls.count()).toEqual(3); expect(onReactivation.calls.allArgs()).toEqual([ ['2', 'ok'], ['c', 'ok'], ['d', 'ok'], ]); const keyReactivationCall = api.calls.argsFor(0)[0]; expect(keyReactivationCall).toEqual({ url: 'core/v4/keys/user/2', method: 'put', data: jasmine.objectContaining({ PrivateKey: jasmine.any(String), AddressKeyFingerprints: expectedAddressKeysReactivated.map((x) => x.getFingerprint()), SignedKeyLists: { [Addresses[0].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }, }), }); }); it('reactivate user keys and the connected address keys, and legacy address keys', async () => { const { keyPassword, keyReactivationRecords, User, Addresses, userKeys, expectedAddressKeysReactivated } = await getSetup2(); const onReactivation = jasmine.createSpy('on reactivation'); const api = jasmine.createSpy('api').and.returnValues(Promise.resolve(), Promise.resolve()); await reactivateKeysProcess({ api, user: User, userKeys, addresses: Addresses, keyReactivationRecords, keyPassword, onReactivation, keyTransparencyVerify: async () => {}, }); expect(onReactivation.calls.count()).toEqual(7); expect(onReactivation.calls.allArgs()).toEqual([ ['2', 'ok'], ['b', 'ok'], ['a2', 'ok'], ['b2', 'ok'], ['b1', jasmine.any(Error)], ['c1', 'ok'], ['c2', 'ok'], ]); expect(api.calls.count()).toEqual(3); expect(api.calls.argsFor(0)[0]).toEqual({ url: 'core/v4/keys/user/2', method: 'put', data: jasmine.objectContaining({ PrivateKey: jasmine.any(String), AddressKeyFingerprints: expectedAddressKeysReactivated.map((x) => x.getFingerprint()), SignedKeyLists: { [Addresses[0].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, [Addresses[2].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }, }), }); expect(api.calls.argsFor(1)[0]).toEqual({ url: 'core/v4/keys/address/c1', method: 'put', data: { Token: jasmine.any(String), Signature: jasmine.any(String), PrivateKey: jasmine.any(String), SignedKeyList: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }, }); expect(api.calls.argsFor(2)[0]).toEqual({ url: 'core/v4/keys/address/c2', method: 'put', data: { Token: jasmine.any(String), Signature: jasmine.any(String), PrivateKey: jasmine.any(String), SignedKeyList: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }, }); }); it('reactivate user keys and the connected address keys', async () => { const { keyPassword, keyReactivationRecords, User, Addresses, userKeys, expectedAddressKeysReactivated } = await getSetup3(); const onReactivation = jasmine.createSpy('on reactivation'); const api = jasmine.createSpy('api').and.callFake(() => Promise.resolve()); await reactivateKeysProcess({ api, user: User, userKeys, addresses: Addresses, keyReactivationRecords, keyPassword, onReactivation, keyTransparencyVerify: async () => {}, }); expect(onReactivation.calls.count()).toEqual(2); expect(onReactivation.calls.allArgs()).toEqual([ ['2', 'ok'], ['b', 'ok'], ]); expect(api.calls.count()).toEqual(1); expect(api.calls.argsFor(0)[0]).toEqual({ url: 'core/v4/keys/user/2', method: 'put', data: jasmine.objectContaining({ PrivateKey: jasmine.any(String), AddressKeyFingerprints: expectedAddressKeysReactivated.map((x) => x.getFingerprint()), SignedKeyLists: { [Addresses[0].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }, }), }); }); });
8,877
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/reactivatedAddressKeys.spec.ts
import { Address as tsAddress, User as tsUser } from '../../lib/interfaces'; import { getDecryptedAddressKeysHelper, getDecryptedUserKeysHelper } from '../../lib/keys'; import { getAddressReactivationPayload, getReactivatedAddressKeys, getReactivatedAddressesKeys, } from '../../lib/keys/reactivation/reactivateKeyHelper'; import { getAddressKey, getUserKey } from './keyDataHelper'; const DEFAULT_KEYPASSWORD = '1'; const getSetup1 = async () => { const keyPassword = DEFAULT_KEYPASSWORD; const UserKeysFull = await Promise.all([getUserKey('1', keyPassword), getUserKey('2', keyPassword)]); const User = { Keys: UserKeysFull.map(({ Key }) => Key), } as unknown as tsUser; const address1 = '[email protected]'; const userKeys = await getDecryptedUserKeysHelper(User, keyPassword); const addressKeysFull = await Promise.all([ getAddressKey('a', userKeys[0].privateKey, address1), getAddressKey('b', userKeys[0].privateKey, address1), getAddressKey('c', userKeys[1].privateKey, address1), ]); const Address = { ID: 'AddressID', Email: address1, Keys: addressKeysFull.map(({ Key }) => Key), } as unknown as tsAddress; return { User, Address, userKeys, addressKeys: await getDecryptedAddressKeysHelper(Address.Keys, User, userKeys, keyPassword), }; }; const getSetup2 = async () => { const keyPassword = DEFAULT_KEYPASSWORD; const UserKeysFull = await Promise.all([ getUserKey('1', keyPassword), getUserKey('2', keyPassword), getUserKey('3', keyPassword), getUserKey('4', keyPassword), ]); const User = { Keys: UserKeysFull.map(({ Key }) => Key), } as unknown as tsUser; const address1 = '[email protected]'; const userKeys = await getDecryptedUserKeysHelper(User, keyPassword); const AddressKeys1 = await Promise.all([ getAddressKey('1a', userKeys[0].privateKey, address1), getAddressKey('1b', userKeys[0].privateKey, address1), getAddressKey('1c', userKeys[1].privateKey, address1), getAddressKey('1d', userKeys[2].privateKey, address1), ]); const address2 = '[email protected]'; const AddressKeys2 = await Promise.all([ getAddressKey('2a', userKeys[1].privateKey, address2), getAddressKey('2b', userKeys[1].privateKey, address2).then((r) => ({ ...r, Key: { ...r.Key, Flags: 0 } })), getAddressKey('2c', userKeys[2].privateKey, address2), getAddressKey('2d', userKeys[2].privateKey, address2), getAddressKey('2e', userKeys[3].privateKey, address2), ]); const Address1 = { ID: 'AddressID-1', Email: address1, Keys: AddressKeys1.map(({ Key }) => Key), } as unknown as tsAddress; const Address2 = { ID: 'AddressID-2', Email: address2, Keys: AddressKeys2.map(({ Key }) => Key), } as unknown as tsAddress; return { User, Addresses: [Address1, Address2], userKeys, addressKeys1: await getDecryptedAddressKeysHelper(Address1.Keys, User, userKeys, keyPassword), addressKeys2: await getDecryptedAddressKeysHelper(Address2.Keys, User, userKeys, keyPassword), }; }; describe('reactivate address keys', () => { it('should return an empty result', async () => { const { User, Address, userKeys } = await getSetup1(); const result = await getReactivatedAddressKeys({ user: User, address: Address, oldUserKeys: userKeys, newUserKeys: userKeys, keyPassword: '', keyTransparencyVerify: async () => {}, }); expect(result).toEqual({ address: Address, reactivatedKeys: undefined, signedKeyList: undefined, }); }); it('should return keys that got reactivated', async () => { const { User, Address, userKeys } = await getSetup1(); const result = await getReactivatedAddressKeys({ user: User, address: Address, oldUserKeys: [userKeys[0]], newUserKeys: userKeys, keyPassword: '', keyTransparencyVerify: async () => {}, }); expect(result).toEqual( jasmine.objectContaining({ address: Address, reactivatedKeys: jasmine.any(Array), signedKeyList: jasmine.any(Object), }) ); }); it('should get correct payload from keys that got reactivated', async () => { const { User, Address, userKeys, addressKeys } = await getSetup1(); const result = await getReactivatedAddressKeys({ user: User, address: Address, oldUserKeys: [userKeys[0]], newUserKeys: userKeys, keyPassword: '', keyTransparencyVerify: async () => {}, }); const payload = await getAddressReactivationPayload([result]); expect(payload).toEqual( jasmine.objectContaining({ AddressKeyFingerprints: [...[addressKeys[2]].map(({ privateKey }) => privateKey.getFingerprint())], SignedKeyLists: { [Address.ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }, }) ); }); it('should get correct payload from keys that got reactivated on multiple addresses', async () => { const { User, Addresses, userKeys, addressKeys1, addressKeys2 } = await getSetup2(); const result = await getReactivatedAddressesKeys({ user: User, addresses: Addresses, oldUserKeys: [userKeys[0]], newUserKeys: [userKeys[0], userKeys[1]], keyPassword: '', keyTransparencyVerify: async () => {}, }); expect(JSON.parse(result[0].signedKeyList?.Data || '')).toEqual([ { Primary: 1, Flags: 3, Fingerprint: jasmine.any(String), SHA256Fingerprints: jasmine.any(Array) }, { Primary: 0, Flags: 3, Fingerprint: jasmine.any(String), SHA256Fingerprints: jasmine.any(Array) }, { Primary: 0, Flags: 1, Fingerprint: jasmine.any(String), SHA256Fingerprints: jasmine.any(Array), }, ]); expect(JSON.parse(result[1].signedKeyList?.Data || '')).toEqual([ { Primary: 1, Flags: 1, Fingerprint: jasmine.any(String), SHA256Fingerprints: jasmine.any(Array) }, { Primary: 0, Flags: 0, Fingerprint: jasmine.any(String), SHA256Fingerprints: jasmine.any(Array), }, ]); const payload = await getAddressReactivationPayload(result); expect(payload).toEqual( jasmine.objectContaining({ AddressKeyFingerprints: [ ...[addressKeys1[2], addressKeys2[0], addressKeys2[1]].map(({ privateKey }) => privateKey.getFingerprint() ), ], SignedKeyLists: { [Addresses[0].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, [Addresses[1].ID]: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }, }) ); }); });
8,878
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/replaceAddressKeyTokens.ts
import { CryptoProxy } from '@proton/crypto'; import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding'; import { Address as tsAddress, User as tsUser } from '../../lib/interfaces'; import { getDecryptedUserKeysHelper, getReplacedAddressKeyTokens } from '../../lib/keys'; import { getAddressKey, getUserKey } from './keyDataHelper'; const getSetup = async () => { const keyPassword = '1'; const userKeysFull = await Promise.all([ getUserKey('1', keyPassword), getUserKey('2', keyPassword), getUserKey('3', keyPassword), ]); const UserKeys = userKeysFull.map(({ Key }) => Key); const User = { Keys: UserKeys, } as unknown as tsUser; const address1 = '[email protected]'; const address2 = '[email protected]'; const address3 = '[email protected]'; const userKeys = await getDecryptedUserKeysHelper(User, keyPassword); const addressKeysFull = await Promise.all([ getAddressKey('a', userKeysFull[0].key.privateKey, address1), getAddressKey('b', userKeysFull[0].key.privateKey, address1), getAddressKey('c', userKeysFull[1].key.privateKey, address1), getAddressKey('d', userKeysFull[1].key.privateKey, address1), getAddressKey('e', userKeysFull[1].key.privateKey, address1), getAddressKey('f', userKeysFull[2].key.privateKey, address1), ]); const address2KeysFull = await Promise.all([ getAddressKey('g', userKeysFull[0].key.privateKey, address2), getAddressKey('h', userKeysFull[1].key.privateKey, address2), ]); const address3KeysFull = await Promise.all([ getAddressKey('i', userKeysFull[2].key.privateKey, address3), getAddressKey('j', userKeysFull[2].key.privateKey, address3), ]); const Addresses = [ { ID: 'my-address', Email: address1, Keys: addressKeysFull.map(({ Key }) => Key), }, { ID: 'my-address-2', Email: address2, Keys: address2KeysFull.map(({ Key }) => Key), }, { ID: 'my-address-3', Email: address3, Keys: address3KeysFull.map(({ Key }) => Key), }, ] as unknown as tsAddress[]; return { keyPassword, User, Addresses, userKeys, }; }; describe('re-encrypt address keys', () => { it('should get address key tokens and re-encrypt to another user key', async () => { const setup = await getSetup(); const tokens = await getReplacedAddressKeyTokens({ userKeys: setup.userKeys, addresses: setup.Addresses, privateKey: setup.userKeys[0].privateKey, }); const decryptedTokens = await Promise.all( tokens.AddressKeyTokens.map(async (addressKeyToken) => { await CryptoProxy.decryptSessionKey({ binaryMessage: base64StringToUint8Array(addressKeyToken.KeyPacket), decryptionKeys: [setup.userKeys[0].privateKey], }); return true; }) ); expect(decryptedTokens.length).toBe(setup.Addresses.reduce((acc, address) => acc + address.Keys.length, 0)); }); });
8,879
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/resetKeys.spec.ts
import { CryptoProxy } from '@proton/crypto'; import { ENCRYPTION_CONFIGS, ENCRYPTION_TYPES } from '../../lib/constants'; import { Address } from '../../lib/interfaces'; import { getResetAddressesKeysV2 } from '../../lib/keys'; describe('reset keys v2', () => { it('should return an empty result', async () => { const result = await getResetAddressesKeysV2({ addresses: [], passphrase: '', encryptionConfig: ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519], preAuthKTVerify: () => async () => {}, }); expect(result).toEqual({ userKeyPayload: undefined, addressKeysPayload: undefined, onSKLPublishSuccess: undefined, }); }); it('should return reset keys', async () => { const { userKeyPayload, addressKeysPayload } = await getResetAddressesKeysV2({ addresses: [ { ID: '123', Email: '[email protected]', } as unknown as Address, ], passphrase: '123', encryptionConfig: ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519], preAuthKTVerify: () => async () => {}, }); if (!addressKeysPayload?.length) { throw new Error('Missing address keys'); } await Promise.all( [userKeyPayload, ...addressKeysPayload.map(({ PrivateKey }) => PrivateKey)].map(async (armoredKey) => { if (!armoredKey) { throw new Error('Missing key'); } const { keyIsDecrypted } = await CryptoProxy.getKeyInfo({ armoredKey }); if (keyIsDecrypted) { throw new Error('Invalid key'); } }) ); addressKeysPayload.forEach((payload) => { expect(payload).toEqual({ AddressID: jasmine.any(String), PrivateKey: jasmine.any(String), Token: jasmine.any(String), Signature: jasmine.any(String), SignedKeyList: { Data: jasmine.any(String), Signature: jasmine.any(String), }, }); }); }); });
8,880
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/signedKeyList.spec.ts
import { ADDRESS_TYPE } from '@proton/shared/lib/constants'; import { Address } from '@proton/shared/lib/interfaces'; import { getSignedKeyList } from '../../lib/keys'; import { getActiveKeyObject, getActiveKeys } from '../../lib/keys/getActiveKeys'; import { getAddressKey, getAddressKeyForE2EEForwarding, getUserKey } from './keyDataHelper'; describe('active keys', () => { it('should get active keys without a signed key list', async () => { const keyPassword = '123'; const userKey = await getUserKey('123', keyPassword); const addressKeysFull = await Promise.all([ getAddressKey('a', userKey.key.privateKey, '[email protected]'), getAddressKey('b', userKey.key.privateKey, '[email protected]'), getAddressKey('c', userKey.key.privateKey, '[email protected]'), ]); const address = { Email: '[email protected]' } as Address; const addressKeys = addressKeysFull.map(({ Key }) => Key); const decryptedAddressKeys = addressKeysFull.map(({ key }) => key); const activeKeys = await getActiveKeys(address, null, addressKeys, decryptedAddressKeys); expect(activeKeys).toEqual([ { ID: 'a', primary: 1, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'b', primary: 0, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'c', primary: 0, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, ]); }); it('should get active keys with a signed key list', async () => { const keyPassword = '123'; const userKey = await getUserKey('123', keyPassword); const addressKeysFull = await Promise.all([ getAddressKey('a', userKey.key.privateKey, '[email protected]'), getAddressKey('b', userKey.key.privateKey, '[email protected]'), getAddressKey('c', userKey.key.privateKey, '[email protected]'), ]); const addressKeys = addressKeysFull.map(({ Key }) => Key); const decryptedAddressKeys = addressKeysFull.map(({ key }) => key); const signedKeyList = await getSignedKeyList( await Promise.all([ getActiveKeyObject(addressKeysFull[0].key.privateKey, { ID: 'a', flags: 3 }), getActiveKeyObject(addressKeysFull[1].key.privateKey, { ID: 'b', primary: 1, flags: 3 }), getActiveKeyObject(addressKeysFull[2].key.privateKey, { ID: 'c', flags: 2 }), ]), { ID: 'a', Email: '[email protected]', } as unknown as Address, async () => {} ); const address = { Email: '[email protected]' } as Address; const activeKeys = await getActiveKeys(address, signedKeyList, addressKeys, decryptedAddressKeys); expect(activeKeys).toEqual([ { ID: 'a', primary: 0, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'b', primary: 1, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'c', primary: 0, flags: 2, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, ]); }); it('should get active keys with a signed key list for external keys', async () => { const keyPassword = '123'; const userKey = await getUserKey('123', keyPassword); const addressKeysFull = await Promise.all([ getAddressKey('a', userKey.key.privateKey, '[email protected]'), getAddressKey('b', userKey.key.privateKey, '[email protected]'), getAddressKey('c', userKey.key.privateKey, '[email protected]'), ]); const addressKeys = addressKeysFull.map(({ Key }) => Key); const decryptedAddressKeys = addressKeysFull.map(({ key }) => key); const address = { Email: '[email protected]', Type: ADDRESS_TYPE.TYPE_EXTERNAL } as Address; const signedKeyList = await getSignedKeyList( await Promise.all([ getActiveKeyObject(addressKeysFull[0].key.privateKey, { ID: 'a', flags: 7 }), getActiveKeyObject(addressKeysFull[1].key.privateKey, { ID: 'b', primary: 1, flags: 7 }), getActiveKeyObject(addressKeysFull[2].key.privateKey, { ID: 'c', flags: 6 }), ]), address, async () => {} ); const activeKeys = await getActiveKeys(address, signedKeyList, addressKeys, decryptedAddressKeys); expect(activeKeys).toEqual([ { ID: 'a', primary: 0, flags: 7, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'b', primary: 1, flags: 7, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'c', primary: 0, flags: 6, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, ]); }); it('should should fall back to key flags when no signed key list exists', async () => { const keyPassword = '123'; const userKey = await getUserKey('123', keyPassword); const addressKeysFull = await Promise.all([ getAddressKey('a', userKey.key.privateKey, '[email protected]'), getAddressKey('b', userKey.key.privateKey, '[email protected]'), getAddressKey('c', userKey.key.privateKey, '[email protected]'), ]); addressKeysFull[2].Key.Flags = 1; addressKeysFull[0].Key.Primary = 1; addressKeysFull[1].Key.Primary = 0; addressKeysFull[2].Key.Primary = 0; const addressKeys = addressKeysFull.map(({ Key }) => Key); const decryptedAddressKeys = addressKeysFull.map(({ key }) => key); const activeKeys = await getActiveKeys(undefined, undefined, addressKeys, decryptedAddressKeys); expect(activeKeys).toEqual([ { ID: 'a', primary: 1, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'b', primary: 0, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'c', primary: 0, flags: 1, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, ]); }); it('should include forwarding keys', async () => { const keyPassword = '123'; const userKey = await getUserKey('123', keyPassword); const addressKeysFull = await Promise.all([ getAddressKey('a', userKey.key.privateKey, '[email protected]'), getAddressKeyForE2EEForwarding('b', userKey.key.privateKey, '[email protected]'), getAddressKey('c', userKey.key.privateKey, '[email protected]'), ]); const addressKeys = addressKeysFull.map(({ Key }) => Key); const decryptedAddressKeys = addressKeysFull.map(({ key }) => key); const address = { Email: '[email protected]', Type: ADDRESS_TYPE.TYPE_ORIGINAL } as Address; const signedKeyList = await getSignedKeyList( await Promise.all([ getActiveKeyObject(addressKeysFull[0].key.privateKey, { ID: 'a', primary: 1, flags: 3 }), getActiveKeyObject(addressKeysFull[1].key.privateKey, { ID: 'b', flags: 3 }), getActiveKeyObject(addressKeysFull[2].key.privateKey, { ID: 'c', flags: 3 }), ]), address, async () => {} ); // ensure that forwarding keys are not included in the SKL const signedKeys = JSON.parse(signedKeyList.Data); expect(signedKeys.length).toEqual(2); expect(signedKeys[0].Fingerprint).toEqual(addressKeysFull[0].key.privateKey.getFingerprint()); expect(signedKeys[1].Fingerprint).toEqual(addressKeysFull[2].key.privateKey.getFingerprint()); const activeKeys = await getActiveKeys(address, signedKeyList, addressKeys, decryptedAddressKeys); expect(activeKeys).toEqual([ { ID: 'a', primary: 1, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'b', primary: 0, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, { ID: 'c', primary: 0, flags: 3, privateKey: jasmine.any(Object), publicKey: jasmine.any(Object), fingerprint: jasmine.any(String), sha256Fingerprints: jasmine.any(Array), }, ]); }); });
8,881
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/keys/upgradeKeys.spec.ts
import { CryptoProxy, PrivateKeyReference } from '@proton/crypto'; import { Address as tsAddress, User as tsUser } from '../../lib/interfaces'; import { getDecryptedAddressKeysHelper, getDecryptedUserKeysHelper } from '../../lib/keys'; import { upgradeV2KeysHelper } from '../../lib/keys/upgradeKeysV2'; import { Modulus } from '../authentication/login.data'; import { getAddressKey, getUserKey } from './keyDataHelper'; const DEFAULT_EMAIL = '[email protected]'; const DEFAULT_KEYPASSWORD = '1'; const getKey = async (email = DEFAULT_EMAIL, keyPassword = DEFAULT_KEYPASSWORD) => { const privateKey = await CryptoProxy.generateKey({ userIDs: [{ name: email, email }], curve: 'ed25519', }); return { privateKey, privateKeyArmored: await CryptoProxy.exportPrivateKey({ privateKey, passphrase: keyPassword, }), }; }; describe('upgrade keys v2', () => { describe('do v2 upgrade', () => { it('should upgrade v2 keys', async () => { const keyPassword = DEFAULT_KEYPASSWORD; const [userKey1, userKey2] = await Promise.all([ getUserKey('a', keyPassword, 2), getUserKey('b', keyPassword, 2), ]); const User = { Keys: [userKey1.Key, userKey2.Key], } as tsUser; const keys = await Promise.all([ getAddressKey('c', userKey1.key.privateKey, '[email protected]', 2), getAddressKey('d', userKey1.key.privateKey, '[email protected]', 2), getAddressKey('e', userKey2.key.privateKey, '[email protected]', 2), ]); const Addresses = [ { Email: '[email protected]', Keys: [keys[0].Key, keys[1].Key], }, { Email: '[email protected]', Keys: [keys[2].Key], }, ] as tsAddress[]; const api = jasmine.createSpy('api').and.returnValues(Promise.resolve({ Modulus }), Promise.resolve()); const newKeyPassword = await upgradeV2KeysHelper({ user: User, addresses: Addresses, loginPassword: keyPassword, keyPassword, clearKeyPassword: keyPassword, isOnePasswordMode: true, api, preAuthKTVerify: () => async () => {}, keyMigrationKTVerifier: async () => {}, }); if (!newKeyPassword) { throw new Error('Missing new password'); } expect(api.calls.all().length).toBe(2); const newKeysArgs = api.calls.all()[1].args[0]; const decryptedUserKeys = await getDecryptedUserKeysHelper( { ...User, Keys: newKeysArgs.data.UserKeys }, newKeyPassword ); const decryptedAddressesKeys = await getDecryptedAddressKeysHelper( newKeysArgs.data.AddressKeys, User, decryptedUserKeys, '' ); expect(decryptedUserKeys.every((key) => key.privateKey.isPrivate())).toBe(true); expect(decryptedUserKeys.length).toBe(2 as any); expect(decryptedAddressesKeys.every((key) => key.privateKey.isPrivate())).toBe(true); expect(decryptedAddressesKeys.length).toBe(3 as any); expect(newKeysArgs).toEqual({ url: 'core/v4/keys/private/upgrade', method: 'post', data: jasmine.objectContaining({ KeySalt: jasmine.any(String), Auth: jasmine.any(Object), UserKeys: jasmine.any(Array), AddressKeys: jasmine.any(Array), SignedKeyLists: jasmine.any(Object), }), }); expect(newKeyPassword).toEqual(jasmine.any(String)); }); }); describe('do legacy upgrade', () => { it('should upgrade v2 keys', async () => { const keyPassword = DEFAULT_KEYPASSWORD; const [userKey1, userKey2, addressKey1, addressKey2, addressKey3] = await Promise.all([ getKey(), getKey(), getKey(), getKey(), getKey(), ]); const User = { Keys: [ { ID: 'a', PrivateKey: userKey1.privateKeyArmored, Version: 2, }, { ID: 'b', PrivateKey: userKey2.privateKeyArmored, Version: 2, }, ], } as tsUser; const Addresses = [ { Email: '[email protected]', Keys: [ { ID: 'c', PrivateKey: addressKey1.privateKeyArmored, Version: 2, }, { ID: 'd', PrivateKey: addressKey2.privateKeyArmored, Version: 2, }, ], }, { Email: '[email protected]', Keys: [ { ID: 'e', PrivateKey: addressKey3.privateKeyArmored, Version: 2, }, ], }, ] as tsAddress[]; const api = jasmine.createSpy('api').and.returnValues(Promise.resolve({ Modulus }), Promise.resolve()); const newKeyPassword = await upgradeV2KeysHelper({ user: User, addresses: Addresses, loginPassword: keyPassword, keyPassword, clearKeyPassword: keyPassword, isOnePasswordMode: true, api, preAuthKTVerify: () => async () => {}, keyMigrationKTVerifier: async () => {}, }); if (!newKeyPassword) { throw new Error('Missing new password'); } expect(api.calls.all().length).toBe(2); const newKeysArgs = api.calls.all()[1].args[0]; const decryptedKeys: PrivateKeyReference[] = await Promise.all( newKeysArgs.data.Keys.map(({ PrivateKey }: any) => { return CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: newKeyPassword }); }) ); expect(decryptedKeys.every((key) => key.isPrivate())).toBe(true); expect(decryptedKeys.length).toBe(5); expect(newKeysArgs.data.Keys[0].PrivateKey); expect(newKeysArgs).toEqual({ url: 'core/v4/keys/private/upgrade', method: 'post', data: jasmine.objectContaining({ KeySalt: jasmine.any(String), Auth: jasmine.any(Object), Keys: jasmine.any(Array), }), }); expect(newKeyPassword).toEqual(jasmine.any(String)); }); it('should upgrade v2 keys in two password mode', async () => { const keyPassword = DEFAULT_KEYPASSWORD; const [userKey1, userKey2, addressKey1, addressKey2] = await Promise.all([ getKey(), getKey(), getKey(), getKey(), ]); const User = { Keys: [ { ID: 'a', PrivateKey: userKey1.privateKeyArmored, Version: 2, }, { ID: 'b', PrivateKey: userKey2.privateKeyArmored, Version: 2, }, ], } as tsUser; const Addresses = [ { Email: '[email protected]', Keys: [ { ID: 'c', PrivateKey: addressKey1.privateKeyArmored, Version: 2, }, { ID: 'd', PrivateKey: addressKey2.privateKeyArmored, Version: 2, }, ], }, ] as tsAddress[]; const api = jasmine.createSpy('api').and.returnValues(Promise.resolve()); const newKeyPassword = await upgradeV2KeysHelper({ user: User, addresses: Addresses, loginPassword: '123', keyPassword, clearKeyPassword: keyPassword, isOnePasswordMode: false, api, preAuthKTVerify: () => async () => {}, keyMigrationKTVerifier: async () => {}, }); expect(api.calls.all().length).toBe(1); if (!newKeyPassword) { throw new Error('Missing password'); } const newKeysArgs = api.calls.all()[0].args[0]; const decryptedKeys: PrivateKeyReference[] = await Promise.all( newKeysArgs.data.Keys.map(({ PrivateKey }: any) => { return CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: newKeyPassword }); }) ); expect(decryptedKeys.length).toBe(4); expect(decryptedKeys.every((key) => key.isPrivate())).toBe(true); expect(newKeysArgs.data.Keys[0].PrivateKey); expect(newKeysArgs).toEqual({ url: 'core/v4/keys/private/upgrade', method: 'post', data: jasmine.objectContaining({ KeySalt: jasmine.any(String), Keys: jasmine.any(Array), }), }); expect(newKeyPassword).toEqual(jasmine.any(String)); }); it('should upgrade v2 and v3 keys mixed', async () => { const keyPassword = DEFAULT_KEYPASSWORD; const [userKey1, userKey2, addressKey1, addressKey2] = await Promise.all([ getKey(), getKey(), getKey(), getKey(), ]); const User = { Keys: [ { ID: 'a', PrivateKey: userKey1.privateKeyArmored, Version: 3, }, { ID: 'b', PrivateKey: userKey2.privateKeyArmored, Version: 2, }, ], } as tsUser; const Addresses = [ { Email: '[email protected]', Keys: [ { ID: 'c', PrivateKey: addressKey1.privateKeyArmored, Version: 3, }, { ID: 'd', PrivateKey: addressKey2.privateKeyArmored, Version: 2, }, ], }, ] as tsAddress[]; const api = jasmine.createSpy('api').and.returnValues(Promise.resolve()); const newKeyPassword = await upgradeV2KeysHelper({ user: User, addresses: Addresses, loginPassword: '123', keyPassword, clearKeyPassword: keyPassword, isOnePasswordMode: false, api, preAuthKTVerify: () => async () => {}, keyMigrationKTVerifier: async () => {}, }); if (!newKeyPassword) { throw new Error('Missing password'); } expect(api.calls.all().length).toBe(1); const newKeysArgs = api.calls.all()[0].args[0]; const decryptedKeys: PrivateKeyReference[] = await Promise.all( newKeysArgs.data.Keys.map(({ PrivateKey }: any) => { return CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: newKeyPassword }); }) ); expect(decryptedKeys.length).toBe(4); expect(decryptedKeys.every((key) => key.isPrivate())).toBe(true); expect(newKeysArgs.data.Keys[0].PrivateKey); expect(newKeysArgs).toEqual({ url: 'core/v4/keys/private/upgrade', method: 'post', data: jasmine.objectContaining({ KeySalt: jasmine.any(String), Keys: jasmine.any(Array), }), }); expect(newKeyPassword).toEqual(jasmine.any(String)); }); }); describe('do not upgrade', () => { it('should not upgrade if the v2 keys cannot be decrypted', async () => { const email = '[email protected]'; const keyPassword = '1'; const [userKey1, addressKey1, addressKey2] = await Promise.all([ getKey(), getKey(), getKey('[email protected]', '123'), ]); const User = { Keys: [ { ID: 'a', PrivateKey: userKey1.privateKeyArmored, Version: 3, }, ], } as tsUser; const Addresses = [ { Email: email, Keys: [ { ID: 'b', PrivateKey: addressKey1.privateKeyArmored, Version: 3, }, { ID: 'c', PrivateKey: addressKey2.privateKeyArmored, Version: 2, }, ], }, ] as tsAddress[]; const api = jasmine.createSpy('api').and.returnValues(Promise.resolve()); const newKeyPassword = await upgradeV2KeysHelper({ user: User, addresses: Addresses, loginPassword: keyPassword, keyPassword, clearKeyPassword: keyPassword, isOnePasswordMode: false, api, preAuthKTVerify: () => async () => {}, keyMigrationKTVerifier: async () => {}, }); expect(api.calls.all().length).toBe(0); expect(newKeyPassword).toBeUndefined(); }); it('should not upgrade if there are no v2 keys', async () => { const email = '[email protected]'; const keyPassword = '1'; const [userKey1, addressKey1, addressKey2] = await Promise.all([getKey(), getKey(), getKey()]); const User = { Keys: [ { ID: 'a', PrivateKey: userKey1.privateKeyArmored, Version: 3, }, ], } as tsUser; const Addresses = [ { Email: email, Keys: [ { ID: 'c', PrivateKey: addressKey1.privateKeyArmored, Version: 3, }, { ID: 'd', PrivateKey: addressKey2.privateKeyArmored, Version: 3, }, ], }, ] as tsAddress[]; const api = jasmine.createSpy('api').and.returnValues(Promise.resolve({ Modulus }), Promise.resolve()); const newKeyPassword = await upgradeV2KeysHelper({ user: User, addresses: Addresses, loginPassword: keyPassword, keyPassword, clearKeyPassword: keyPassword, isOnePasswordMode: true, api, preAuthKTVerify: () => async () => {}, keyMigrationKTVerifier: async () => {}, }); expect(api.calls.all().length).toBe(0); expect(newKeyPassword).toBeUndefined(); }); }); });
8,882
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mail/autocrypt.spec.ts
import { getParsedAutocryptHeader } from '../../lib/mail/autocrypt'; const validKeyData = { base64: ` xjMEYAffqRYJKwYBBAHaRw8BAQdAFKaMT9wf5w6gMeW6X+6CSKCwTw5ohqESZQXzNfHG+CrN FDxwcm90b25xYUB5YWhvby5jb20+wncEEBYKAB8FAmAH36kGCwkHCAMCBBUICgIDFgIBAhkB AhsDAh4BAAoJEHhS0KVKBiDsdGgBAMzShBIHmMcpfR9wfXQdJZJBsO/3NTqJfpR6lQM7b0Yh AQDmVdb5v9XofabzXILvXFCsY6G8m2enwfCZw00YK/C0Dc44BGAH36kSCisGAQQBl1UBBQEB B0CnB3qq73mdvkEfyixD+hAk3+5vW/Gg5rZaPoV0gixGOwMBCAfCYQQYFggACQUCYAffqQIb DAAKCRB4UtClSgYg7On/AQDAh4kb5SvbWpxvAj2XJjSD3VnoTq4mXiYVX+5porb2XgEAijZr EgjyGGjkRTwRZ7+ufgn+Qfvk/6+uc7/3efwlngA=`, // prettier-ignore uint8array: new Uint8Array([198, 51, 4, 96, 7, 223, 169, 22, 9, 43, 6, 1, 4, 1, 218, 71, 15, 1, 1, 7, 64, 20, 166, 140, 79, 220, 31, 231, 14, 160, 49, 229, 186, 95, 238, 130, 72, 160, 176, 79, 14, 104, 134, 161, 18, 101, 5, 243, 53, 241, 198, 248, 42, 205, 20, 60, 112, 114, 111, 116, 111, 110, 113, 97, 64, 121, 97, 104, 111, 111, 46, 99, 111, 109, 62, 194, 119, 4, 16, 22, 10, 0, 31, 5, 2, 96, 7, 223, 169, 6, 11, 9, 7, 8, 3, 2, 4, 21, 8, 10, 2, 3, 22, 2, 1, 2, 25, 1, 2, 27, 3, 2, 30, 1, 0, 10, 9, 16, 120, 82, 208, 165, 74, 6, 32, 236, 116, 104, 1, 0, 204, 210, 132, 18, 7, 152, 199, 41, 125, 31, 112, 125, 116, 29, 37, 146, 65, 176, 239, 247, 53, 58, 137, 126, 148, 122, 149, 3, 59, 111, 70, 33, 1, 0, 230, 85, 214, 249, 191, 213, 232, 125, 166, 243, 92, 130, 239, 92, 80, 172, 99, 161, 188, 155, 103, 167, 193, 240, 153, 195, 77, 24, 43, 240, 180, 13, 206, 56, 4, 96, 7, 223, 169, 18, 10, 43, 6, 1, 4, 1, 151, 85, 1, 5, 1, 1, 7, 64, 167, 7, 122, 170, 239, 121, 157, 190, 65, 31, 202, 44, 67, 250, 16, 36, 223, 238, 111, 91, 241, 160, 230, 182, 90, 62, 133, 116, 130, 44, 70, 59, 3, 1, 8, 7, 194, 97, 4, 24, 22, 8, 0, 9, 5, 2, 96, 7, 223, 169, 2, 27, 12, 0, 10, 9, 16, 120, 82, 208, 165, 74, 6, 32, 236, 233, 255, 1, 0, 192, 135, 137, 27, 229, 43, 219, 90, 156, 111, 2, 61, 151, 38, 52, 131, 221, 89, 232, 78, 174, 38, 94, 38, 21, 95, 238, 105, 162, 182, 246, 94, 1, 0, 138, 54, 107, 18, 8, 242, 24, 104, 228, 69, 60, 17, 103, 191, 174, 126, 9, 254, 65, 251, 228, 255, 175, 174, 115, 191, 247, 121, 252, 37, 158, 0]), }; describe('autocrypt helper', () => { it('should parse a valid string', () => { const result = `[email protected]; prefer-encrypt=mutual; keydata=${validKeyData.base64}`; expect(getParsedAutocryptHeader(result, '[email protected]')).toEqual({ addr: '[email protected]', 'prefer-encrypt': 'mutual', keydata: validKeyData.uint8array, }); }); it('should parse a valid string with non-critical fields', () => { const result = `[email protected]; _other=test; prefer-encrypt=mutual; keydata=${validKeyData.base64}`; expect(getParsedAutocryptHeader(result, '[email protected]')).toEqual({ addr: '[email protected]', _other: 'test', 'prefer-encrypt': 'mutual', keydata: validKeyData.uint8array, }); }); it('should not parse a valid string that does not contain prefer-encrypt', () => { const result = `[email protected]; keydata=${validKeyData.base64}`; expect(getParsedAutocryptHeader(result, '[email protected]')).toEqual(undefined); }); it('should not parse a valid string that contains an invalid prefer-encrypt', () => { const result = `[email protected]; _other=test; prefer-encrypt=none; keydata=${validKeyData.base64}`; expect(getParsedAutocryptHeader(result, '[email protected]')).toEqual(undefined); }); it('should not parse invalid base64 keydata', () => { const result = `[email protected]; prefer-encrypt=mutual; keydata=a`; expect(getParsedAutocryptHeader(result, '[email protected]')).toEqual(undefined); }); it('should not parse an invalid string that contains critical unknown fields', () => { const result = `[email protected]; other=test; prefer-encrypt=mutual; keydata=${validKeyData.base64}`; expect(getParsedAutocryptHeader(result, '[email protected]')).toEqual(undefined); }); it('should not parse an invalid string that does not contain addr', () => { const result = `other=test; prefer-encrypt=mutual; keydata=${validKeyData.base64}`; expect(getParsedAutocryptHeader(result, '[email protected]')).toEqual(undefined); }); it('should not parse an invalid string', () => { const result = `[email protected]; prefer-encrypt=none; keydata=${validKeyData.base64}`; expect(getParsedAutocryptHeader(result, '[email protected]')).toEqual(undefined); }); it('should not parse an unknown sender', () => { const result = `[email protected]; prefer-encrypt=mutual; keydata=${validKeyData.base64}`; expect(getParsedAutocryptHeader(result, '[email protected]')).toEqual(undefined); }); });
8,883
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mail/encryptionPreferences.spec.ts
import { PublicKeyReference } from '@proton/crypto'; import { PACKAGE_TYPE, SIGN } from '@proton/shared/lib/mail/mailSettings'; import { CONTACT_MIME_TYPES, MIME_TYPES, MIME_TYPES_MORE, PGP_SCHEMES, PGP_SCHEMES_MORE } from '../../lib/constants'; import { KT_VERIFICATION_STATUS, MailSettings, SelfSend } from '../../lib/interfaces'; import extractEncryptionPreferences, { ENCRYPTION_PREFERENCES_ERROR_TYPES } from '../../lib/mail/encryptionPreferences'; const fakeKey1: PublicKeyReference = { getFingerprint() { return 'fakeKey1'; }, getUserIDs: () => ['<[email protected]>'], } as any; const pinnedFakeKey1: PublicKeyReference = { getFingerprint() { return 'fakeKey1'; }, getUserIDs: () => ['<[email protected]>'], } as any; const fakeKey2: PublicKeyReference = { getFingerprint() { return 'fakeKey2'; }, getUserIDs: () => ['<[email protected]>'], } as any; const pinnedFakeKey2: PublicKeyReference = { getFingerprint() { return 'fakeKey2'; }, getUserIDs: () => ['<[email protected]>'], } as any; const fakeKey3: PublicKeyReference = { getFingerprint() { return 'fakeKey3'; }, } as any; const pinnedFakeKey3: PublicKeyReference = { getFingerprint() { return 'fakeKey3'; }, } as any; describe('extractEncryptionPreferences for an internal user', () => { const ktVerificationResult = { status: KT_VERIFICATION_STATUS.VERIFIED_KEYS }; const model = { emailAddress: '[email protected]', publicKeys: { apiKeys: [], pinnedKeys: [] }, scheme: PGP_SCHEMES_MORE.GLOBAL_DEFAULT, mimeType: MIME_TYPES_MORE.AUTOMATIC, isInternalWithDisabledE2EEForMail: false, trustedFingerprints: new Set([]), encryptionCapableFingerprints: new Set([]), obsoleteFingerprints: new Set([]), compromisedFingerprints: new Set([]), isPGPExternal: false, isPGPInternal: true, isPGPExternalWithWKDKeys: false, isPGPExternalWithoutWKDKeys: false, pgpAddressDisabled: false, isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), ktVerificationResult, }; const mailSettings = { Sign: SIGN.ENABLED, PGPScheme: PACKAGE_TYPE.SEND_PGP_MIME, DraftMIMEType: MIME_TYPES.DEFAULT, } as MailSettings; it('should extract the primary API key when the email address does not belong to any contact', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [] as PublicKeyReference[]; const verifyingPinnedKeys = [] as PublicKeyReference[]; const publicKeyModel = { ...model, isContact: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result).toEqual({ encrypt: true, sign: true, mimeType: MIME_TYPES_MORE.AUTOMATIC, scheme: PGP_SCHEMES.PGP_MIME, isInternalWithDisabledE2EEForMail: false, sendKey: fakeKey1, isSendKeyPinned: false, apiKeys, pinnedKeys, verifyingPinnedKeys, isInternal: true, hasApiKeys: true, hasPinnedKeys: false, warnings: [], isContact: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should extract the primary API key when there are no pinned keys', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [] as PublicKeyReference[]; const verifyingPinnedKeys = [] as PublicKeyReference[]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result).toEqual({ encrypt: true, sign: true, mimeType: MIME_TYPES_MORE.AUTOMATIC, scheme: PGP_SCHEMES.PGP_MIME, isInternalWithDisabledE2EEForMail: false, sendKey: fakeKey1, isSendKeyPinned: false, apiKeys, pinnedKeys, verifyingPinnedKeys, isInternal: true, hasApiKeys: true, hasPinnedKeys: false, warnings: [], isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should pick the pinned key (and not the API one)', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [pinnedFakeKey2, pinnedFakeKey1]; const verifyingPinnedKeys = [pinnedFakeKey2]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, trustedFingerprints: new Set(['fakeKey1', 'fakeKey2']), encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result).toEqual({ encrypt: true, sign: true, mimeType: MIME_TYPES_MORE.AUTOMATIC, scheme: PGP_SCHEMES.PGP_MIME, isInternalWithDisabledE2EEForMail: false, sendKey: pinnedFakeKey1, isSendKeyPinned: true, apiKeys, pinnedKeys, verifyingPinnedKeys, isInternal: true, hasApiKeys: true, hasPinnedKeys: true, warnings: [], isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should give a warning for keyid mismatch', () => { const apiKeys = [fakeKey2, fakeKey3]; const pinnedKeys = [pinnedFakeKey2]; const verifyingPinnedKeys = [] as PublicKeyReference[]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, trustedFingerprints: new Set(['fakeKey2']), encryptionCapableFingerprints: new Set(['fakeKey2', 'fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result.warnings?.length).toEqual(1); }); it('should give an error when the API gave emailAddress errors', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [pinnedFakeKey1]; const verifyingPinnedKeys = [pinnedFakeKey1] as PublicKeyReference[]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey2', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey1']), emailAddressErrors: ['Recipient could not be found'], }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR); }); it('should give an error when there are no pinned keys and the primary key is not valid for sending', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys: [], verifyingPinnedKeys: [] }, encryptionCapableFingerprints: new Set(['fakeKey2', 'fakeKey3']), compromisedFingerprints: new Set(['fakeKey1']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_CANNOT_SEND); }); it('should give an error when the preferred pinned key is not valid for sending', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [pinnedFakeKey1]; const verifyingPinnedKeys = [pinnedFakeKey1]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, encryptionCapableFingerprints: new Set(['fakeKey2', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey1']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_CANNOT_SEND); }); it('should give an error when the preferred pinned key is not among the keys returned by the API', () => { const apiKeys = [fakeKey1, fakeKey2]; const pinnedKeys = [pinnedFakeKey3]; const verifyingPinnedKeys = [pinnedFakeKey3]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey2']), trustedFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_NOT_PINNED); }); it('should give an error if the API returned no keys', () => { const apiKeys = [] as PublicKeyReference[]; const pinnedKeys = [pinnedFakeKey1]; const verifyingPinnedKeys = [pinnedFakeKey1]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, trustedFingerprints: new Set(['fakeKey1']), encryptionCapableFingerprints: new Set(['fakeKey1']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.INTERNAL_USER_NO_API_KEY); }); it('should give an error if the API returned no keys valid for sending', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [pinnedFakeKey1]; const verifyingPinnedKeys = [] as PublicKeyReference[]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, trustedFingerprints: new Set(['fakeKey1']), encryptionCapableFingerprints: new Set(['fakeKey3']), obsoleteFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_CANNOT_SEND); }); it('should give an error if there are pinned keys but the contact signature could not be verified', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [pinnedFakeKey1]; const verifyingPinnedKeys = [pinnedFakeKey1]; const publicKeyModel = { ...model, isContactSignatureVerified: false, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey2', 'fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.CONTACT_SIGNATURE_NOT_VERIFIED); }); it('should give an error if key transparency returned an error', () => { const publicKeyModel = { ...model, publicKeys: { apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [] }, emailAddressErrors: ['Key verification error'], }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR); }); it('should give an error if key transparency returned an error, and ignore pinned keys', () => { const pinnedKeys = [pinnedFakeKey2, pinnedFakeKey1]; const verifyingPinnedKeys = [pinnedFakeKey2]; const publicKeyModel = { ...model, publicKeys: { apiKeys: [], pinnedKeys, verifyingPinnedKeys }, trustedFingerprints: new Set(['fakeKey1', 'fakeKey2']), emailAddressErrors: ['Key verification error'], }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR); }); }); const testExtractEncryptionPreferencesWithWKD = (encrypt: boolean) => describe(`extractEncryptionPreferences for an external user with WKD keys (encrypt: ${encrypt})`, () => { const ktVerificationResult = { status: KT_VERIFICATION_STATUS.UNVERIFIED_KEYS }; const model = { encrypt, emailAddress: '[email protected]', publicKeys: { apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [] }, scheme: PGP_SCHEMES.PGP_INLINE, mimeType: MIME_TYPES.PLAINTEXT as CONTACT_MIME_TYPES, isInternalWithDisabledE2EEForMail: false, trustedFingerprints: new Set([]), encryptionCapableFingerprints: new Set([]), obsoleteFingerprints: new Set([]), compromisedFingerprints: new Set([]), isPGPExternal: true, isPGPInternal: false, isPGPExternalWithWKDKeys: true, isPGPExternalWithoutWKDKeys: false, pgpAddressDisabled: false, isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), ktVerificationResult, }; const mailSettings = { Sign: SIGN.DISABLED, PGPScheme: PACKAGE_TYPE.SEND_PGP_MIME, DraftMIMEType: MIME_TYPES.DEFAULT, } as MailSettings; it('should extract the primary API key when the email address does not belong to any contact', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [] as PublicKeyReference[]; const verifyingPinnedKeys = [] as PublicKeyReference[]; const publicKeyModel = { ...model, isContact: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result).toEqual({ encrypt, sign: encrypt, mimeType: MIME_TYPES.PLAINTEXT, scheme: PGP_SCHEMES.PGP_INLINE, isInternalWithDisabledE2EEForMail: false, sendKey: fakeKey1, isSendKeyPinned: false, apiKeys, pinnedKeys, verifyingPinnedKeys, isInternal: false, hasApiKeys: true, hasPinnedKeys: false, warnings: [], isContact: false, isContactSignatureVerified: undefined, emailAddressWarnings: undefined, contactSignatureTimestamp: undefined, ktVerificationResult, }); }); it('should extract the primary API key when there are no pinned keys', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [] as PublicKeyReference[]; const verifyingPinnedKeys = [] as PublicKeyReference[]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result).toEqual({ encrypt, sign: encrypt, mimeType: MIME_TYPES.PLAINTEXT, scheme: PGP_SCHEMES.PGP_INLINE, isInternalWithDisabledE2EEForMail: false, sendKey: fakeKey1, isSendKeyPinned: false, apiKeys, pinnedKeys, verifyingPinnedKeys, isInternal: false, hasApiKeys: true, hasPinnedKeys: false, warnings: [], isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should pick the pinned key (and not the API one)', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [pinnedFakeKey2, pinnedFakeKey1]; const verifyingPinnedKeys = [pinnedFakeKey1]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, trustedFingerprints: new Set(['fakeKey1', 'fakeKey2']), encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result).toEqual({ encrypt, sign: encrypt, mimeType: MIME_TYPES.PLAINTEXT, scheme: PGP_SCHEMES.PGP_INLINE, isInternalWithDisabledE2EEForMail: false, sendKey: pinnedFakeKey1, isSendKeyPinned: true, apiKeys, pinnedKeys, verifyingPinnedKeys, isInternal: false, hasApiKeys: true, hasPinnedKeys: true, warnings: [], isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should give a warning for keyid mismatch', () => { const apiKeys = [fakeKey2, fakeKey3]; const pinnedKeys = [pinnedFakeKey2]; const verifyingPinnedKeys = [pinnedFakeKey2]; const publicKeyModel = { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, trustedFingerprints: new Set(['fakeKey2']), encryptionCapableFingerprints: new Set(['fakeKey2', 'fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result.warnings?.length).toEqual(1); }); it('should give an error when the API gave emailAddress errors', () => { const publicKeyModel = { ...model, publicKeys: { apiKeys: [fakeKey1, fakeKey2, fakeKey3], pinnedKeys: [pinnedFakeKey1], verifyingPinnedKeys: [], }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey2', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey1']), emailAddressErrors: ['Recipient could not be found'], }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR); }); it('should give an error when the preferred pinned key is not valid for sending', () => { const publicKeyModel = { ...model, publicKeys: { apiKeys: [fakeKey1, fakeKey2, fakeKey3], pinnedKeys: [pinnedFakeKey1], verifyingPinnedKeys: [pinnedFakeKey1], }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey2', 'fakeKey3']), obsoleteFingerprints: new Set(['fakeKey1']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_NOT_PINNED); }); it('should give an error when the preferred pinned key is not among the keys returned by the API', () => { const publicKeyModel = { ...model, publicKeys: { apiKeys: [fakeKey1, fakeKey2], pinnedKeys: [pinnedFakeKey3], verifyingPinnedKeys: [pinnedFakeKey3], }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey2', 'fakeKey3']), trustedFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_NOT_PINNED); }); it('should give an error if the API returned no keys valid for sending', () => { const publicKeyModel = { ...model, publicKeys: { apiKeys: [fakeKey1, fakeKey2, fakeKey3], pinnedKeys: [pinnedFakeKey1], verifyingPinnedKeys: [], }, trustedFingerprints: new Set(['fakeKey1']), encryptionCapableFingerprints: new Set(['fakeKey3']), obsoleteFingerprints: new Set(['fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.WKD_USER_NO_VALID_WKD_KEY); }); it('should give an error if there are pinned keys but the contact signature could not be verified', () => { const apiKeys = [fakeKey1, fakeKey2, fakeKey3]; const pinnedKeys = [pinnedFakeKey1]; const verifyingPinnedKeys = [pinnedFakeKey1]; const publicKeyModel = { ...model, isContactSignatureVerified: false, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey2', 'fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.CONTACT_SIGNATURE_NOT_VERIFIED); }); }); testExtractEncryptionPreferencesWithWKD(true); testExtractEncryptionPreferencesWithWKD(false); describe('extractEncryptionPreferences for an external user without WKD keys', () => { const ktVerificationResult = { status: KT_VERIFICATION_STATUS.UNVERIFIED_KEYS }; const model = { emailAddress: '[email protected]', publicKeys: { apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [] }, encrypt: false, sign: false, scheme: PGP_SCHEMES_MORE.GLOBAL_DEFAULT, mimeType: MIME_TYPES_MORE.AUTOMATIC, isInternalWithDisabledE2EEForMail: false, trustedFingerprints: new Set([]), encryptionCapableFingerprints: new Set([]), obsoleteFingerprints: new Set([]), compromisedFingerprints: new Set([]), isPGPExternal: true, isPGPInternal: false, isPGPExternalWithWKDKeys: false, isPGPExternalWithoutWKDKeys: true, pgpAddressDisabled: false, isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), ktVerificationResult, }; const mailSettings = { Sign: SIGN.ENABLED, PGPScheme: PACKAGE_TYPE.SEND_PGP_MIME, DraftMIMEType: MIME_TYPES.PLAINTEXT, } as MailSettings; it('should take into account the mail Settings', () => { const modelWithoutSign = { ...model, encrypt: undefined, sign: undefined }; const result = extractEncryptionPreferences(modelWithoutSign, mailSettings); expect(result).toEqual({ encrypt: false, sign: true, mimeType: MIME_TYPES_MORE.AUTOMATIC, scheme: PGP_SCHEMES.PGP_MIME, isInternalWithDisabledE2EEForMail: false, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: false, hasApiKeys: false, hasPinnedKeys: false, isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should pick no key when the email address does not belong to any contact', () => { const result = extractEncryptionPreferences( { ...model, isContact: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, }, mailSettings ); expect(result).toEqual({ encrypt: false, sign: false, mimeType: MIME_TYPES_MORE.AUTOMATIC, scheme: PGP_SCHEMES.PGP_MIME, isInternalWithDisabledE2EEForMail: false, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: false, hasApiKeys: false, hasPinnedKeys: false, isContact: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should pick no key when there are no pinned keys', () => { const result = extractEncryptionPreferences(model, mailSettings); expect(result).toEqual({ encrypt: false, sign: false, mimeType: MIME_TYPES_MORE.AUTOMATIC, scheme: PGP_SCHEMES.PGP_MIME, isInternalWithDisabledE2EEForMail: false, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: false, hasApiKeys: false, hasPinnedKeys: false, isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should pick the first pinned key', () => { const apiKeys = [] as PublicKeyReference[]; const pinnedKeys = [pinnedFakeKey2, pinnedFakeKey3]; const verifyingPinnedKeys = [pinnedFakeKey2, pinnedFakeKey3]; const publicKeyModel = { ...model, encrypt: true, sign: true, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, trustedFingerprints: new Set(['fakeKey2', 'fakeKey3']), encryptionCapableFingerprints: new Set(['fakeKey2', 'fakeKey3']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result).toEqual({ encrypt: true, sign: true, mimeType: MIME_TYPES_MORE.AUTOMATIC, scheme: PGP_SCHEMES.PGP_MIME, isInternalWithDisabledE2EEForMail: false, sendKey: pinnedFakeKey2, isSendKeyPinned: true, apiKeys, pinnedKeys, verifyingPinnedKeys, isInternal: false, hasApiKeys: false, hasPinnedKeys: true, warnings: [], isContact: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(0), emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should give a warning for keyid mismatch', () => { const publicKeyModel = { ...model, encrypt: true, sign: true, publicKeys: { apiKeys: [], pinnedKeys: [pinnedFakeKey1], verifyingPinnedKeys: [] }, trustedFingerprints: new Set(['fakeKey1']), encryptionCapableFingerprints: new Set(['fakeKey1']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result.warnings?.length).toEqual(1); }); it('should give an error when the preferred pinned key is not valid for sending', () => { const publicKeyModel = { ...model, encrypt: true, sign: true, publicKeys: { apiKeys: [], pinnedKeys: [pinnedFakeKey2, pinnedFakeKey1], verifyingPinnedKeys: [pinnedFakeKey1], }, encryptionCapableFingerprints: new Set([]), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.EXTERNAL_USER_NO_VALID_PINNED_KEY); }); it('should give an error if there are pinned keys but the contact signature could not be verified', () => { const publicKeyModel = { ...model, isContactSignatureVerified: false, publicKeys: { apiKeys: [], pinnedKeys: [pinnedFakeKey2, pinnedFakeKey1], verifyingPinnedKeys: [pinnedFakeKey2], }, encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey2']), }; const result = extractEncryptionPreferences(publicKeyModel, mailSettings); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.CONTACT_SIGNATURE_NOT_VERIFIED); }); }); describe('extractEncryptionPreferences for an own address', () => { const apiKeys = [fakeKey1, fakeKey2]; const pinnedKeys = [] as PublicKeyReference[]; const verifyingPinnedKeys = [] as PublicKeyReference[]; const ktVerificationResult = { status: KT_VERIFICATION_STATUS.VERIFIED_KEYS }; const model = { emailAddress: '[email protected]', publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, mimeType: MIME_TYPES_MORE.AUTOMATIC, scheme: PGP_SCHEMES_MORE.GLOBAL_DEFAULT, isInternalWithDisabledE2EEForMail: false, trustedFingerprints: new Set([]), encryptionCapableFingerprints: new Set(['fakeKey1', 'fakeKey2']), obsoleteFingerprints: new Set([]), compromisedFingerprints: new Set([]), isPGPExternal: false, isPGPInternal: true, isPGPExternalWithWKDKeys: false, isPGPExternalWithoutWKDKeys: false, pgpAddressDisabled: false, isContact: false, emailAddressWarnings: undefined, ktVerificationResult, }; const mailSettings = { Sign: SIGN.ENABLED, PGPScheme: PACKAGE_TYPE.SEND_PGP_MIME, DraftMIMEType: MIME_TYPES.PLAINTEXT, } as MailSettings; it('should not pick the public key from the keys in selfSend.address', () => { const selfSend: SelfSend = { address: { HasKeys: 1, Receive: 1, }, publicKey: pinnedFakeKey1, canSend: true, } as any; const result = extractEncryptionPreferences(model, mailSettings, selfSend); expect(result).toEqual({ encrypt: true, sign: true, mimeType: MIME_TYPES_MORE.AUTOMATIC, scheme: PGP_SCHEMES.PGP_MIME, isInternalWithDisabledE2EEForMail: false, sendKey: pinnedFakeKey1, isSendKeyPinned: false, apiKeys, pinnedKeys, verifyingPinnedKeys, isInternal: true, hasApiKeys: true, hasPinnedKeys: false, warnings: [], isContact: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, emailAddressWarnings: undefined, ktVerificationResult, }); }); it('should give a warning for keyid mismatch', () => { const selfSend: SelfSend = { address: { HasKeys: 1, Receive: 1, }, publicKey: pinnedFakeKey2, canSend: true, } as any; const result = extractEncryptionPreferences(model, mailSettings, selfSend); expect(result.warnings?.length).toEqual(1); }); it('should give an error when the address is disabled', () => { const selfSend: SelfSend = { address: { HasKeys: 1, Receive: 0, }, publicKey: pinnedFakeKey1, canSend: true, } as any; const result = extractEncryptionPreferences(model, mailSettings, selfSend); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.INTERNAL_USER_DISABLED); }); it('should give an error when the API returned no keys for the address', () => { const selfSend: SelfSend = { address: { HasKeys: 0, Receive: 1, }, publicKey: pinnedFakeKey1, canSend: true, } as any; const result = extractEncryptionPreferences(model, mailSettings, selfSend); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.INTERNAL_USER_NO_API_KEY); }); it('should give an error if the primary key is compromised', () => { const selfSend: SelfSend = { address: { HasKeys: 0, Receive: 1, }, publicKey: pinnedFakeKey1, canSend: false, } as any; const result = extractEncryptionPreferences(model, mailSettings, selfSend); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.INTERNAL_USER_NO_API_KEY); }); it('should give an error when no public key (from the decypted private key) was received', () => { const selfSend: SelfSend = { address: { HasKeys: 1, Receive: 1, }, } as any; const result = extractEncryptionPreferences(model, mailSettings, selfSend); expect(result?.error?.type).toEqual(ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_CANNOT_SEND); }); });
8,884
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mail/helpers.spec.ts
import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants'; import { clearFlag, hasFlag, setFlag, toggleFlag } from '@proton/shared/lib/mail/messages'; describe('hasFlag', () => { it('should detect correctly that the message has a flag', () => { const message = { Flags: MESSAGE_FLAGS.FLAG_SENT, } as Partial<Message>; expect(hasFlag(MESSAGE_FLAGS.FLAG_SENT)(message)).toBeTrue(); }); it('should detect correctly that the message has not a flag', () => { const message = { Flags: MESSAGE_FLAGS.FLAG_RECEIVED, } as Partial<Message>; expect(hasFlag(MESSAGE_FLAGS.FLAG_SENT)(message)).toBeFalsy(); }); }); describe('setFlag', () => { it('should set the message Flag', () => { const message = { Flags: MESSAGE_FLAGS.FLAG_SENT, } as Partial<Message>; const newFlags = setFlag(MESSAGE_FLAGS.FLAG_RECEIPT_SENT)(message); expect(newFlags).toEqual(MESSAGE_FLAGS.FLAG_SENT + MESSAGE_FLAGS.FLAG_RECEIPT_SENT); }); }); describe('clearFlag', () => { it('should clear the message flag', () => { const message = { Flags: MESSAGE_FLAGS.FLAG_SENT + MESSAGE_FLAGS.FLAG_RECEIPT_SENT, } as Partial<Message>; const newFlags = clearFlag(MESSAGE_FLAGS.FLAG_RECEIPT_SENT)(message); expect(newFlags).toEqual(MESSAGE_FLAGS.FLAG_SENT); }); }); describe('toggleFlag', () => { it('should clear the message flag', () => { const message = { Flags: MESSAGE_FLAGS.FLAG_SENT + MESSAGE_FLAGS.FLAG_RECEIPT_SENT, } as Partial<Message>; const newFlags = toggleFlag(MESSAGE_FLAGS.FLAG_RECEIPT_SENT)(message); expect(newFlags).toEqual(MESSAGE_FLAGS.FLAG_SENT); }); });
8,885
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mail/legacyMigration.data.ts
export const testPrivateKeyLegacy = `-----BEGIN PGP PRIVATE KEY BLOCK----- Version: OpenPGP.js v0.9.0 Comment: http://openpgpjs.org xcMGBFSjdRkBB/9slBPGNrHAMbYT71AnxF4a0W/fcrzCP27yd1nte+iUKGyh yux3xGQRIHrwB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eQQyPA0yuoRDwpaeTiaBYOSa06YYuK5Agr0buQAxRIMCxI2o+fucjoabv FsQHKGu20U5GlJroSIyIVVkaH3evhNti/AnYX1HuokcGEQNsF5vo4SjWcH23 2P86EIV+w5lUWC1FN9vZCyvbvyuqLHQMtqKVn4GBOkIc3bYQ0jru3a0FG4Cx bNJ0ASps2+p3Vxe0d+so2iFV92ByQ+0skyCUwCNUlwOV5V5f2fy1ImXk4mXI cO/bcbqRxx3pG9gkPIh43FoQktTT+tsJ5vS53qfaLGdhCYfkrWjsKu+2P9Xg +Cr8clh6NTblhfkoAS1gzjA3XgsgEFrtP+OGqwg= =c5WU -----END PGP MESSAGE----- ---END ENCRYPTED RANDOM KEY--- `; export const testMessageContentLegacy = '<div>flkasjfkjasdklfjasd<br></div><div>fasd<br></div><div>jfasjdfjasd<br></div><div>fj<br></div><div>asdfj<br></div><div>sadjf<br></div><div>sadjf<br></div><div>asjdf<br></div><div>jasd<br></div><div>fj<br></div><div>asdjf<br></div><div>asdjfsad<br></div><div>fasdlkfjasdjfkljsadfljsdfjsdljflkdsjfkljsdlkfjsdlk<br></div><div>jasfd<br></div><div>jsd<br></div><div>jf<br></div><div>sdjfjsdf<br></div><div><br></div><div>djfskjsladf<br></div><div>asd<br></div><div>fja<br></div><div>sdjfajsf<br></div><div>jas<br></div><div>fas<br></div><div>fj<br></div><div>afj<br></div><div>ajf<br></div><div>af<br></div><div>asdfasdfasd<br></div><div>Sent from <a href="https://protonmail.ch">ProtonMail</a>, encrypted email based in Switzerland.<br></div><div>dshfljsadfasdf<br></div><div>as<br></div><div>df<br></div><div>asd<br></div><div>fasd<br></div><div>f<br></div><div>asd<br></div><div>fasdflasdklfjsadlkjf</div><div>asd<br></div><div>fasdlkfjasdlkfjklasdjflkasjdflaslkfasdfjlasjflkasflksdjflkjasdf<br></div><div>asdflkasdjflajsfljaslkflasf<br></div><div>asdfkas<br></div><div>dfjas<br></div><div>djf<br></div><div>asjf<br></div><div>asj<br></div><div>faj<br></div><div>f<br></div><div>afj<br></div><div>sdjaf<br></div><div>jas<br></div><div>sdfj<br></div><div>ajf<br></div><div>aj<br></div><div>ajsdafafdaaf<br></div><div>a<br></div><div>f<br></div><div>lasl;ga<br></div><div>sags<br></div><div>ad<br></div><div>gags<br></div><div>g<br></div><div>ga<br></div><div>a<br></div><div>gg<br></div><div>a<br></div><div>ag<br></div><div>ag<br></div><div>agga.g.ga,ag.ag./ga<br></div><div><br></div><div>dsga<br></div><div>sg<br></div><div><br></div><div>gasga\\g\\g\\g\\g\\g\\n\\y\\t\\r\\\\r\\r\\\\n\\n\\n\\<br></div><div><br></div><div><br></div><div>sd<br></div><div>asdf<br></div><div>asdf<br></div><div>dsa<br></div><div>fasd<br></div><div>f</div>';
8,886
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mail/legacyMigration.spec.ts
import { CryptoProxy } from '@proton/crypto'; import { Api } from '@proton/shared/lib/interfaces'; import { migrateSingle } from '@proton/shared/lib/mail/legacyMessagesMigration/helpers'; import { testMessageContentLegacy, testMessageEncryptedLegacy, testPrivateKeyLegacy } from './legacyMigration.data'; describe('legacy message migration helpers', () => { it('should re-encrypt a legacy message', async () => { const messageID = 'testID'; const decryptionKey = await CryptoProxy.importPrivateKey({ armoredKey: testPrivateKeyLegacy, passphrase: '123', }); const primaryKey = await CryptoProxy.generateKey({ userIDs: { email: '[email protected]' } }); let wasMigrated = false; let validReEncryption = false; let wasMarkedBroken = false; const mockApi = async ({ url, data }: { url: string; data: any }) => { if (url.endsWith(`messages/${messageID}`)) { const Message = { Body: testMessageEncryptedLegacy, Time: 1420070400000, ID: messageID, AddressID: 'keyID', }; return { Message }; } if (url.endsWith(`messages/${messageID}/body`)) { wasMigrated = true; const { Body: reEncryptedBody } = data; // we should be able to decrypt the migrated message const { data: decryptedData, signatures } = await CryptoProxy.decryptMessage({ armoredMessage: reEncryptedBody, decryptionKeys: primaryKey, }); validReEncryption = decryptedData === testMessageContentLegacy && !signatures.length; } if (url.endsWith(`messages/${messageID}/mark/broken`)) { wasMarkedBroken = true; } }; await migrateSingle({ id: messageID, statusMap: {}, api: mockApi as Api, getAddressKeys: async () => [ { ID: 'keyID', privateKey: decryptionKey, publicKey: primaryKey, Flags: 3, Primary: 1, }, ], }); expect(wasMigrated).toBe(true); expect(validReEncryption).toBe(true); expect(wasMarkedBroken).toBe(false); }); it('should mark an undecryptable message as broken', async () => { const messageID = 'testID'; const decryptionKey = await CryptoProxy.importPrivateKey({ armoredKey: testPrivateKeyLegacy, passphrase: '123', }); let wasMigrated = false; let wasMarkedBroken = false; const mockApi = async ({ url }: { url: string; data: any }) => { if (url.endsWith(`messages/${messageID}`)) { const Message = { Body: '---BEGIN INVALID MESSAGE---', Time: 1420070400000, ID: messageID, AddressID: 'keyID', }; return { Message }; } if (url.endsWith(`messages/${messageID}/body`)) { wasMigrated = true; } if (url.endsWith(`messages/${messageID}/mark/broken`)) { wasMarkedBroken = true; } }; await migrateSingle({ id: messageID, statusMap: {}, api: mockApi as Api, getAddressKeys: async () => [ { ID: 'keyID', privateKey: decryptionKey, publicKey: decryptionKey, Flags: 3, Primary: 1, }, ], }); expect(wasMigrated).toBe(false); expect(wasMarkedBroken).toBe(true); }); });
8,887
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mail/message.spec.ts
import { Message } from '../../lib/interfaces/mail/Message'; import { isBounced } from '../../lib/mail/messages'; describe('isBounced helper', () => { const generateMessage = (sender: string, subject: string) => ({ Sender: { Name: 'dummy', Address: sender }, Subject: subject } as Message); it('should return true for the typical bounced message by Proton', () => { expect( isBounced(generateMessage('[email protected]', 'Undelivered Mail Returned to Sender')) ).toEqual(true); }); it('should be robust with respect to changes in the email sender and subject', () => { expect(isBounced(generateMessage('[email protected]', 'Delivery Status Notification (Failure)'))).toEqual( true ); }); it('should return false if the sender is not mailer-daemon', () => { expect(isBounced(generateMessage('[email protected]', 'Undelivered Mail Returned to Sender'))).toEqual(false); }); it('should return false if the subject is not about an undelivered message', () => { expect(isBounced(generateMessage('[email protected]', 'Do you like fishing?'))).toEqual(false); }); });
8,888
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mail/recipients.spec.ts
import { Recipient } from '@proton/shared/lib/interfaces'; import { clearValue, findRecipientsWithSpaceSeparator, inputToRecipient, recipientToInput, splitBySeparator, } from '@proton/shared/lib/mail/recipient'; const address1 = '[email protected]'; const address2 = '[email protected]'; const addessName = 'Address'; describe('splitBySeparator', () => { it('should omit separators present at the beginning and the end', () => { const input = ',[email protected], [email protected]; [email protected],'; const result = splitBySeparator(input); expect(result).toEqual(['[email protected]', '[email protected]', '[email protected]']); }); it('should omit empty values', () => { const input = '[email protected], [email protected], [email protected],,'; const result = splitBySeparator(input); expect(result).toEqual(['[email protected]', '[email protected]', '[email protected]']); }); }); describe('clearValue', () => { it('should trim the value', () => { const input = ' [email protected] '; const result = clearValue(input); expect(result).toEqual('[email protected]'); }); it('should remove surrounding chevrons', () => { const input = '<[email protected]>'; const result = clearValue(input); expect(result).toEqual('[email protected]'); }); it('should keep chevrons when needed', () => { const input = 'Panda <[email protected]>'; const result = clearValue(input); expect(result).toEqual('Panda <[email protected]>'); }); }); describe('inputToRecipient', () => { it('should return a recipient with the email as the name and address if the input is an email', () => { const input = '[email protected]'; const result = inputToRecipient(input); expect(result).toEqual({ Name: input, Address: input }); }); it('should extract the email address surrounded by brackets', () => { const input = '<[email protected]>'; const result = inputToRecipient(input); expect(result).toEqual({ Name: '', Address: '[email protected]' }); }); it('should extract name and email address', () => { const input = 'Panda <[email protected]>'; const result = inputToRecipient(input); expect(result).toEqual({ Name: 'Panda', Address: '[email protected]' }); }); }); describe('findRecipientsWithSpaceSeparator', () => { it('should detect recipients with space separator', () => { const input = `${address1} ${address2}`; const result = findRecipientsWithSpaceSeparator(input); expect(result).toEqual([address1, address2]); }); it('should not split recipients from space separator when separator is a coma', () => { const input1 = `${address1}, ${address2}`; const input2 = `Address1 <${address1}>, Address2 <${address2}></address2>`; expect(findRecipientsWithSpaceSeparator(input1)).toEqual([]); expect(findRecipientsWithSpaceSeparator(input2)).toEqual([]); }); it('should not split recipients when input does not contain a space', () => { expect(findRecipientsWithSpaceSeparator(address1)).toEqual([]); }); }); describe('recipientToInput', () => { it('should return the expected input', () => { const recipient1 = { Name: addessName, Address: address1, } as Recipient; const recipient2 = { Name: address1, Address: address1, } as Recipient; const expected1 = `${addessName} <${address1}>`; const expected2 = address1; expect(recipientToInput(recipient1)).toEqual(expected1); expect(recipientToInput(recipient2)).toEqual(expected2); }); });
8,889
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mail/shortcuts.spec.ts
import { KeyboardKey } from '../../lib/interfaces'; import { isValidShortcut } from '../../lib/shortcuts/helpers'; describe('isValidShortcut - Validate keyboard shortcut', () => { const aKey = { key: KeyboardKey.A, metaKey: false, ctrlKey: false, shiftKey: false, } as KeyboardEvent; const aKeyWithShift = { key: KeyboardKey.A, metaKey: false, ctrlKey: false, shiftKey: true, } as KeyboardEvent; const aKeyWithMeta = { key: KeyboardKey.A, metaKey: true, ctrlKey: true, shiftKey: false, } as KeyboardEvent; it('Should validate a single key shortcut', () => { expect(isValidShortcut([KeyboardKey.A], aKey)).toBe(true); expect(isValidShortcut([KeyboardKey.A], aKeyWithShift)).toBe(false); expect(isValidShortcut([KeyboardKey.A], aKeyWithMeta)).toBe(false); }); it('Should validate combined keys shortcut', () => { expect(isValidShortcut([KeyboardKey.A, 'Shift'], aKeyWithShift)).toBe(true); expect(isValidShortcut([KeyboardKey.A, 'Shift'], aKeyWithMeta)).toBe(false); expect(isValidShortcut([KeyboardKey.A, 'Shift'], aKey)).toBe(false); }); });
8,890
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mail/trackers.spec.ts
import { getUTMTrackersFromURL } from '@proton/shared/lib/mail/trackers'; import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers'; // Complete to verify that links are cleaned as expected const links: { originalLink: string; cleanedLink: string }[] = [ { originalLink: 'https://support.apple.com/fr-fr/HTXXXXXX?cid=email_receipt_itunes_article_HTXXXXXX', cleanedLink: 'https://support.apple.com/fr-fr/HTXXXXXX', }, ]; describe('trackers', () => { describe('getUTMTrackersFromURL', () => { it('should clean utm trackers', () => { const originalURL = 'https://ads.com?utm_source=tracker'; const cleanedURL = 'https://ads.com/'; const expectedUTMTracker: MessageUTMTracker = { originalURL, cleanedURL, removed: [{ key: 'utm_source', value: 'tracker' }], }; const result = getUTMTrackersFromURL(originalURL); expect(result!.url).toEqual(cleanedURL); expect(result!.utmTracker).toEqual(expectedUTMTracker); }); it('should not clean utm trackers', () => { const originalURL = 'https://ads.com?whatever=something'; const result = getUTMTrackersFromURL(originalURL); expect(result!.url).toEqual(originalURL); expect(result!.utmTracker).toEqual(undefined); }); it('should clean all links as expected', () => { links.map((link) => { const result = getUTMTrackersFromURL(link.originalLink); expect(result!.url).toEqual(link.cleanedLink); }); }); it('should return undefined when it throws or URL is not valid', () => { expect(getUTMTrackersFromURL(`<html>dude <a href="dude sd;lkfjads;lkfj !+@#%$^&*()"<html>`)).toBe( undefined ); }); it('should not clean amp links', () => { const originalURL = 'https://something.me/L0/https:%2F%2Fsomething-else.amazonaws.com%randomID'; const result = getUTMTrackersFromURL(originalURL); expect(result!.url).toEqual(originalURL); expect(result!.utmTracker).toEqual(undefined); }); }); });
8,891
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/mnemonic/bip39Wrapper.spec.ts
import { base64StringToUint8Array } from '../../lib/helpers/encoding'; import { generateMnemonicBase64RandomBytes, generateMnemonicFromBase64RandomBytes, mnemonicToBase64RandomBytes, validateMnemonic, } from '../../lib/mnemonic'; describe('generateMnemonicBase64RandomBytes', () => { it('should return base64 string', () => { const base64RandomBytes = generateMnemonicBase64RandomBytes(); expect(() => { base64StringToUint8Array(base64RandomBytes); }).not.toThrow(); }); it('should return base64 string of length 16', () => { const base64RandomBytes = generateMnemonicBase64RandomBytes(); const randomBytes = base64StringToUint8Array(base64RandomBytes); expect(randomBytes.length).toBe(16); }); }); describe('generateMnemonicFromBase64RandomBytes', () => { it('should generate mnemonic', async () => { const base64RandomBytes = 'yNbY5xQk5N8ROW0Ci7Yg4g=='; const result = await generateMnemonicFromBase64RandomBytes(base64RandomBytes); expect(result).toBe('silver replace degree choose exact hurdle eager color action frozen market series'); }); }); describe('mnemonicToBase64RandomBytes', () => { it('should recover base 64 random bytes from mnemonic', async () => { const mnemonic = 'frozen craft abuse human property drama dutch frame carpet giant orange aim'; const result = await mnemonicToBase64RandomBytes(mnemonic); expect(result).toBe('XaZABLdqxoRRGuQizDZvAg=='); }); }); describe('validateMnemonic', () => { it('should return false for an invalid mnemonic', async () => { const invaldMnemonic = 'this is definitely an invalid mnemonic'; const result = await validateMnemonic(invaldMnemonic); expect(result).toBeFalse(); }); it('should return true for a valid mnemonic', async () => { const validMnemonic = 'frozen craft abuse human property drama dutch frame carpet giant orange aim'; const result = await validateMnemonic(validMnemonic); expect(result).toBeTrue(); }); });
8,892
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/recoveryFile/recoveryFile.spec.ts
import { KeyWithRecoverySecret } from '@proton/shared/lib/interfaces'; import { parseRecoveryFiles } from '../../lib/recoveryFile/recoveryFile'; describe('recoveryFile', () => { describe('parseRecoveryFiles', () => { it('returns empty array if no keys can be decrypted', async () => { const recoveryFiles = ['invalid recovery file']; const recoverySecrets: KeyWithRecoverySecret[] = [ { ID: '1', Primary: 1, Active: 1, Fingerprint: 'Fingerprint', Fingerprints: [], PublicKey: 'PublicKey', Version: 1, PrivateKey: 'PrivateKey', Signature: 'Signature', RecoverySecret: 'RecoverySecret', RecoverySecretSignature: 'RecoverySecretSignature', }, ]; const result = await parseRecoveryFiles(recoveryFiles, recoverySecrets); expect(result).toEqual([]); }); it('decrypts keys from recovery file using the recovery secrets', async () => { const recoveryFiles = [ '-----BEGIN PGP MESSAGE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwy4ECQMIdx7exdMdvOtgIXzvh1XfBSpFUuAMaj5OoQCmIJKYya6CF7SVMu4s\r\ntLL90sF6ARi45hSfd5ZNgNH4YK9AYFc06fE95mBnB7/IzVfgJTZFTIgPTRl+\r\nlBeMKit7iz8iygI1BGlCLb6ZyP2KS29/P8NN5BWaSgB/1OVNTNMn9QblRyfB\r\n9ckoN4Co92NjNKwSwBicCwoahhLQACcDYfeFsuXleGW3rV4fVYINWKdYRJKO\r\njMk/6PMc2cRmfSApicSqvq6LPtrLfT6aV9M1/M3xgQAMRdU+KWTPtHNG/hXA\r\nKZPz1rTWQHxjA1jgl8hsihhILmoIHf0en3EkbQZSDLGU36ov4qQGEo6Wnrxr\r\n2uZxXOVtYKRPHb0qDLlIGU4qBKjfAnQwUHAL8Q1SQklZenw4eheP7bGuosvr\r\n2Nd5cD7G3c1m+NCSF2+XS8FWleTxcmd40ggl4l61qJ+Qz/U+gr6lr1O9rzRz\r\n2cJSOC2dy/NYRWKB8UVhaI3hhxnQhUvzUOj0PpkwmCmSzGOJkDrOiDtYmHZr\r\nt0YOR0dFjKqNAz6RIc6MQLKp9j+d7Dhe8cII/dxVNUmW+Vh6cqE2XhsgbIYu\r\nDgziI1j8CLV3KJJfjlgws0aQsNKGHb3WsNbQkllhind7AKLxBVel6ZJ2uy2N\r\nKynBQ63jLe8fu1GUbeoyKTZ3aPTVCdeY8aSBG8TLtXZ2U28udIaeKVQisp2x\r\nfkwl6k8jHdRBG9a0rrAobzEeEWAanjytqt8BnmDkDJYFcnrmASc7cDp4VFcn\r\nJLGF8aUuZ5LVD+yPzg9VqzhHRzqxsVvBnqJGd/qDzeWXVejG\r\n=51yq\r\n-----END PGP MESSAGE-----', ]; const recoverySecrets: KeyWithRecoverySecret[] = [ { ID: '38g3A5xjaoqFPg_vup9c1gHiJonqDNSOwOdZPd-Wjp-nzHQV0lXoVdq6GS11-g28B90viPUxMW3nQ9zgk0TzmA==', Primary: 1, Active: 1, Fingerprint: 'b50e775fdd67a73e85b3e8dd10ec81b36975d982', Fingerprints: [], PublicKey: '', Version: 3, PrivateKey: '-----BEGIN PGP PRIVATE KEY BLOCK-----\nVersion: ProtonMail\n\nxYYEYtARORYJKwYBBAHaRw8BAQdAUq67LdtCJ0/BZWiLUQ+yDf4H5d5J11LX\nr0Vo6DmGSq/+CQMIFuUKHWx/RkZg7tTbHb5HD31PLT9+OrKl2wQKPrsSkv54\nya9a1+CWAB+Hn9iu+6HTca3rj3WSqy/gbp5P+JB/TuhHFsangxLfYFqvkyFe\ncc07bm90X2Zvcl9lbWFpbF91c2VAZG9tYWluLnRsZCA8bm90X2Zvcl9lbWFp\nbF91c2VAZG9tYWluLnRsZD7CjwQQFgoAIAUCYtAROQYLCQcIAwIEFQgKAgQW\nAgEAAhkBAhsDAh4BACEJEBDsgbNpddmCFiEEtQ53X91npz6Fs+jdEOyBs2l1\n2YIP8gEAjjFVIlPIl7DYx5iopxTlzZCuYXiPYu6FkJT2lQLNcnYBAM/GEb2v\n2GocnGXvVztd2L9LafKoiZ/NUn2mx3+aqRANx4sEYtARORIKKwYBBAGXVQEF\nAQEHQLdzFWS+gMPQ+Ve7AFsV6h7F8Wp0e8npXTXplioPSWJpAwEIB/4JAwhQ\nIBWPXSobzmD0D6BynuyDvgnKRKNIkcn+877QQ/0KB52TyxYj76bl7bLEqItN\nr5c6z8rBAXu2MIaMO8uzbbIVxyluvwYmHu6x8l7ExSsGwngEGBYIAAkFAmLQ\nETkCGwwAIQkQEOyBs2l12YIWIQS1Dndf3WenPoWz6N0Q7IGzaXXZghH1AP4r\n0h1efEeP3ZoW3WmS7alxTgp0B/baYzYczxRLcZp7nQD7BLERoW7ENaszG6JA\nojZaWBqq3SDwb505wwCxZ/kMnA8=\n=AAX0\n-----END PGP PRIVATE KEY BLOCK-----\n', Signature: '', RecoverySecret: 'P3/THKBFAc8MDJHH635oUnM1it9/A23spz5zRRrT90U=', RecoverySecretSignature: '-----BEGIN PGP SIGNATURE-----\nVersion: ProtonMail\n\nwnUEARYKAAYFAmLRcoMAIQkQEOyBs2l12YIWIQS1Dndf3WenPoWz6N0Q7IGz\naXXZgoYWAQDjLFftBiDKD9x5vPmdWPUdFiQn87YhVyB9CLLpLz5HXgEA8mt2\nnD9+t4gyVjHkFgTpLr89coWRO4MX82m4o23qcwY=\n=wJHG\n-----END PGP SIGNATURE-----\n', }, ]; const result = await parseRecoveryFiles(recoveryFiles, recoverySecrets); expect(result.map((key) => key.fingerprint)).toEqual(['b50e775fdd67a73e85b3e8dd10ec81b36975d982']); }); }); });
8,893
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/sanitize/escape.spec.ts
import { escapeForbiddenStyle, recurringUnescapeCSSEncoding } from '../../lib/sanitize/escape'; describe('Escape', () => { describe('escapeForbiddenStyles', () => { it('Should replace absolute styles by relative', () => { expect(escapeForbiddenStyle('position: absolute')).toBe('position: relative'); }); it('Should replace percentage height by unset', () => { expect(escapeForbiddenStyle('height: 100%; min-height: 30% ; max-height: 50%;')).toBe( 'height: unset; min-height: unset ; max-height: 50%;' ); }); it('Should not replace percent line-height by unset', () => { expect(escapeForbiddenStyle('line-height: 100%;')).toBe('line-height: 100%;'); }); it('Should disable dark styles Color schemes', () => { expect(escapeForbiddenStyle('Color-scheme: light dark;')).toBe('proton-disabled-Color-scheme: light dark;'); }); it('Should disable dark styles media queries', () => { expect(escapeForbiddenStyle('(prefers-color-scheme: dark)')).toBe( '(prefers-proton-disabled-Color-scheme: dark)' ); }); }); describe('recurringUnescapeCSSEncoding', () => { it('should return the expected unescaped CSS string when there is few escapes', () => { const string = `background ur&#x26;#x26;#x26;#x26;#x26;(https://proton.me/image.jpg);`; const expectedString = `background ur&(https://proton.me/image.jpg);`; expect(recurringUnescapeCSSEncoding(string)).toEqual(expectedString); }); it('should return an empty string when trying to unescape CSS a content with too much escapes', () => { const string = `background ur&#x26;#x26;#x26;#x26;#x26;#x26;(https://proton.me/image.jpg);`; const expectedString = ``; expect(recurringUnescapeCSSEncoding(string)).toEqual(expectedString); }); }); });
8,894
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/spotlight/spotlight.spec.ts
import { getEnvironmentDate } from '@proton/shared/lib/spotlight/helpers'; import { SpotlightDate } from '@proton/shared/lib/spotlight/interface'; describe('Spotlight', () => { describe('getEnvironmentDate', () => { const defaultDate = Date.UTC(2022, 1, 1, 12); const betaDate = Date.UTC(2023, 1, 1, 12); const alphaDate = Date.UTC(2024, 1, 1, 12); const dates: SpotlightDate = { default: defaultDate, beta: betaDate, alpha: alphaDate, }; it('should return the expected dates depending on the current environement', () => { expect(getEnvironmentDate(undefined, dates)).toBe(defaultDate); expect(getEnvironmentDate('default', dates)).toBe(defaultDate); expect(getEnvironmentDate('beta', dates)).toBe(betaDate); expect(getEnvironmentDate('alpha', dates)).toBe(alphaDate); }); }); });
8,895
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/subscription/format.spec.ts
import format from '@proton/shared/lib/subscription/format'; describe('Subscription Format', () => { let subscription: any; let upcoming: any; beforeEach(() => { subscription = { ID: 'k2ou1ckjSusQvcOkMvMYo5_9tO93iG-5l0ycRA2wxWXkgR_3uW086eI8xit5qENSOes9nPbjIvUjkn8FdpZPrw==', InvoiceID: 'EodtkjoLzxaZpTfWOMEEsfqQuKftg11lPzfDuMxQFnX2sagjugYRm8AZ7O6N3K9mJdbLN_t0dbEMWuhs-EhSLQ==', Cycle: 1, PeriodStart: 1669038950, PeriodEnd: 1671630950, CreateTime: 1669038951, CouponCode: null, Currency: 'CHF', Amount: 499, Discount: 0, RenewDiscount: 0, RenewAmount: 499, Plans: [ { ID: 'Wb4NAqmiuqoA7kCHE28y92bBFfN8jaYQCLxHRAB96yGj-bh9SxguXC48_WSU-fRUjdAr-lx95c6rFLplgXyXYA==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'mail2022', Title: 'Mail Plus', MaxDomains: 1, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Cycle: 1, Currency: 'CHF', Amount: 499, Quantity: 1, }, ], Renew: 1, }; upcoming = { ID: 'klHlWI9EqPULc0sWO_C36DM8eHJ1H1bzIo4EmX-HG_VbDfS67gMvCt_5mhHFwHh9n02aNoux8qj4bUZOaebRUg==', InvoiceID: 'EodtkjoLzxaZpTfWOMEEsfqQuKftg11lPzfDuMxQFnX2sagjugYRm8AZ7O6N3K9mJdbLN_t0dbEMWuhs-EhSLQ==', Cycle: 12, PeriodStart: 1671630950, PeriodEnd: 1703166950, CreateTime: 1669039317, CouponCode: 'BUNDLE', Currency: 'CHF', Amount: 499, Discount: 0, RenewDiscount: 0, RenewAmount: 4788, Plans: [ { ID: 'Wb4NAqmiuqoA7kCHE28y92bBFfN8jaYQCLxHRAB96yGj-bh9SxguXC48_WSU-fRUjdAr-lx95c6rFLplgXyXYA==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'mail2022', Title: 'Mail Plus', MaxDomains: 1, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Cycle: 12, Currency: 'CHF', Amount: 4788, Quantity: 1, }, ], Renew: 1, }; }); it('should add isManagedByMozilla property', () => { const result = format(subscription); expect(result.isManagedByMozilla).toBeDefined(); }); it('should not add upcoming property if it is not specified', () => { const result = format(subscription); expect(result.UpcomingSubscription).not.toBeDefined(); }); it('should add upcoming property if it is the second parameter', () => { const result = format(subscription, upcoming); expect(result.UpcomingSubscription).toBeDefined(); }); });
8,896
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/subscription/subscriptionModel.spec.ts
import { SubscriptionModel as SubscriptionModelInterface } from '@proton/shared/lib/interfaces'; import { SubscriptionModel, getSubscriptionModel } from '@proton/shared/lib/models/subscriptionModel'; type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]>; } : T; type PartialSubscriptionModel = DeepPartial<SubscriptionModelInterface>; describe('subscriptionModel', () => { describe('getSubscriptionModel()', () => { it('should expect the API response with two top-level properties: Subscription and UpcomingSubscription', async () => { const apiMock = () => Promise.resolve({ Subscription: { ID: 'Subscription1' }, UpcomingSubscription: { ID: 'Subscription2' }, }); const result: PartialSubscriptionModel = await getSubscriptionModel(apiMock); expect(result).toEqual({ ID: 'Subscription1', UpcomingSubscription: { ID: 'Subscription2' }, isManagedByMozilla: false, }); }); it('should handle the case when there is no UpcomingSubscription', async () => { const apiMock = () => Promise.resolve({ Subscription: { ID: 'Subscription1' }, }); const result: PartialSubscriptionModel = await getSubscriptionModel(apiMock); expect(result).toEqual({ ID: 'Subscription1', UpcomingSubscription: undefined, isManagedByMozilla: false, }); }); it('should handle the case when UpcomingSubscription is null', async () => { const apiMock = () => Promise.resolve({ Subscription: { ID: 'Subscription1' }, UpcomingSubscription: null, }); const result: PartialSubscriptionModel = await getSubscriptionModel(apiMock); expect(result).toEqual({ ID: 'Subscription1', UpcomingSubscription: null, isManagedByMozilla: false, }); }); }); describe('SubscriptionModel.update', () => { it('should add the UpcomingSubscription from the events', () => { const model = { ID: 'Subscription1', isManagedByMozilla: false, }; const events = { ID: 'Subscription1', UpcomingSubscription: { ID: 'Subscription2' }, }; const result: PartialSubscriptionModel = SubscriptionModel.update(model, events); expect(result).toEqual({ ID: 'Subscription1', isManagedByMozilla: false, UpcomingSubscription: { ID: 'Subscription2' }, }); }); it('should remove UpcomingSubscription when events does not have it', () => { const model = { ID: 'Subscription1', UpcomingSubscription: { ID: 'Subscription2' }, isManagedByMozilla: false, }; const events = { ID: 'Subscription1', }; const result: PartialSubscriptionModel = SubscriptionModel.update(model, events); expect(result).toEqual({ ID: 'Subscription1', UpcomingSubscription: undefined, isManagedByMozilla: false, }); }); it('should set UpcomingSubscription to null when events set it to null', () => { const model = { ID: 'Subscription1', UpcomingSubscription: { ID: 'Subscription2' }, isManagedByMozilla: false, }; const events = { ID: 'Subscription1', UpcomingSubscription: null, }; const result: PartialSubscriptionModel = SubscriptionModel.update(model, events); expect(result).toEqual({ ID: 'Subscription1', UpcomingSubscription: null, isManagedByMozilla: false, }); }); it('should do nothing if model does not have UpcomingSubscription, nor events', () => { const model = { ID: 'Subscription1', isManagedByMozilla: false, }; const events = { ID: 'Subscription1', }; const result: PartialSubscriptionModel = SubscriptionModel.update(model, events); expect(result).toEqual({ ID: 'Subscription1', UpcomingSubscription: undefined, isManagedByMozilla: false, }); }); }); });
8,897
0
petrpan-code/ProtonMail/WebClients/packages/shared/test
petrpan-code/ProtonMail/WebClients/packages/shared/test/upsell/upsell.spec.ts
import { APPS, APP_UPSELL_REF_PATH, SHARED_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { addUpsellPath, getUpsellRef, getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell'; const feature = SHARED_UPSELL_PATHS.STORAGE; describe('addUpsellPath', () => { it('should add the upsell path to the link', () => { const link = '/myLink'; const upsellPath = 'myUpsellPath'; const expected = `${link}?ref=${upsellPath}`; expect(addUpsellPath(link, upsellPath)).toEqual(expected); }); it('should add the upsell path in a new param to the link', function () { const link = '/myLink?something=1'; const upsellPath = 'myUpsellPath'; const expected = `${link}&ref=${upsellPath}`; expect(addUpsellPath(link, upsellPath)).toEqual(expected); }); it('should not add anything to the link', () => { const link = '/myLink'; expect(addUpsellPath(link, undefined)).toEqual(link); }); }); describe('getUpsellRef', () => { it('should generate expected upsell ref with app and feature', () => { expect(getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, feature })).toEqual( `${APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH}${feature}` ); }); it('should generate expected upsell ref with app, feature and component', () => { expect( getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.BANNER, feature }) ).toEqual(`${APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH}${UPSELL_COMPONENT.BANNER}${feature}`); }); it('should generate expected upsell ref with app, feature and settings', () => { expect(getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, feature, isSettings: true })).toEqual( `${APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH}${feature}_settings` ); }); it('should generate expected upsell ref with app, feature, component and settings', () => { expect( getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.BANNER, feature, isSettings: true, }) ).toEqual(`${APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH}${UPSELL_COMPONENT.BANNER}${feature}_settings`); }); }); describe('getUpsellRefFromApp', () => { it('should generate the expected upsell ref', () => { // Open from mail expect(getUpsellRefFromApp({ app: APPS.PROTONMAIL, feature })).toEqual( `${APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH}${feature}` ); // Open from calendar expect(getUpsellRefFromApp({ app: APPS.PROTONCALENDAR, feature })).toEqual( `${APP_UPSELL_REF_PATH.CALENDAR_UPSELL_REF_PATH}${feature}` ); // Open from drive expect(getUpsellRefFromApp({ app: APPS.PROTONDRIVE, feature })).toEqual( `${APP_UPSELL_REF_PATH.DRIVE_UPSELL_REF_PATH}${feature}` ); // Open from mail settings expect(getUpsellRefFromApp({ app: APPS.PROTONACCOUNT, feature, fromApp: APPS.PROTONMAIL })).toEqual( `${APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH}${feature}_settings` ); // Open from calendar settings expect(getUpsellRefFromApp({ app: APPS.PROTONACCOUNT, feature, fromApp: APPS.PROTONCALENDAR })).toEqual( `${APP_UPSELL_REF_PATH.CALENDAR_UPSELL_REF_PATH}${feature}_settings` ); // Open from drive settings expect(getUpsellRefFromApp({ app: APPS.PROTONACCOUNT, feature, fromApp: APPS.PROTONDRIVE })).toEqual( `${APP_UPSELL_REF_PATH.DRIVE_UPSELL_REF_PATH}${feature}_settings` ); // Open from vpn settings expect(getUpsellRefFromApp({ app: APPS.PROTONACCOUNT, feature, fromApp: APPS.PROTONVPN_SETTINGS })).toEqual( `${APP_UPSELL_REF_PATH.VPN_UPSELL_REF_PATH}${feature}_settings` ); }); });
8,898
0
petrpan-code/ProtonMail/WebClients/packages/shared
petrpan-code/ProtonMail/WebClients/packages/shared/typings/index.d.ts
declare module 'ical.js'; declare module 'pm-srp'; declare module 'is-valid-domain'; declare module '@protontech/mimemessage';
8,899