index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/contacts/VCard.ts | import { PGP_SCHEMES } from '../../constants';
import { MimeTypeVcard } from '../EncryptionPreferences';
export type VCardKey =
| 'fn'
| 'n'
| 'nickname'
| 'email'
| 'tel'
| 'adr'
| 'bday'
| 'anniversary'
| 'gender'
| 'lang'
| 'tz'
| 'geo'
| 'title'
| 'role'
| 'logo'
| 'org'
| 'related'
| 'member'
| 'note'
| 'url';
export type ParamKey =
| 'language'
| 'value'
| 'pref'
| 'altid'
| 'pid'
| 'type'
| 'mediatype'
| 'calscale'
| 'sort-as'
| 'geo'
| 'tz';
export interface VCardProperty<T = any> {
value: T;
params?: Partial<Record<ParamKey, string>>;
group?: string;
/**
* Proton specific: outside of RFC's scope
*/
field: string;
uid: string;
}
export interface VcardNValue {
familyNames: string[];
givenNames: string[];
additionalNames: string[];
honorificPrefixes: string[];
honorificSuffixes: string[];
}
export enum VCardGender {
Male = 'M',
Female = 'F',
Other = 'O',
None = 'N',
Unknown = 'U',
Empty = '',
}
export interface VCardOrg {
organizationalName?: string;
organizationalUnitNames?: string[];
}
export interface VCardGenderValue {
gender: VCardGender;
text?: string;
}
export interface VCardAddress {
postOfficeBox: string;
extendedAddress: string;
streetAddress: string;
locality: string;
region: string;
postalCode: string;
country: string;
}
export type VCardDateOrText =
| {
/**
* Local date
*/
date?: Date;
}
| {
text?: string;
};
interface BaseVCardContact {
fn: VCardProperty<string>[];
n?: VCardProperty<VcardNValue>;
nickname?: VCardProperty<string>[];
photo?: VCardProperty<string>[];
bday?: VCardProperty<VCardDateOrText>;
anniversary?: VCardProperty<VCardDateOrText>;
gender?: VCardProperty<VCardGenderValue>;
adr?: VCardProperty<VCardAddress>[];
tel?: VCardProperty<string>[];
email?: VCardProperty<string>[];
impp?: VCardProperty<string>[];
lang?: VCardProperty<string>[];
tz?: VCardProperty<string>[];
geo?: VCardProperty<string>[];
title?: VCardProperty<string>[];
role?: VCardProperty<string>[];
logo?: VCardProperty<string>[];
org?: VCardProperty<VCardOrg>[];
member?: VCardProperty<string>[];
related?: VCardProperty<string>[];
note?: VCardProperty<string>[];
url?: VCardProperty<string>[];
/**
* Array-valued categories pose problems to ICAL (even though a vcard with CATEGORIES:ONE,TWO
* will be parsed into a value ['ONE', 'TWO'], ICAL.js fails to transform it back).
* So we prefer storing array-valued category as several properties
*/
categories?: VCardProperty<string>[];
key?: VCardProperty<string>[];
version?: VCardProperty<string>;
'x-pm-sign'?: VCardProperty<boolean>[];
'x-pm-scheme'?: VCardProperty<PGP_SCHEMES>[];
'x-pm-mimetype'?: VCardProperty<MimeTypeVcard>[];
}
export type VCardContact = BaseVCardContact &
(
| {
/**
* Encryption flag that applies if 'key' field (i.e. pinned keys) is populated
*/
'x-pm-encrypt'?: VCardProperty<boolean>[];
}
| {
/**
* Encryption flag that applies to (unpinned) keys from e.g. WKD or other untrusted servers
*/
'x-pm-encrypt-untrusted'?: VCardProperty<boolean>[];
}
);
| 8,600 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/contacts/index.ts | export * from './Contact';
export * from './Import';
| 8,601 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/device.ts | export interface DevicePayload {
Device: {
DeviceID: string;
VolumeID: string;
CreateTime: number;
ModifyTime: number;
Type: number;
SyncState: number;
};
Share: {
ShareID: string;
Name: string;
LinkID: string;
};
}
export type DevicesResult = {
Devices: DevicePayload[];
};
export interface CreateDeviceVolume {
Device: {
VolumeID: string;
SyncState: number;
Type: number;
};
Share: {
Name: string;
AddressID: string;
Key: string;
Passphrase: string;
PassphraseSignature: string;
};
Link: {
NodeKey: string;
NodePassphrase: string;
NodePassphraseSignature: string;
NodeHashKey: string;
Name: string;
};
}
| 8,602 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/events.ts | import { EVENT_TYPES } from '../../drive/constants';
import { LinkMeta } from './link';
export interface DriveEventsResult {
Events: DriveEventResult[];
EventID: string;
More: DriveEventsPaginationFlag;
Refresh: 0 | 1;
}
type DriveEventResult = {
Data: any;
Link: LinkMeta;
CreateTime: number;
} & (
| {
EventType: EVENT_TYPES.DELETE;
}
| {
EventType: EVENT_TYPES;
ContextShareID: string;
FromContextShareID?: string;
}
);
enum DriveEventsPaginationFlag {
completed = 0,
hasMore = 1,
}
| 8,603 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/file.ts | export enum FileRevisionState {
Draft = 0,
Active = 1,
Inactive = 2,
}
export interface CreateDriveFile {
Name: string;
Hash: string;
ParentLinkID: string;
NodePassphrase: string;
NodePassphraseSignature: string;
SignatureAddress: string;
NodeKey: string;
MIMEType: string;
ContentKeyPacket: string;
ContentKeyPacketSignature: string;
ClientUID?: string;
}
export interface RevisionManifest {
PreviousRootHash: string;
BlockHashes: {
Hash: string;
Index: number;
}[];
}
export interface UpdateFileRevision {
ManifestSignature: string;
SignatureAddress: string;
XAttr?: string;
Photo?: {
MainPhotoLinkID: string | null;
CaptureTime: number;
Exif?: string;
ContentHash?: string;
};
}
export interface CreateFileResult {
File: {
ID: string;
RevisionID: string;
};
}
export interface CreateFileRevisionResult {
Revision: {
ID: string;
};
}
export interface UploadLink {
Token: string;
BareURL: string;
}
export interface RequestUploadResult {
UploadLinks: UploadLink[];
ThumbnailLinks?: UploadLink[];
}
export interface DriveFileBlock {
Index: number;
EncSignature?: string;
BareURL: string;
Token: string;
Hash: string;
}
export type Thumbnail = { Size: number; Type: number; Hash: string };
export interface DriveFileRevisionPayload {
ID: string;
CreateTime: number;
Size: number;
State: number;
ManifestSignature: string;
SignatureAddress: string;
SignatureEmail: string;
Blocks: DriveFileBlock[];
Thumbnails: Thumbnail[];
XAttr?: string;
}
export interface DriveFileRestoreRevisionResult {
Code: 1000 | 1002; // 1000: restore sync, 1002: restore async
}
export interface DriveFileRevisionsResult {
Revisions: DriveFileRevisionPayload[];
}
export interface DriveFileRevisionResult {
Revision: DriveFileRevisionPayload;
}
export interface DriveFileRevisionThumbnailResult {
ThumbnailBareURL: string;
ThumbnailToken: string;
}
export interface GetVerificationDataResult {
VerificationCode: string;
ContentKeyPacket: string;
}
| 8,604 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/folder.ts | export interface CreateNewFolder {
Name: string;
Hash: string;
ParentLinkID: string;
NodePassphrase: string;
NodePassphraseSignature: string;
SignatureAddress: string;
NodeKey: string;
NodeHashKey: string;
XAttr?: string;
}
| 8,605 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/link.ts | import type { SORT_DIRECTION } from '../../constants';
import type { FileRevisionState } from './file';
import type { Photo } from './photos';
export enum LinkType {
FOLDER = 1,
FILE = 2,
}
export type SharedUrlInfo = {
CreateTime: number;
ExpireTime: number | null;
ShareUrlID: string;
Token: string;
NumAccesses?: number;
};
interface FileProperties {
ContentKeyPacket: string;
ContentKeyPacketSignature: string;
ActiveRevision: {
ID: string;
CreateTime: number;
Size: number;
ManifestSignature: string;
SignatureAddress: string;
State: FileRevisionState;
Thumbnail: number;
ThumbnailURLInfo: {
BareURL: string;
Token: string;
URL: string;
};
Photo: Photo | null;
} | null;
}
interface FolderProperties {
NodeHashKey: string;
}
interface DriveLink {
LinkID: string;
ParentLinkID: string;
Type: LinkType;
Name: string;
NameSignatureEmail: string;
EncryptedName: string;
Size: number;
MIMEType: string;
Hash: string;
CreateTime: number;
// API returns only ModifyTime which represents modification on API, i.e.,
// the time when the last revision was uploaded. The real modification time
// (set by file system) is available in XAttr and these times are properly
// set during decryption of the link.
ModifyTime: number;
RealModifyTime: number;
Trashed: number | null;
State: number;
NodeKey: string;
NodePassphrase: string;
NodePassphraseSignature: string;
SignatureAddress: string;
Attributes: number;
Permissions: number;
FileProperties: FileProperties | null;
FolderProperties: FolderProperties | null;
Shared: number;
UrlsExpired: boolean;
ShareIDs: string[];
ShareUrls: SharedUrlInfo[];
// XAttr has following JSON structure encrypted by node key:
// {
// Common: {
// ModificationTime: "2021-09-16T07:40:54+0000",
// Size: 13283,
// },
// }
XAttr: string;
// CachedThumbnailURL is computed URL to cached image. This is not part
// of any request and not filled automatically. To get this value, use
// `loadLinkThumbnail` from `useDrive`.
CachedThumbnailURL: string;
ThumbnailIsLoading: boolean;
}
export interface FileLinkMeta extends DriveLink {
Type: LinkType.FILE;
FileProperties: FileProperties;
FolderProperties: null;
}
export interface FolderLinkMeta extends DriveLink {
Type: LinkType.FOLDER;
FolderProperties: FolderProperties;
FileProperties: null;
}
export type LinkMeta = FileLinkMeta | FolderLinkMeta;
export const isFolderLinkMeta = (link: LinkMeta): link is FolderLinkMeta => link.Type === LinkType.FOLDER;
export interface LinkMetaResult {
Link: LinkMeta;
}
export interface LinkChildrenResult {
Links: LinkMeta[];
}
export interface HashCheckResult {
AvailableHashes: string[];
PendingHashes: {
ClientUID: string;
Hash: string;
LinkID: string;
RevisionID: string;
}[];
}
export interface MoveLink {
Name: string;
Hash: string;
ParentLinkID: string;
NodePassphrase: string;
NodePassphraseSignature: string;
SignatureAddress: string;
NewShareID?: string;
ContentHash?: string;
}
export type DriveSectionSortKeys = keyof Pick<DriveLink, 'MIMEType' | 'ModifyTime' | 'Size' | 'Name'>;
export type SharedLinksSectionSortKeys =
| keyof Pick<DriveLink, 'Name'>
| keyof Pick<SharedUrlInfo, 'CreateTime' | 'ExpireTime'>;
export type AllSortKeys = DriveSectionSortKeys | SharedLinksSectionSortKeys;
export type SortParams<T extends AllSortKeys = AllSortKeys> = {
sortField: T;
sortOrder: SORT_DIRECTION;
};
export interface ShareMapLink {
CreateTime: number;
Hash: string;
Index: number;
LinkID: string;
MIMEType: string;
ModifyTime: number;
Name: string;
ParentLinkID: string | null;
Size: number;
State: number;
Type: LinkType;
// These will be missing for Link.Type !== LinkType.FOLDER
NodeKey?: string;
NodePassphrase?: string;
NodePassphraseSignature?: string;
NodePassphraseSignatureEmail?: string;
}
export interface ShareMapPayload {
Links: ShareMapLink[];
SessionName: string;
More: 0 | 1;
Total: number;
}
export interface LinkMetaBatchPayload {
Links: LinkMeta[];
Parents: LinkMeta[];
}
| 8,606 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/node.ts | import { PrivateKeyReference, SessionKey } from '@proton/crypto';
export interface NodeKeys {
privateKey: PrivateKeyReference;
sessionKey?: SessionKey;
}
| 8,607 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/photos.ts | export interface Photo {
LinkID: string;
CaptureTime: number;
MainPhotoLinkID: string | null;
Exif: string | null;
Hash: string | null;
ContentHash: string | null;
}
| 8,608 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/restore.ts | import { RESPONSE_CODE } from '../../drive/constants';
export interface RestoreFromTrashResult {
Responses: {
LinkID: string;
Response: RestoreResponse;
}[];
}
export interface RestoreResponse {
Code: RESPONSE_CODE;
Error?: string;
}
| 8,609 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/share.ts | export interface CreateDriveShare {
AddressID: string;
RootLinkID: string;
Name: string;
ShareKey: string;
SharePassphrase: string;
SharePassphraseSignature: string;
PassphraseKeyPacket: string;
NameKeyPacket: string;
}
export interface CreateDrivePhotosShare {
Share: {
Name: string;
AddressID: string;
Key: string;
Passphrase: string;
PassphraseSignature: string;
};
Link: {
NodeKey: string;
NodePassphrase: string;
NodePassphraseSignature: string;
NodeHashKey: string;
Name: string;
};
}
export interface UserShareResult {
Shares: ShareMetaShort[];
}
export interface ShareMetaShort {
ShareID: string;
Type: number;
LinkID: string;
Locked: boolean;
VolumeID: string;
Creator: string;
Flags: number;
PossibleKeyPackets?: { KeyPacket: string }[];
VolumeSoftDeleted: boolean;
State: number;
}
export interface ShareMeta extends ShareMetaShort {
Key: string;
Passphrase: string;
PassphraseSignature: string;
AddressID: string;
RootLinkRecoveryPassphrase?: string;
}
export enum ShareFlags {
MainShare = 1,
}
| 8,610 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/sharing.ts | import { SessionKey } from '@proton/crypto';
import { AuthVersion } from '../../authentication/interface';
import { DriveFileBlock, Thumbnail } from './file';
import { LinkType } from './link';
type WithSRPPayload<T extends any> = T & {
SRPModulusID: string;
SRPVerifier: string;
UrlPasswordSalt: string;
};
/**
* drive/shares/{enc_shareID}/urls request payload
*/
export type CreateSharedURL = WithSRPPayload<{
CreatorEmail: string;
ExpirationDuration: number | null;
Flags: number; // Unused in first iteration
MaxAccesses: number;
Password: string;
Permissions: number; // Only read (4) in first iteration
SharePassphraseKeyPacket: string;
SharePasswordSalt: string;
}>;
/**
* drive/shares/{enc_shareID}/urls response payload
*/
export type ShareURL = WithSRPPayload<{
CreateTime: number;
CreatorEmail: string;
ExpirationTime: number | null;
Flags: number;
LastAccessTime: number;
MaxAccesses: number;
NumAccesses: number;
Password: string;
Permissions: number;
ShareID: string;
SharePassphraseKeyPacket: string;
SharePasswordSalt: string;
ShareURLID: string;
Token: string;
PublicUrl: string;
}>;
export type UpdateSharedURL = WithSRPPayload<{
ExpirationDuration: number | null;
ExpirationTime: number | null;
Flags: number; // Unused in first iteration
MaxAccesses: number;
Password: string;
Permissions: number; // Only read (4) in first iteration
SharePassphraseKeyPacket: string;
SharePasswordSalt: string;
}>;
/**
* drive/urls/{token} response payload
*/
export interface SharedURLInfo {
ContentKeyPacket: string;
ContentKeyPacketSignature: string;
CreateTime: number;
ExpirationTime: number | null;
LinkID: string;
LinkType: LinkType;
MIMEType: string;
Name: string;
NodeKey: string;
NodePassphrase: string;
ShareKey: string;
SharePassphrase: string;
SharePasswordSalt: string;
Size: number;
ThumbnailURLInfo: ThumbnailURLInfo;
Token: string;
}
/**
* drive/urls/{token}/files/{linkId} response payload
*/
export interface SharedURLRevision {
Blocks: DriveFileBlock[];
CreateTime: number;
ID: string;
ManifestSignature: string;
SignatureAddress: string;
Size: number;
State: number;
Thumbnails: Thumbnail[];
XAttr: string;
}
/**
* drive/urls/{token}/info response payload
*/
export interface SRPHandshakeInfo {
Code: number;
Modulus: string;
ServerEphemeral: string;
UrlPasswordSalt: string;
SRPSession: string;
Version: AuthVersion;
Flags: number;
}
export interface ThumbnailURLInfo {
BareURL: string;
Token: string;
}
export interface SharedURLSessionKeyPayload {
sharePasswordSalt: string;
shareSessionKey: SessionKey;
}
export enum SharedURLFlags {
// CustomPassword flag is set by both types, legacy and new, of custom
// password. Legacy has set only CustomPassword, whereas the new type
// has both CustomPassword and GeneratedPasswordIncluded. That is for
// easier detection whether user should be asked for the password.
// All new shares should use new logic, and the legacy mode should be
// removed when all old shares are cancelled.
CustomPassword = 1,
GeneratedPasswordIncluded,
}
export interface AbuseReportPayload {
ShareURL: string;
Password?: string;
AbuseCategory: string;
ReporterEmail?: string;
ReporterMessage?: string;
ResourcePassphrase: string;
}
| 8,611 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/userSettings.ts | export enum SortSetting {
NameAsc = 1,
SizeAsc = 2,
ModifiedAsc = 4,
NameDesc = -1,
SizeDesc = -2,
ModifiedDesc = -4,
}
export enum LayoutSetting {
List = 0,
Grid = 1,
}
export type RevisionRetentionDaysSetting = 0 | 7 | 30 | 180 | 365 | 3650;
export interface UserSettings {
Sort: SortSetting;
Layout: LayoutSetting;
RevisionRetentionDays: RevisionRetentionDaysSetting;
}
export interface UserSettingsResponse {
UserSettings: { [K in keyof UserSettings]: UserSettings[K] | null };
Defaults: { RevisionRetentionDays: UserSettings['RevisionRetentionDays'] };
}
| 8,612 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/drive/volume.ts | import { ShareURL } from './sharing';
export interface CreateDriveVolume {
AddressID: string;
VolumeName: string;
ShareName: string;
FolderName: string;
SharePassphrase: string;
ShareKey: string;
FolderPassphrase: string;
FolderKey: string;
FolderHashKey: string;
}
export interface DriveVolume {
ID: string;
Share: {
ID: string;
LinkID: string;
};
}
export interface CreatedDriveVolumeResult {
Volume: DriveVolume;
}
export interface RestoreDriveVolume {
Name: string;
SignatureAddress: string;
Hash: string;
NodePassphrase: string;
NodePassphraseSignature: string;
TargetVolumeID: string;
Devices?: {
LockedShareID: string;
ShareKeyPacket: string;
PassphraseSignature: string;
}[];
PhotoShares?: {
LockedShareID: string;
ShareKeyPacket: string;
PassphraseSignature: string;
}[];
}
export interface ListDriveVolumeTrashPayload {
Trash: {
LinkIDs: string[];
ShareID: string;
ParentIDs: string[];
}[];
}
export interface ListDriveVolumeSharedLinksPayload {
ShareURLContexts: {
ContextShareID: string;
ShareURLs: ShareURL[];
LinkIDs: string[];
}[];
}
| 8,613 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetAddressKeys.ts | import { getDecryptedAddressKeys } from '../../keys';
export type GetAddressKeys = (id: string) => ReturnType<typeof getDecryptedAddressKeys>;
| 8,614 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetAddresses.ts | import { Address } from '../Address';
export type GetAddresses = () => Promise<Address[]>;
| 8,615 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetCalendarEventRaw.ts | import { EVENT_VERIFICATION_STATUS } from '../../calendar/constants';
import { CalendarEvent, CalendarEventEncryptionData, SelfAddressData, VcalVeventComponent } from '../calendar';
export type GetCalendarEventRaw = (Event: CalendarEvent) => Promise<{
veventComponent: VcalVeventComponent;
hasDefaultNotifications: boolean;
verificationStatus: EVENT_VERIFICATION_STATUS;
selfAddressData: SelfAddressData;
encryptionData: CalendarEventEncryptionData;
}>;
| 8,616 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetCalendarInfo.ts | import { DecryptedKey } from '../Key';
import { CalendarSettings, DecryptedCalendarKey } from '../calendar';
export type GetCalendarInfo = (ID: string) => Promise<{
memberID: string;
addressID: string;
addressKeys: DecryptedKey[];
calendarKeys: DecryptedCalendarKey[];
calendarSettings: CalendarSettings;
passphrase: string;
passphraseID: string;
}>;
| 8,617 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetCalendarKeys.ts | import { DecryptedCalendarKey } from '../calendar';
export type GetCalendarKeys = (calendarID: string) => Promise<DecryptedCalendarKey[]>;
| 8,618 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetCanonicalEmailsMap.ts | import { SimpleMap } from '../utils';
export type GetCanonicalEmailsMap = (emails: string[]) => Promise<SimpleMap<string>>;
| 8,619 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetContactEmails.ts | import { ContactEmail } from '@proton/shared/lib/interfaces/contacts';
export type GetContactEmails = () => Promise<ContactEmail[]>;
| 8,620 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetContacts.ts | import { Contact } from '@proton/shared/lib/interfaces/contacts';
export type GetContacts = () => Promise<Contact[]>;
| 8,621 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetDecryptedPassphraseAndCalendarKeys.ts | import { SessionKey } from '@proton/crypto';
import { DecryptedCalendarKey } from '../calendar';
export type GetDecryptedPassphraseAndCalendarKeys = (calendarID: string) => Promise<{
decryptedCalendarKeys: DecryptedCalendarKey[];
decryptedPassphrase: string;
decryptedPassphraseSessionKey: SessionKey;
passphraseID: string;
}>;
| 8,622 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetEncryptionPreferences.ts | import { EncryptionPreferences } from '../../mail/encryptionPreferences';
import { ContactEmail } from '../contacts';
export type GetEncryptionPreferences = ({
email,
intendedForEmail,
lifetime,
contactEmailsMap,
}: {
email: string;
/**
* Whether the preferences are used in the context of email encryption.
* If true, internal keys with e2ee disabled are not returned.
*/
intendedForEmail?: boolean;
lifetime?: number;
contactEmailsMap?: { [email: string]: ContactEmail | undefined };
}) => Promise<EncryptionPreferences>;
| 8,623 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetHolidaysDirectory.ts | import { HolidaysDirectoryCalendar } from '../calendar';
export type GetHolidaysDirectory = () => Promise<HolidaysDirectoryCalendar[]>;
| 8,624 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetPublicKeysForInbox.ts | import { ApiKeysConfig } from '../EncryptionPreferences';
export type GetPublicKeysForInbox = ({
email,
lifetime,
internalKeysOnly,
includeInternalKeysWithE2EEDisabledForMail,
noCache,
}: {
email: string;
lifetime?: number;
internalKeysOnly?: boolean;
/**
* Whether to return internal keys which cannot be used for email encryption, as the owner has disabled E2EE.
* These keys may still be used for e.g. calendar sharing or message verification.
**/
includeInternalKeysWithE2EEDisabledForMail?: boolean;
noCache?: boolean;
}) => Promise<ApiKeysConfig>;
| 8,625 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetVTimezonesMap.ts | import { VcalVtimezoneComponent } from '../calendar';
import { SimpleMap } from '../utils';
export interface VTimezoneObject {
vtimezone: VcalVtimezoneComponent;
vtimezoneString: string;
}
export type GetVTimezonesMap = (tzids: string[]) => Promise<SimpleMap<VTimezoneObject>>;
| 8,626 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/GetVerificationPreferences.ts | import { VerificationPreferences } from '../VerificationPreferences';
import { ContactEmail } from '../contacts';
export type GetVerificationPreferences = ({
email,
lifetime,
contactEmailsMap,
}: {
email: string;
lifetime?: number;
contactEmailsMap?: { [email: string]: ContactEmail | undefined };
}) => Promise<VerificationPreferences>;
| 8,627 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/hooks/RelocalizeText.ts | export type RelocalizeText = ({
getLocalizedText,
newLocaleCode,
relocalizeDateFormat,
}: {
getLocalizedText: () => string;
newLocaleCode?: string;
relocalizeDateFormat?: boolean;
}) => Promise<string>;
| 8,628 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/mail/Message.ts | import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { MIME_TYPES } from '../../constants';
import { Recipient } from '../Address';
export interface AttachmentInfo {
inline?: number;
attachment: number;
}
// Attachment metadata that we get in the element list
export interface AttachmentsMetadata {
ID: string;
Disposition: ATTACHMENT_DISPOSITION;
Name: string;
MIMEType: string;
Size: number;
}
export interface AttachmentFullMetadata {
ID: string;
Name?: string;
Size: number;
MIMEType: string;
Disposition: ATTACHMENT_DISPOSITION;
Sender?: Recipient;
KeyPackets?: string;
Signature?: string;
EncSignature?: string;
AddressID: string;
MessageID: string;
ConversationID: string;
}
export interface Attachment {
ID?: string;
Name?: string;
Size?: number;
Preview?: any;
KeyPackets?: any;
MIMEType?: string;
data?: any;
Headers?: { [key: string]: string };
Encrypted?: number;
Signature?: string;
// EO specific
DataPacket?: any;
}
export interface UnsubscribeMethods {
Mailto?: {
Subject?: string;
Body?: string;
ToList: string[];
};
HttpClient?: string;
OneClick?: 'OneClick';
}
export interface MessageMetadata {
ID: string;
Order: number;
ConversationID: string;
Subject: string;
Unread: number;
/** @deprecated use Flags instead */
Type?: number;
/** @deprecated use Sender.Address instead */
SenderAddress?: string;
/** @deprecated use Sender.Name instead */
SenderName?: string;
Sender: Recipient;
ToList: Recipient[];
CCList: Recipient[];
BCCList: Recipient[];
Time: number;
Size: number;
/** @deprecated use Flags instead */
IsEncrypted?: number;
ExpirationTime?: number;
IsReplied: number;
IsRepliedAll: number;
IsForwarded: number;
AddressID: string;
LabelIDs: string[];
ExternalID: string;
NumAttachments: number;
Flags: number;
AttachmentInfo?: { [key in MIME_TYPES]?: AttachmentInfo };
AttachmentsMetadata?: AttachmentsMetadata[];
SnoozeTime: number;
DisplaySnoozedReminder: boolean;
}
export interface Message extends MessageMetadata {
Body: string;
Header: string;
ParsedHeaders: { [key: string]: string | string[] | undefined };
Attachments: Attachment[];
MIMEType: MIME_TYPES;
ReplyTo: Recipient;
ReplyTos: Recipient[];
UnsubscribeMethods?: UnsubscribeMethods;
Password?: string;
PasswordHint?: string;
RightToLeft?: number;
EORecipient?: Recipient;
}
export type DraftMessage = Pick<
Message,
'Subject' | 'Unread' | 'Sender' | 'ToList' | 'CCList' | 'BCCList' | 'ExternalID' | 'Flags' | 'Body' | 'MIMEType'
>;
interface TaskRunning {
TargetType: string;
AddressID: string;
}
export interface GetMessageResponse {
Code: number;
Message?: Message;
Error?: string;
Details?: string[];
}
export interface QueryMessageMetadataResponse {
Code: number;
Total: number;
Messages: MessageMetadata[];
TasksRunning: TaskRunning[];
}
export interface MarkAsBrokenResponse {
Code: number;
Error?: string;
}
| 8,629 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces | petrpan-code/ProtonMail/WebClients/packages/shared/lib/interfaces/mail/crypto.ts | import { PublicKeyReference } from '@proton/crypto';
import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings';
import { MIME_TYPES } from '../../constants';
import { EncryptionPreferencesError } from '../../mail/encryptionPreferences';
import { KeyTransparencyVerificationResult } from '../KeyTransparency';
import { SimpleMap } from '../utils';
export interface SendPreferences {
encrypt: boolean;
sign: boolean;
pgpScheme: PACKAGE_TYPE;
mimeType: MIME_TYPES;
publicKeys?: PublicKeyReference[];
isPublicKeyPinned?: boolean;
hasApiKeys: boolean;
hasPinnedKeys: boolean;
encryptionDisabled: boolean; // if `encryptionDisabled` is true, `encrypt` will always be false
warnings?: string[];
error?: EncryptionPreferencesError;
ktVerificationResult?: KeyTransparencyVerificationResult;
}
export interface Packets {
Filename: string;
MIMEType: MIME_TYPES;
FileSize: number;
Inline: boolean;
signature?: Uint8Array;
Preview: Uint8Array | string;
keys: Uint8Array;
data: Uint8Array;
}
export interface Package {
Flags?: number;
Addresses?: { [email: string]: Package };
MIMEType?: MIME_TYPES;
Body?: string | Uint8Array;
BodyKey?: any;
BodyKeyPacket?: string;
Type?: PACKAGE_TYPE | 0;
PublicKey?: PublicKeyReference;
AttachmentKeys?: { [AttachmentID: string]: { Key: string; Algorithm: string } };
AttachmentKeyPackets?: { [AttachmentID: string]: string };
}
export interface PackageDirect {
Addresses?: SimpleMap<PackageDirect>;
MIMEType?: MIME_TYPES;
Body?: string;
BodyKey?: any;
BodyKeyPacket?: string;
Type?: PACKAGE_TYPE | 0;
PublicKey?: PublicKeyReference;
Token?: string;
EncToken?: string;
Auth?: {
Version: number;
ModulusID: string;
Salt: string;
Verifier: string;
};
PasswordHint?: string;
Signature?: number;
AttachmentKeys?: { Key: string; Algorithm: string }[];
AttachmentKeyPackets?: string[];
}
export interface AttachmentDirect {
Filename: string;
MIMEType: MIME_TYPES;
ContentID?: string;
Contents: string;
Headers?: any;
}
export type PackageStatus = {
[key in MIME_TYPES]?: boolean;
};
export type Packages = {
[key in MIME_TYPES]?: Package;
};
| 8,630 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keyTransparency/defaults.ts | import { getItem, removeItem, setItem } from '../helpers/storage';
import { KTLocalStorageAPI, KeyTransparencyState } from '../interfaces';
/**
* Return the default set of functions to use local storage,
* i.e. those of the currently running subdomain
*/
export const getDefaultKTLS = (): KTLocalStorageAPI => {
return {
getItem: async (key: string) => getItem(key),
setItem: async (key: string, value: string) => setItem(key, value),
removeItem: async (key: string) => removeItem(key),
getBlobs: async () => Object.keys(window.localStorage),
};
};
export const defaultKeyTransparencyState: KeyTransparencyState = {
selfAuditResult: undefined,
};
| 8,631 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keyTransparency/index.ts | export * from './defaults';
| 8,632 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keyTransparency/telemetry.ts | import { AddressAuditWarningDetails, AddressAuditWarningReason } from '@proton/key-transparency/lib';
export const getWarningReason = (warningDetails?: AddressAuditWarningDetails) => {
if (!warningDetails) {
return 'undefined';
}
const { reason, sklVerificationFailed, addressWasDisabled } = warningDetails;
if (reason === AddressAuditWarningReason.UnverifiableHistory) {
if (addressWasDisabled) {
return 'disabled_address';
}
if (sklVerificationFailed) {
return 'skl_verification_failed';
}
return 'unverifiable_history';
}
if (reason === AddressAuditWarningReason.AddressWithNoKeys) {
return 'address_with_no_keys';
}
// should not fall here
return 'unknown';
};
| 8,633 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/activateMemberAddressKeys.ts | import { CryptoProxy } from '@proton/crypto';
import { activateKeyRoute, activateKeyRouteV2 } from '../api/keys';
import { MEMBER_PRIVATE } from '../constants';
import { Address, Api, DecryptedKey, KeyTransparencyVerify, UserModel as tsUserModel } from '../interfaces';
import { generateAddressKeyTokens } from './addressKeys';
import { getActiveKeys, getNormalizedActiveKeys } from './getActiveKeys';
import { getPrimaryKey } from './getPrimaryKey';
import { getHasMigratedAddressKeys } from './keyMigration';
import { getSignedKeyListWithDeferredPublish } from './signedKeyList';
export const getAddressesWithKeysToActivate = (user: tsUserModel, addresses: Address[]) => {
// If signed in as subuser, or not a readable member
if (!user || !addresses || user.OrganizationPrivateKey || user.Private !== MEMBER_PRIVATE.READABLE) {
return [];
}
return addresses.filter(({ Keys = [] }) => {
return Keys.some(({ Activation }) => !!Activation);
});
};
interface Args {
address: Address;
addresses: Address[];
addressKeys: DecryptedKey[];
userKeys: DecryptedKey[];
keyPassword: string;
api: Api;
keyTransparencyVerify: KeyTransparencyVerify;
}
export const activateMemberAddressKeys = async ({
addresses,
address,
addressKeys,
userKeys,
keyPassword,
api,
keyTransparencyVerify,
}: Args) => {
if (!addressKeys.length) {
return;
}
if (!keyPassword) {
throw new Error('Password required to generate keys');
}
const activeKeys = getNormalizedActiveKeys(
address,
await getActiveKeys(address, address.SignedKeyList, address.Keys, addressKeys)
);
const primaryUserKey = getPrimaryKey(userKeys)?.privateKey;
if (!primaryUserKey) {
throw new Error('Missing primary user key');
}
const isKeyMigrationFlow = getHasMigratedAddressKeys(addresses);
for (const addressKey of addressKeys) {
const { ID, privateKey } = addressKey;
const Key = address.Keys.find(({ ID: otherID }) => otherID === ID);
if (!Key?.Activation || !privateKey) {
continue;
}
if (isKeyMigrationFlow) {
const { token, encryptedToken, signature } = await generateAddressKeyTokens(primaryUserKey);
const encryptedPrivateKey = await CryptoProxy.exportPrivateKey({
privateKey,
passphrase: token,
});
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
activeKeys,
address,
keyTransparencyVerify
);
await api(
activateKeyRouteV2({
ID,
PrivateKey: encryptedPrivateKey,
SignedKeyList,
Token: encryptedToken,
Signature: signature,
})
);
// Only once the SKL is successfully posted we add it to the KT commit state.
await onSKLPublishSuccess();
} else {
const encryptedPrivateKey = await CryptoProxy.exportPrivateKey({
privateKey,
passphrase: keyPassword,
});
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
activeKeys,
address,
keyTransparencyVerify
);
await api(activateKeyRoute({ ID, PrivateKey: encryptedPrivateKey, SignedKeyList }));
// Only once the SKL is successfully posted we add it to the KT commit state.
await onSKLPublishSuccess();
}
}
};
| 8,634 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/addressKeyActions.ts | import { removeKeyRoute, setKeyFlagsRoute, setKeyPrimaryRoute } from '../api/keys';
import { Address, Api, DecryptedKey, KeyTransparencyVerify } from '../interfaces';
import { getActiveKeys, getNormalizedActiveKeys } from './getActiveKeys';
import { getSignedKeyListWithDeferredPublish } from './signedKeyList';
export const setPrimaryAddressKey = async (
api: Api,
address: Address,
keys: DecryptedKey[],
ID: string,
keyTransparencyVerify: KeyTransparencyVerify
) => {
const activeKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, keys);
const oldActiveKey = activeKeys.find(({ ID: otherID }) => ID === otherID);
if (!oldActiveKey) {
throw new Error('Cannot set primary key');
}
const updatedActiveKeys = getNormalizedActiveKeys(
address,
activeKeys
.map((activeKey) => {
return {
...activeKey,
primary: activeKey.ID === ID ? 1 : 0,
} as const;
})
.sort((a, b) => b.primary - a.primary)
);
const [signedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
await api(setKeyPrimaryRoute({ ID, SignedKeyList: signedKeyList }));
await onSKLPublishSuccess();
const newActivePrimaryKey = updatedActiveKeys.find((activeKey) => activeKey.ID === ID)!!;
return [newActivePrimaryKey, updatedActiveKeys] as const;
};
export const deleteAddressKey = async (
api: Api,
address: Address,
keys: DecryptedKey[],
ID: string,
keyTransparencyVerify: KeyTransparencyVerify
) => {
const activeKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, keys);
const oldActiveKey = activeKeys.find(({ ID: otherID }) => ID === otherID);
if (oldActiveKey?.primary) {
throw new Error('Cannot delete primary key');
}
const updatedActiveKeys = getNormalizedActiveKeys(
address,
activeKeys.filter(({ ID: otherID }) => ID !== otherID)
);
const [signedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
await api(removeKeyRoute({ ID, SignedKeyList: signedKeyList }));
await onSKLPublishSuccess();
};
export const setAddressKeyFlags = async (
api: Api,
address: Address,
keys: DecryptedKey[],
ID: string,
flags: number,
keyTransparencyVerify: KeyTransparencyVerify
) => {
const activeKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, keys);
const updatedActiveKeys = getNormalizedActiveKeys(
address,
activeKeys.map((activeKey) => {
if (activeKey.ID === ID) {
return {
...activeKey,
flags,
};
}
return activeKey;
})
);
const [signedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
await api(setKeyFlagsRoute({ ID, Flags: flags, SignedKeyList: signedKeyList }));
await onSKLPublishSuccess();
};
| 8,635 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/addressKeys.ts | import { c } from 'ttag';
import { CryptoProxy, PrivateKeyReference, PublicKeyReference, VERIFICATION_STATUS, serverTime } from '@proton/crypto';
import { arrayToHexString } from '@proton/crypto/lib/utils';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { splitKeys } from '@proton/shared/lib/keys/keys';
import isTruthy from '@proton/utils/isTruthy';
import { DEFAULT_ENCRYPTION_CONFIG, ENCRYPTION_CONFIGS } from '../constants';
import {
Address,
AddressKey,
DecryptedAddressKey,
DecryptedKey,
EncryptionConfig,
KeyPair,
KeysPair,
AddressKey as tsAddressKey,
} from '../interfaces';
import { decryptMemberToken } from './memberToken';
interface EncryptAddressKeyTokenArguments {
token: string;
userKey: PrivateKeyReference;
organizationKey?: PrivateKeyReference;
}
export const encryptAddressKeyToken = async ({ token, userKey, organizationKey }: EncryptAddressKeyTokenArguments) => {
const date = serverTime(); // ensure the signed message and the encrypted one have the same creation time, otherwise verification will fail
const textData = token;
const [userSignatureResult, organizationSignatureResult] = await Promise.all([
CryptoProxy.signMessage({
textData, // stripTrailingSpaces: false,
date,
signingKeys: [userKey],
detached: true,
}),
organizationKey
? CryptoProxy.signMessage({
textData, // stripTrailingSpaces: false,
date,
signingKeys: [organizationKey],
detached: true,
})
: undefined,
]);
const { message: encryptedToken } = await CryptoProxy.encryptMessage({
textData,
date,
encryptionKeys: organizationKey ? [userKey, organizationKey] : [userKey],
});
return {
token,
encryptedToken,
signature: userSignatureResult,
...(organizationSignatureResult && { organizationSignature: organizationSignatureResult }),
};
};
interface DecryptAddressKeyTokenArguments {
Token: string;
Signature: string;
privateKeys: PrivateKeyReference | PrivateKeyReference[];
publicKeys: PublicKeyReference | PublicKeyReference[];
}
export const decryptAddressKeyToken = async ({
Token,
Signature,
privateKeys,
publicKeys,
}: DecryptAddressKeyTokenArguments) => {
const { data: decryptedToken, verified } = await CryptoProxy.decryptMessage({
armoredMessage: Token,
armoredSignature: Signature,
decryptionKeys: privateKeys,
verificationKeys: publicKeys,
});
if (verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) {
const error = new Error(c('Error').t`Signature verification failed`);
error.name = 'SignatureError';
throw error;
}
return decryptedToken;
};
interface AddressKeyTokenResult {
token: string;
encryptedToken: string;
signature: string;
organizationSignature?: string;
}
interface AddressKeyOrgTokenResult extends AddressKeyTokenResult {
organizationSignature: string;
}
export function generateAddressKeyTokens(
userKey: PrivateKeyReference,
organizationKey: PrivateKeyReference
): Promise<AddressKeyOrgTokenResult>;
export function generateAddressKeyTokens(
userKey: PrivateKeyReference,
organizationKey?: PrivateKeyReference
): Promise<AddressKeyTokenResult>;
export async function generateAddressKeyTokens(userKey: PrivateKeyReference, organizationKey?: PrivateKeyReference) {
const randomBytes = crypto.getRandomValues(new Uint8Array(32));
const token = arrayToHexString(randomBytes);
return encryptAddressKeyToken({ token, organizationKey, userKey });
}
interface GetAddressKeyTokenArguments {
Token: string;
Signature: string;
organizationKey?: KeyPair;
privateKeys: PrivateKeyReference | PrivateKeyReference[];
publicKeys: PublicKeyReference | PublicKeyReference[];
}
export const getAddressKeyToken = ({
Token,
Signature,
organizationKey,
privateKeys,
publicKeys,
}: GetAddressKeyTokenArguments) => {
// New address key format
if (Signature) {
return decryptAddressKeyToken({
Token,
Signature,
privateKeys,
publicKeys,
});
}
if (!organizationKey) {
throw new Error('Missing organization key');
}
// Old address key format for an admin signed into a non-private user
return decryptMemberToken(Token, [organizationKey.privateKey], [organizationKey.publicKey]);
};
export const getAddressKeyPassword = (
{ Activation, Token, Signature }: tsAddressKey,
userKeys: KeysPair,
keyPassword: string,
organizationKey?: KeyPair
) => {
// If not decrypting the non-private member keys with the organization key, and
// because the activation process is asynchronous in the background, allow the
// private key to get decrypted already here so that it can be used
if (!organizationKey && Activation) {
return decryptMemberToken(Activation, userKeys.privateKeys, userKeys.publicKeys);
}
if (Token) {
return getAddressKeyToken({
Token,
Signature,
organizationKey,
privateKeys: userKeys.privateKeys,
publicKeys: userKeys.publicKeys,
});
}
return Promise.resolve(keyPassword);
};
export const getDecryptedAddressKey = async (
{ ID, PrivateKey, Flags, Primary }: tsAddressKey,
addressKeyPassword: string
): Promise<DecryptedAddressKey> => {
const privateKey = await CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: addressKeyPassword });
const publicKey = await CryptoProxy.importPublicKey({
binaryKey: await CryptoProxy.exportPublicKey({ key: privateKey, format: 'binary' }),
});
return {
ID,
Flags,
privateKey,
publicKey,
Primary,
};
};
export interface ReformatAddressKeyArguments {
email: string;
name?: string;
passphrase: string;
privateKey: PrivateKeyReference;
}
export const reformatAddressKey = async ({
email,
name = email,
passphrase,
privateKey: originalKey,
}: ReformatAddressKeyArguments) => {
const privateKey = await CryptoProxy.reformatKey({
userIDs: [{ name, email }],
privateKey: originalKey,
});
const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase });
return { privateKey, privateKeyArmored };
};
export const getEncryptedArmoredAddressKey = async (
privateKey: PrivateKeyReference,
email: string,
newKeyPassword: string
) => {
return CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase: newKeyPassword });
};
export interface GenerateAddressKeyArguments {
email: string;
name?: string;
passphrase: string;
encryptionConfig?: EncryptionConfig;
}
export const generateAddressKey = async ({
email,
name = email,
passphrase,
encryptionConfig = ENCRYPTION_CONFIGS[DEFAULT_ENCRYPTION_CONFIG],
}: GenerateAddressKeyArguments) => {
const privateKey = await CryptoProxy.generateKey({
userIDs: [{ name, email }],
...encryptionConfig,
});
const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase });
return { privateKey, privateKeyArmored };
};
interface ReplaceAddressTokens {
privateKey: PrivateKeyReference;
userKeys: DecryptedKey[];
addresses: Address[];
}
const replaceAddressKeyToken = async ({
addressKey,
decryptionKeys,
encryptionKey,
}: {
addressKey: AddressKey;
decryptionKeys: PrivateKeyReference[];
encryptionKey: PrivateKeyReference;
}) => {
const sessionKey = await CryptoProxy.decryptSessionKey({
armoredMessage: addressKey.Token,
decryptionKeys,
});
if (!sessionKey) {
return undefined;
}
const message = await CryptoProxy.decryptMessage({
armoredMessage: addressKey.Token,
sessionKeys: sessionKey,
format: 'binary',
});
const result = await CryptoProxy.encryptSessionKey({
...sessionKey,
encryptionKeys: [encryptionKey],
format: 'binary',
});
const signature = await CryptoProxy.signMessage({
binaryData: message.data,
signingKeys: [encryptionKey],
detached: true,
});
return {
id: addressKey.ID,
keyPacket: uint8ArrayToBase64String(result),
signature,
};
};
export const getReplacedAddressKeyTokens = async ({ addresses, userKeys, privateKey }: ReplaceAddressTokens) => {
const { privateKeys } = splitKeys(userKeys);
const reEncryptedTokens = await Promise.all(
addresses.map(async (address) => {
const result = await Promise.all(
address.Keys.map(async (addressKey) => {
try {
const result = await replaceAddressKeyToken({
addressKey,
encryptionKey: privateKey,
decryptionKeys: privateKeys,
});
if (!result) {
return undefined;
}
return {
AddressKeyID: result.id,
KeyPacket: result.keyPacket,
Signature: result.signature,
};
} catch (e) {
return undefined;
}
})
);
return result.filter(isTruthy);
})
);
return {
AddressKeyTokens: reEncryptedTokens.flat(),
};
};
interface RenameAddressKeysArguments {
userKeys: DecryptedKey[];
addressKeys: AddressKey[];
organizationKey?: KeyPair;
email: string;
}
export const getRenamedAddressKeys = async ({
userKeys,
addressKeys,
organizationKey,
email,
}: RenameAddressKeysArguments) => {
const splittedUserKeys = splitKeys(userKeys);
const cb = async (addressKey: AddressKey) => {
try {
const addressKeyPassword = await getAddressKeyPassword(
addressKey,
splittedUserKeys,
'', // Not using a key password since this function only works for address key migrated users
organizationKey
);
const { privateKey } = await getDecryptedAddressKey(addressKey, addressKeyPassword);
const changedPrivateKey = await CryptoProxy.cloneKeyAndChangeUserIDs({
privateKey,
userIDs: [{ name: email, email }],
});
const privateKeyArmored = await CryptoProxy.exportPrivateKey({
privateKey: changedPrivateKey,
passphrase: addressKeyPassword,
});
await CryptoProxy.clearKey({ key: privateKey });
return {
PrivateKey: privateKeyArmored,
ID: addressKey.ID,
};
} catch (e) {
return;
}
};
const result = await Promise.all(addressKeys.map(cb));
return result.filter(isTruthy);
};
| 8,636 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/changePassword.ts | import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import isTruthy from '@proton/utils/isTruthy';
import noop from '@proton/utils/noop';
import { DecryptedKey, Address as tsAddress } from '../interfaces';
import { getEncryptedArmoredAddressKey } from './addressKeys';
import { getHasMigratedAddressKeys } from './keyMigration';
const getEncryptedArmoredUserKey = async ({ ID, privateKey }: DecryptedKey, newKeyPassword: string) => {
const privateKeyArmored = await CryptoProxy.exportPrivateKey({
privateKey,
passphrase: newKeyPassword,
});
return {
ID,
PrivateKey: privateKeyArmored,
};
};
export const getEncryptedArmoredOrganizationKey = async (
organizationKey: PrivateKeyReference | undefined,
newKeyPassword: string
) => {
if (!organizationKey) {
return;
}
return CryptoProxy.exportPrivateKey({ privateKey: organizationKey, passphrase: newKeyPassword });
};
export const getArmoredPrivateUserKeys = async (keys: DecryptedKey[], keyPassword: string) => {
if (keys.length === 0) {
return [];
}
const armoredKeys = await Promise.all(
keys.map((key) => {
return getEncryptedArmoredUserKey(key, keyPassword).catch(noop);
})
);
const result = armoredKeys.filter(isTruthy);
if (result.length === 0) {
const decryptedError = new Error('No decrypted keys exist');
decryptedError.name = 'NoDecryptedKeys';
throw decryptedError;
}
return result;
};
export const getArmoredPrivateAddressKeys = async (keys: DecryptedKey[], address: tsAddress, keyPassword: string) => {
const armoredKeys = await Promise.all(
keys.map(async ({ ID, privateKey }) => {
const PrivateKey = await getEncryptedArmoredAddressKey(privateKey, address.Email, keyPassword).catch(noop);
if (!PrivateKey) {
return;
}
return {
ID,
PrivateKey,
};
})
);
const result = armoredKeys.filter(isTruthy);
if (result.length === 0) {
const decryptedError = new Error('No decrypted keys exist');
decryptedError.name = 'NoDecryptedKeys';
throw decryptedError;
}
return result;
};
interface AddressesKeys {
address: tsAddress;
keys: DecryptedKey[];
}
export const getArmoredPrivateAddressesKeys = async (addressesWithKeysList: AddressesKeys[], keyPassword: string) => {
const result = await Promise.all(
addressesWithKeysList.map(({ address, keys }) => {
if (!keys.length) {
return;
}
return getArmoredPrivateAddressKeys(keys, address, keyPassword);
})
);
return result.flat().filter(isTruthy);
};
export const getUpdateKeysPayload = async (
addressesKeys: AddressesKeys[],
userKeys: DecryptedKey[],
organizationKey: PrivateKeyReference | undefined,
keyPassword: string,
keySalt: string,
forceMigratedAddressKeys?: boolean
) => {
const hasMigratedAddressKeys = forceMigratedAddressKeys
? true
: getHasMigratedAddressKeys(addressesKeys.map(({ address }) => address));
const [armoredUserKeys, armoredAddressesKeys, armoredOrganizationKey] = await Promise.all([
getArmoredPrivateUserKeys(userKeys, keyPassword),
hasMigratedAddressKeys ? [] : getArmoredPrivateAddressesKeys(addressesKeys, keyPassword),
getEncryptedArmoredOrganizationKey(organizationKey, keyPassword),
]);
return hasMigratedAddressKeys
? {
UserKeys: armoredUserKeys,
KeySalt: keySalt,
OrganizationKey: armoredOrganizationKey,
}
: {
Keys: [...armoredUserKeys, ...armoredAddressesKeys],
KeySalt: keySalt,
OrganizationKey: armoredOrganizationKey,
};
};
| 8,637 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/driveKeys.ts | import { CryptoProxy, PrivateKeyReference, PublicKeyReference, SessionKey } from '@proton/crypto';
import { arrayToHexString, stringToUtf8Array } from '@proton/crypto/lib/utils';
import { createSessionKey, getEncryptedSessionKey } from '../calendar/crypto/encrypt';
import { generatePassphrase } from '../calendar/crypto/keys/calendarKeys';
import { ENCRYPTION_CONFIGS, ENCRYPTION_TYPES } from '../constants';
import { uint8ArrayToBase64String } from '../helpers/encoding';
interface UnsignedEncryptionPayload {
message: string | Uint8Array;
publicKey: PublicKeyReference;
}
export const sign = async (data: string | Uint8Array, privateKeys: PrivateKeyReference | PrivateKeyReference[]) => {
const dataType = data instanceof Uint8Array ? 'binaryData' : 'textData';
const signature = await CryptoProxy.signMessage({
[dataType]: data,
stripTrailingSpaces: dataType === 'textData',
signingKeys: privateKeys,
detached: true,
});
return signature;
};
export const encryptUnsigned = async ({ message, publicKey }: UnsignedEncryptionPayload) => {
const dataType = message instanceof Uint8Array ? 'binaryData' : 'textData';
const { message: encryptedToken } = await CryptoProxy.encryptMessage({
[dataType]: message,
stripTrailingSpaces: dataType === 'textData',
encryptionKeys: publicKey,
});
return encryptedToken;
};
export const encryptName = async (
name: string,
parentPublicKey: PublicKeyReference,
addressPrivateKey: PrivateKeyReference
) => {
const { message: Name } = await CryptoProxy.encryptMessage({
textData: name,
stripTrailingSpaces: true,
encryptionKeys: parentPublicKey,
signingKeys: addressPrivateKey,
});
return Name;
};
interface UnsignedDecryptionPayload {
armoredMessage: string;
privateKey: PrivateKeyReference | PrivateKeyReference[];
}
interface SignedDecryptionPayload<F extends 'utf8' | 'binary'> extends UnsignedDecryptionPayload {
publicKey: PublicKeyReference | PublicKeyReference[];
format?: F;
}
export const decryptSigned = async <F extends 'utf8' | 'binary' = 'utf8'>({
armoredMessage,
privateKey,
publicKey,
format,
}: SignedDecryptionPayload<F>) => {
const { data, verified } = await CryptoProxy.decryptMessage({
armoredMessage,
decryptionKeys: privateKey,
verificationKeys: publicKey,
format,
});
return { data, verified };
};
/**
* Decrypts unsigned armored message, in the context of drive it's share's passphrase and folder's contents.
*/
export const decryptUnsigned = async ({ armoredMessage, privateKey }: UnsignedDecryptionPayload) => {
const { data: decryptedMessage } = await CryptoProxy.decryptMessage({
armoredMessage,
decryptionKeys: privateKey,
});
return decryptedMessage;
};
export const generateDriveKey = async (rawPassphrase: string) => {
const encryptionConfigs = ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519];
const privateKey = await CryptoProxy.generateKey({
userIDs: [{ name: 'Drive key' }],
...encryptionConfigs,
});
const privateKeyArmored = await CryptoProxy.exportPrivateKey({
privateKey,
passphrase: rawPassphrase,
});
return { privateKey, privateKeyArmored };
};
export const generateLookupHash = async (name: string, parentHashKey: Uint8Array) => {
const key = await crypto.subtle.importKey('raw', parentHashKey, { name: 'HMAC', hash: 'SHA-256' }, false, [
'sign',
'verify',
]);
const signature = await crypto.subtle.sign(
{ name: 'HMAC', hash: { name: 'SHA-256' } },
key,
stringToUtf8Array(name)
);
return arrayToHexString(new Uint8Array(signature));
};
export const generateNodeHashKey = async (publicKey: PublicKeyReference, addressPrivateKey: PrivateKeyReference) => {
const { message: NodeHashKey } = await CryptoProxy.encryptMessage({
// Once all clients can use non-ascii bytes, switch to simple
// generating of random bytes without encoding it into base64:
//binaryData: crypto.getRandomValues(new Uint8Array(32)),
textData: generatePassphrase(),
encryptionKeys: publicKey,
signingKeys: addressPrivateKey,
});
return { NodeHashKey };
};
export const encryptPassphrase = async (
parentKey: PrivateKeyReference,
addressKey: PrivateKeyReference = parentKey,
rawPassphrase = generatePassphrase(),
passphraseSessionKey?: SessionKey
) => {
const sessionKey = passphraseSessionKey
? passphraseSessionKey
: await CryptoProxy.generateSessionKey({ recipientKeys: parentKey });
const { message: NodePassphrase, signature: NodePassphraseSignature } = await CryptoProxy.encryptMessage({
textData: rawPassphrase,
sessionKey,
signingKeys: addressKey,
encryptionKeys: parentKey,
detached: true,
});
return { NodePassphrase, NodePassphraseSignature, sessionKey };
};
export const generateNodeKeys = async (parentKey: PrivateKeyReference, addressKey: PrivateKeyReference = parentKey) => {
const rawPassphrase = generatePassphrase();
const [{ NodePassphrase, NodePassphraseSignature, sessionKey }, { privateKey, privateKeyArmored: NodeKey }] =
await Promise.all([encryptPassphrase(parentKey, addressKey, rawPassphrase), generateDriveKey(rawPassphrase)]);
return { privateKey, NodeKey, NodePassphrase, NodePassphraseSignature, sessionKey };
};
export const generateContentHash = async (content: Uint8Array) => {
const data = await CryptoProxy.computeHash({ algorithm: 'SHA256', data: content });
return { HashType: 'sha256', BlockHash: data };
};
export const generateContentKeys = async (nodeKey: PrivateKeyReference) => {
const publicKey: PublicKeyReference = nodeKey; // no need to get a separate public key reference in this case
const sessionKey = await createSessionKey(publicKey);
const sessionKeySignature = await sign(sessionKey.data, nodeKey);
const contentKeys = await getEncryptedSessionKey(sessionKey, publicKey);
const ContentKeyPacket = uint8ArrayToBase64String(contentKeys);
return { sessionKey, ContentKeyPacket, ContentKeyPacketSignature: sessionKeySignature };
};
export const generateDriveBootstrap = async (addressPrivateKey: PrivateKeyReference) => {
const {
NodeKey: ShareKey,
NodePassphrase: SharePassphrase,
privateKey: sharePrivateKey,
NodePassphraseSignature: SharePassphraseSignature,
} = await generateNodeKeys(addressPrivateKey);
const {
NodeKey: FolderKey,
NodePassphrase: FolderPassphrase,
privateKey: folderPrivateKey,
NodePassphraseSignature: FolderPassphraseSignature,
} = await generateNodeKeys(sharePrivateKey, addressPrivateKey);
const FolderName = await encryptName('root', sharePrivateKey, addressPrivateKey);
return {
bootstrap: {
SharePassphrase,
SharePassphraseSignature,
FolderPassphrase,
FolderPassphraseSignature,
ShareKey,
FolderKey,
FolderName,
},
sharePrivateKey,
folderPrivateKey,
};
};
| 8,638 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/drivePassphrase.ts | import { c } from 'ttag';
import { CryptoProxy, PrivateKeyReference, PublicKeyReference, VERIFICATION_STATUS } from '@proton/crypto';
export const getDecryptedSessionKey = async ({
data: serializedMessage,
privateKeys,
}: {
data: string | Uint8Array;
privateKeys: PrivateKeyReference | PrivateKeyReference[];
}) => {
const messageType = serializedMessage instanceof Uint8Array ? 'binaryMessage' : 'armoredMessage';
const sessionKey = await CryptoProxy.decryptSessionKey({
[messageType]: serializedMessage,
decryptionKeys: privateKeys,
});
if (!sessionKey) {
throw new Error('Could not decrypt session key');
}
return sessionKey;
};
export const decryptPassphrase = async ({
armoredPassphrase,
armoredSignature,
privateKeys,
publicKeys,
validateSignature = true,
}: {
armoredPassphrase: string;
armoredSignature?: string;
privateKeys: PrivateKeyReference[];
publicKeys: PublicKeyReference[];
validateSignature?: boolean;
}) => {
const sessionKey = await getDecryptedSessionKey({ data: armoredPassphrase, privateKeys });
const { data: decryptedPassphrase, verified } = await CryptoProxy.decryptMessage({
armoredMessage: armoredPassphrase,
armoredSignature,
sessionKeys: sessionKey,
verificationKeys: publicKeys,
});
if (validateSignature && verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) {
const error = new Error(c('Error').t`Signature verification failed`);
error.name = 'SignatureError';
throw error;
}
return { decryptedPassphrase, sessionKey, verified };
};
| 8,639 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/generatePrivateMemberKeys.ts | import { ADDRESS_STATUS, MEMBER_PRIVATE } from '../constants';
import { Address, Api, DecryptedKey, KeyTransparencyVerify, UserModel as tsUserModel } from '../interfaces';
import { createAddressKeyLegacy, createAddressKeyV2 } from './add';
import { getPrimaryKey } from './getPrimaryKey';
import { getHasMigratedAddressKeys } from './keyMigration';
export const getAddressesWithKeysToGenerate = (user: tsUserModel, addresses: Address[]) => {
// If signed in as subuser, or not a private user
if (!user || !addresses || user.OrganizationPrivateKey || user.Private !== MEMBER_PRIVATE.UNREADABLE) {
return [];
}
// Any enabled address without keys
return addresses.filter(({ Status, Keys = [] }) => {
return Status === ADDRESS_STATUS.STATUS_ENABLED && !Keys.length;
});
};
interface GenerateAllPrivateMemberKeys {
addresses: Address[];
addressesToGenerate: Address[];
userKeys: DecryptedKey[];
api: Api;
keyPassword: string;
keyTransparencyVerify: KeyTransparencyVerify;
}
export const generateAllPrivateMemberKeys = async ({
addresses,
addressesToGenerate,
userKeys,
keyPassword,
api,
keyTransparencyVerify,
}: GenerateAllPrivateMemberKeys) => {
if (!keyPassword) {
throw new Error('Password required to generate keys');
}
if (getHasMigratedAddressKeys(addresses)) {
const primaryUserKey = getPrimaryKey(userKeys)?.privateKey;
if (!primaryUserKey) {
throw new Error('Missing primary user key');
}
return Promise.all(
addressesToGenerate.map((address) => {
return createAddressKeyV2({
api,
userKey: primaryUserKey,
address,
activeKeys: [],
keyTransparencyVerify,
});
})
);
}
return Promise.all(
addressesToGenerate.map((address) => {
return createAddressKeyLegacy({
api,
address,
passphrase: keyPassword,
activeKeys: [],
keyTransparencyVerify,
});
})
);
};
| 8,640 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/getActiveKeys.ts | import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import isTruthy from '@proton/utils/isTruthy';
import { ADDRESS_TYPE, KEY_FLAG } from '../constants';
import { clearBit } from '../helpers/bitset';
import { ActiveKey, Address, DecryptedKey, Key, SignedKeyList } from '../interfaces';
import { getDefaultKeyFlags, setExternalFlags } from './keyFlags';
import { getParsedSignedKeyList, getSignedKeyListMap } from './signedKeyList';
export const getPrimaryFlag = (keys: ActiveKey[]): 1 | 0 => {
return !keys.length ? 1 : 0;
};
// When a key is disabled, the NOT_OBSOLETE flag is removed. Thus when the key is reactivated, the client uses the old key flags, with the not obsolete flag removed. This is mainly to take into account the old NOT_COMPROMISED flag
export const getReactivatedKeyFlag = (address: Address, Flags: number | undefined) => {
return clearBit(Flags ?? getDefaultKeyFlags(address), KEY_FLAG.FLAG_NOT_OBSOLETE);
};
export const getActiveKeyObject = async (
privateKey: PrivateKeyReference,
partial: Partial<ActiveKey> & { ID: string } & Pick<ActiveKey, 'flags'>
): Promise<ActiveKey> => {
const publicKey = await CryptoProxy.importPublicKey({
binaryKey: await CryptoProxy.exportPublicKey({ key: privateKey, format: 'binary' }),
});
return {
privateKey,
publicKey,
primary: 0,
fingerprint: privateKey.getFingerprint(),
sha256Fingerprints: await CryptoProxy.getSHA256Fingerprints({ key: privateKey }),
...partial,
};
};
export const getActiveKeys = async (
address: Address | undefined,
signedKeyList: SignedKeyList | null | undefined,
keys: Key[],
decryptedKeys: DecryptedKey[]
): Promise<ActiveKey[]> => {
if (!decryptedKeys.length) {
return [];
}
const signedKeyListMap = getSignedKeyListMap(getParsedSignedKeyList(signedKeyList?.Data));
const keysMap = keys.reduce<{ [key: string]: Key | undefined }>((acc, key) => {
acc[key.ID] = key;
return acc;
}, {});
const result = await Promise.all(
decryptedKeys.map(async ({ ID, privateKey }, index) => {
const fingerprint = privateKey.getFingerprint();
const Key = keysMap[ID];
const signedKeyListItem = signedKeyListMap[fingerprint];
return getActiveKeyObject(privateKey, {
ID,
primary: signedKeyListItem?.Primary ?? Key?.Primary ?? index === 0 ? 1 : 0,
// SKL may not exist for non-migrated users, fall back to the flag value of the key.
// Should be improved by asserting SKLs for migrated users, but pushed to later since SKL
// signatures are not verified.
flags: signedKeyListItem?.Flags ?? Key?.Flags ?? getDefaultKeyFlags(address),
});
})
);
return result.filter(isTruthy);
};
export const getNormalizedActiveKeys = (address: Address | undefined, keys: ActiveKey[]): ActiveKey[] => {
return keys
.sort((a, b) => b.primary - a.primary)
.map((result, index) => {
return {
...result,
flags: address?.Type === ADDRESS_TYPE.TYPE_EXTERNAL ? setExternalFlags(result.flags) : result.flags,
// Reset and normalize the primary key. The primary values can be doubly set to 1 if an old SKL is used.
primary: index === 0 ? 1 : 0,
};
});
};
| 8,641 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/getDecryptedAddressKeys.ts | import { getAddressKeyPassword, getDecryptedAddressKey } from '@proton/shared/lib/keys/addressKeys';
import isTruthy from '@proton/utils/isTruthy';
import noop from '@proton/utils/noop';
import { DecryptedAddressKey, KeyPair, User, AddressKey as tsAddressKey } from '../interfaces';
import { getDecryptedOrganizationKey } from './getDecryptedOrganizationKey';
import { splitKeys } from './keys';
export const getDecryptedAddressKeys = async (
addressKeys: tsAddressKey[] = [],
userKeys: KeyPair[] = [],
keyPassword: string,
organizationKey?: KeyPair
): Promise<DecryptedAddressKey[]> => {
if (!addressKeys.length || !userKeys.length) {
return [];
}
const userKeysPair = splitKeys(userKeys);
const [primaryKey, ...restKeys] = addressKeys;
const primaryKeyResult = await getAddressKeyPassword(primaryKey, userKeysPair, keyPassword, organizationKey)
.then((password) => getDecryptedAddressKey(primaryKey, password))
.catch(noop);
// In case the primary key fails to decrypt, something is broken, so don't even try to decrypt the rest of the keys.
if (!primaryKeyResult) {
return [];
}
const restKeyResults = await Promise.all(
restKeys.map((restKey) => {
return getAddressKeyPassword(restKey, userKeysPair, keyPassword, organizationKey)
.then((password) => getDecryptedAddressKey(restKey, password))
.catch(noop);
})
);
return [primaryKeyResult, ...restKeyResults].filter(isTruthy);
};
export const getDecryptedAddressKeysHelper = async (
addressKeys: tsAddressKey[] = [],
user: User,
userKeys: KeyPair[] = [],
keyPassword: string
): Promise<DecryptedAddressKey[]> => {
if (!user.OrganizationPrivateKey) {
return getDecryptedAddressKeys(addressKeys, userKeys, keyPassword);
}
const { OrganizationPrivateKey } = user;
const organizationKey = OrganizationPrivateKey
? await getDecryptedOrganizationKey(OrganizationPrivateKey, keyPassword).catch(noop)
: undefined;
// When signed into a non-private member, if the organization key can't be decrypted, the rest
// of the keys won't be able to get decrypted
if (!organizationKey) {
return [];
}
return getDecryptedAddressKeys(addressKeys, userKeys, keyPassword, organizationKey);
};
| 8,642 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/getDecryptedOrganizationKey.ts | import { CryptoProxy } from '@proton/crypto';
import { CachedOrganizationKey, OrganizationKey } from '../interfaces';
export const getDecryptedOrganizationKey = async (OrganizationPrivateKey: string, keyPassword: string) => {
const privateKey = await CryptoProxy.importPrivateKey({
armoredKey: OrganizationPrivateKey,
passphrase: keyPassword,
});
const publicKey = await CryptoProxy.importPublicKey({
binaryKey: await CryptoProxy.exportPublicKey({ key: privateKey, format: 'binary' }),
});
return {
privateKey,
publicKey,
};
};
export const getCachedOrganizationKey = async ({
keyPassword,
Key,
}: {
keyPassword: string;
Key: OrganizationKey;
}): Promise<CachedOrganizationKey> => {
if (!Key.PrivateKey) {
return {
Key,
};
}
try {
const { privateKey, publicKey } = await getDecryptedOrganizationKey(Key.PrivateKey, keyPassword);
return {
Key,
privateKey,
publicKey,
};
} catch (e: any) {
return {
Key,
error: e,
};
}
};
| 8,643 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/getDecryptedUserKeys.ts | import { CryptoProxy } from '@proton/crypto';
import isTruthy from '@proton/utils/isTruthy';
import noop from '@proton/utils/noop';
import { DecryptedKey, KeyPair, User, Key as tsKey } from '../interfaces';
import { getDecryptedOrganizationKey } from './getDecryptedOrganizationKey';
import { decryptMemberToken } from './memberToken';
export const getUserKeyPassword = ({ Token }: tsKey, keyPassword: string, organizationKey?: KeyPair) => {
if (Token && organizationKey) {
return decryptMemberToken(Token, [organizationKey.privateKey], [organizationKey.publicKey]);
}
return keyPassword;
};
const getDecryptedUserKey = async (Key: tsKey, keyPassword: string, organizationKey?: KeyPair) => {
const { ID, PrivateKey } = Key;
const userKeyPassword = await getUserKeyPassword(Key, keyPassword, organizationKey);
const privateKey = await CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: userKeyPassword });
const publicKey = await CryptoProxy.importPublicKey({
binaryKey: await CryptoProxy.exportPublicKey({ key: privateKey, format: 'binary' }),
});
return {
ID,
privateKey,
publicKey,
};
};
export const getDecryptedUserKeys = async (
userKeys: tsKey[] = [],
keyPassword: string,
organizationKey?: KeyPair
): Promise<DecryptedKey[]> => {
if (userKeys.length === 0) {
return [];
}
// Attempts to first decrypt the primary key. If this fails, there's no reason to continue with the rest because something is broken.
const [primaryKey, ...restKeys] = userKeys;
const primaryKeyResult = await getDecryptedUserKey(primaryKey, keyPassword, organizationKey).catch(noop);
if (!primaryKeyResult) {
return [];
}
const restKeysResult = await Promise.all(
restKeys.map((restKey) => getDecryptedUserKey(restKey, keyPassword, organizationKey).catch(noop))
);
return [primaryKeyResult, ...restKeysResult].filter(isTruthy);
};
export const getDecryptedUserKeysHelper = async (user: User, keyPassword: string): Promise<DecryptedKey[]> => {
if (!user.OrganizationPrivateKey) {
return getDecryptedUserKeys(user.Keys, keyPassword);
}
const organizationKey = user.OrganizationPrivateKey
? await getDecryptedOrganizationKey(user.OrganizationPrivateKey, keyPassword).catch(noop)
: undefined;
if (!organizationKey) {
return [];
}
return getDecryptedUserKeys(user.Keys, keyPassword, organizationKey);
};
| 8,644 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/getInactiveKeys.ts | import { CryptoProxy } from '@proton/crypto';
import { DecryptedKey, InactiveKey, Key } from '../interfaces';
export const getInactiveKeys = async (Keys: Key[], decryptedKeys: DecryptedKey[]): Promise<InactiveKey[]> => {
const decryptedKeysIDs = new Set<string>(decryptedKeys.map(({ ID }) => ID));
const inactiveKeys = Keys.filter(({ ID }) => !decryptedKeysIDs.has(ID));
return Promise.all(
inactiveKeys.map(async (Key) => {
const publicKey = await CryptoProxy.importPublicKey({ armoredKey: Key.PublicKey }).catch(() => undefined);
return {
Key,
publicKey,
fingerprint: publicKey?.getFingerprint(),
};
})
);
};
| 8,645 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/getPrimaryKey.ts | import { KeyPair } from '../interfaces';
export const getPrimaryKey = (keys: KeyPair[] = []): KeyPair | undefined => {
return keys[0];
};
| 8,646 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/index.ts | export * from './add';
export * from './import';
export * from './reactivation';
export * from './keyFlags';
export * from './activateMemberAddressKeys';
export * from './addressKeyActions';
export * from './addressKeys';
export * from './getDecryptedAddressKeys';
export * from './getDecryptedUserKeys';
export * from './getDecryptedOrganizationKey';
export * from './organizationKeys';
export * from './keyImport';
export * from './generatePrivateMemberKeys';
export * from './signedKeyList';
export * from './setupKeys';
export * from './setupAddress';
export * from './setupAddressKeys';
export * from './keyMigration';
export * from './keyAlgorithm';
export * from './getPrimaryKey';
export * from './keys';
export * from './memberToken';
export * from './memberKeys';
export * from './resetKeys';
export * from './userKeys';
export * from './missingKeysMemberProcess';
export * from './missingKeysSelfProcess';
export { getInternalKeys } from './keySource';
export { getExternalKeys } from './keySource';
| 8,647 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/keyAlgorithm.ts | import { AlgorithmInfo } from '@proton/crypto';
import capitalize from '@proton/utils/capitalize';
import unique from '@proton/utils/unique';
import { EncryptionConfig, SimpleMap } from '../interfaces';
const CUSTOM_FORMATTED_ALGS: SimpleMap<string> = { elgamal: 'ElGamal' };
const ECC_ALGS = new Set(['ecdh', 'ecdsa', 'eddsa']);
export const isRSA = (algorithmName = '') => algorithmName.toLowerCase().startsWith('rsa');
export const isECC = (algorithmName = '') => ECC_ALGS.has(algorithmName.toLowerCase());
export const getFormattedAlgorithmName = ({ algorithm = '', bits, curve }: AlgorithmInfo = { algorithm: '' }) => {
// For RSA keys, the algorithm is one of 'rsaEncrypt', 'rsaSign' or 'rsaEncryptSign', for historical reason. We simply display 'RSA'.
const name = isRSA(algorithm) ? 'rsa' : algorithm;
if (isECC(name)) {
// Keys using curve 25519 have different curve names (ed25519 or curve25519), which we unify under 'Curve25519'
return `ECC (${capitalize(curve === 'ed25519' ? 'curve25519' : curve)})`;
}
const formattedName = CUSTOM_FORMATTED_ALGS[name] || name.toUpperCase();
return `${formattedName} (${bits})`;
};
/**
* Aggregate different algorithm information, returning a string including the list of unique key algo descriptors.
* @param {AlgorithmInfo[]} algorithmInfos
* @returns {String} formatted unique algorithm names. Different curves or key sizes result in separate entries, e.g.
* [{ name: 'rsa', bits: 2048 }, { name: 'rsa', bits: 4096 }] returns `RSA (2048), RSA (4096)`.
*/
export const getFormattedAlgorithmNames = (algorithmInfos: AlgorithmInfo[] = []) => {
const formattedAlgos = algorithmInfos.map(getFormattedAlgorithmName);
return unique(formattedAlgos).join(', ');
};
export const getAlgorithmExists = (algorithmInfos: AlgorithmInfo[] = [], encryptionConfig: EncryptionConfig) => {
return algorithmInfos.some(({ algorithm, curve, bits }) => {
if (isECC(algorithm)) {
return curve === encryptionConfig.curve;
}
if (isRSA(algorithm)) {
return bits === encryptionConfig.rsaBits;
}
return false;
});
};
| 8,648 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/keyFlags.ts | import { Address, ProcessedApiAddressKey } from '@proton/shared/lib/interfaces';
import { ADDRESS_FLAGS, ADDRESS_TYPE, KEY_FLAG } from '../constants';
import { clearBit, hasBit, setBit } from '../helpers/bitset';
export const setExternalFlags = (flags: number) => {
flags = setBit(flags, KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT);
flags = setBit(flags, KEY_FLAG.FLAG_EMAIL_NO_SIGN);
return flags;
};
export const clearExternalFlags = (flags: number) => {
flags = clearBit(flags, KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT);
flags = clearBit(flags, KEY_FLAG.FLAG_EMAIL_NO_SIGN);
return flags;
};
export const getDefaultKeyFlags = (address: Address | undefined) => {
let flags = KEY_FLAG.FLAG_NOT_OBSOLETE + KEY_FLAG.FLAG_NOT_COMPROMISED;
if (address?.Type === ADDRESS_TYPE.TYPE_EXTERNAL) {
flags = setExternalFlags(flags);
}
if (hasBit(address?.Flags, ADDRESS_FLAGS.FLAG_DISABLE_E2EE)) {
flags = setBit(flags, KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT);
}
if (hasBit(address?.Flags, ADDRESS_FLAGS.FLAG_DISABLE_EXPECTED_SIGNED)) {
flags = setBit(flags, KEY_FLAG.FLAG_EMAIL_NO_SIGN);
}
return flags;
};
export const getKeyHasFlagsToVerify = (flags: KEY_FLAG) => {
return hasBit(flags, KEY_FLAG.FLAG_NOT_COMPROMISED);
};
export const getKeyHasFlagsToEncrypt = (flags: KEY_FLAG) => {
return hasBit(flags, KEY_FLAG.FLAG_NOT_OBSOLETE);
};
export const supportsMail = (flags: number): Boolean => {
return !hasBit(flags, KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT);
};
export const getMailCapableKeys = (keys: ProcessedApiAddressKey[]) => {
return keys.filter(({ flags }) => supportsMail(flags));
};
| 8,649 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/keyImport.ts | import { CryptoProxy, KeyInfo } from '@proton/crypto';
import isTruthy from '@proton/utils/isTruthy';
import { readFileAsString } from '../helpers/file';
export interface ArmoredKeyWithInfo extends KeyInfo {
/**
* Armored key corresponding to the key info.
* This could be a decrypted private key (see `this.keyIsDecrypted`), so handle with care.
*/
armoredKey: string;
}
const ARMORED_KEY_EXPR =
/-----BEGIN PGP (PRIVATE|PUBLIC) KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP (PRIVATE|PUBLIC) KEY BLOCK-----/g;
export const parseArmoredKeys = (fileString: string) => {
return fileString.match(ARMORED_KEY_EXPR) || [];
};
export const parseKeys = (filesAsStrings: string[] = []) => {
const armoredKeys = parseArmoredKeys(filesAsStrings.join('\n'));
if (!armoredKeys.length) {
return [];
}
return Promise.all(
armoredKeys.map(async (armoredKey) => {
try {
const keyInfo = await CryptoProxy.getKeyInfo({ armoredKey });
const ArmoredKeyWithInfo = {
...keyInfo,
armoredKey,
};
return ArmoredKeyWithInfo;
} catch (e: any) {
// ignore errors
}
})
).then((result) => result.filter<ArmoredKeyWithInfo>(isTruthy));
};
export const parseKeyFiles = async (files: File[] = []) => {
const filesAsStrings = await Promise.all(files.map((file) => readFileAsString(file))).catch(() => []);
return parseKeys(filesAsStrings);
};
| 8,650 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/keyMigration.ts | import { CryptoProxy, PrivateKeyReference, toPublicKeyReference } from '@proton/crypto';
import isTruthy from '@proton/utils/isTruthy';
import noop from '@proton/utils/noop';
import { queryScopes } from '../api/auth';
import { getApiError, getIsConnectionIssue } from '../api/helpers/apiErrorHelper';
import { migrateAddressKeysRoute } from '../api/keys';
import { migrateMembersAddressKeysRoute } from '../api/memberKeys';
import { getAllMemberAddresses, getAllMembers, getMember } from '../api/members';
import { getOrganizationKeys } from '../api/organization';
import { MEMBER_PRIVATE, USER_ROLES } from '../constants';
import { ApiError } from '../fetch/ApiError';
import {
Address,
Api,
DecryptedKey,
KeyMigrationKTVerifier,
KeyTransparencyVerify,
Member,
Organization,
OrganizationKey,
PreAuthKTVerify,
SignedKeyList,
User,
} from '../interfaces';
import { generateAddressKeyTokens } from './addressKeys';
import { getDecryptedAddressKeys, getDecryptedAddressKeysHelper } from './getDecryptedAddressKeys';
import { getDecryptedOrganizationKey } from './getDecryptedOrganizationKey';
import { getDecryptedUserKeys, getDecryptedUserKeysHelper } from './getDecryptedUserKeys';
import { getPrimaryKey } from './getPrimaryKey';
import { OnSKLPublishSuccess, createSignedKeyListForMigration } from './signedKeyList';
export const getSentryError = (error: any): any => {
// Only interested in api errors where the API gave a valid error response, or run time errors.
if (error instanceof ApiError) {
const { message, code } = getApiError(error);
return message && code >= 400 && code < 500 ? message : null;
}
if (
!error ||
error.ignore ||
getIsConnectionIssue(error) ||
error.message === 'Failed to fetch' ||
error.message === 'Load failed' ||
error.message === 'Operation aborted' ||
error.name === 'AbortError'
) {
return;
}
return error;
};
export const getHasMigratedAddressKey = ({ Token, Signature }: { Token?: string; Signature?: string }): boolean => {
return !!Token && !!Signature;
};
export const getHasMigratedAddressKeys = (addresses: Address[]) => {
return addresses.some((address) => address.Keys?.some(getHasMigratedAddressKey));
};
export const getHasMemberMigratedAddressKeys = (memberAddresses: Address[], ownerAddresses: Address[]) => {
const primaryMemberAddress = memberAddresses[0];
return primaryMemberAddress?.Keys?.length > 0
? getHasMigratedAddressKeys(memberAddresses)
: getHasMigratedAddressKeys(ownerAddresses);
};
export interface MigrateAddressKeyPayload {
ID: string;
Token: string;
Signature: string;
PrivateKey: string;
}
export interface MigrateMemberAddressKeyPayload extends MigrateAddressKeyPayload {
OrgSignature: string;
}
interface MigrationResult<T extends MigrateAddressKeyPayload> {
SignedKeyLists: { [id: string]: SignedKeyList };
AddressKeys: T[];
}
interface AddressKeyMigrationValue<T extends MigrateAddressKeyPayload> {
Address: Address;
AddressKeys: T[];
SignedKeyList: SignedKeyList | undefined;
onSKLPublishSuccess: OnSKLPublishSuccess | undefined;
}
interface AddressesKeys {
address: Address;
keys: DecryptedKey[];
}
export function getAddressKeysMigration(
addressesKeys: AddressesKeys[],
userKey: PrivateKeyReference,
keyTransparencyVerify: KeyTransparencyVerify,
keyMigrationKTVerifier: KeyMigrationKTVerifier,
organizationKey: PrivateKeyReference
): Promise<AddressKeyMigrationValue<MigrateMemberAddressKeyPayload>[]>;
export function getAddressKeysMigration(
addressesKeys: AddressesKeys[],
userKey: PrivateKeyReference,
keyTransparencyVerify: KeyTransparencyVerify,
keyMigrationKTVerifier: KeyMigrationKTVerifier,
organizationKey?: PrivateKeyReference
): Promise<AddressKeyMigrationValue<MigrateAddressKeyPayload>[]>;
export function getAddressKeysMigration(
addressesKeys: AddressesKeys[],
userKey: PrivateKeyReference,
keyTransparencyVerify: KeyTransparencyVerify,
keyMigrationKTVerifier: KeyMigrationKTVerifier,
organizationKey?: PrivateKeyReference
) {
return Promise.all(
addressesKeys.map(async ({ address, keys }) => {
const migratedKeys = await Promise.all(
keys.map(async ({ ID, privateKey }) => {
const { token, encryptedToken, signature, organizationSignature } = await generateAddressKeyTokens(
userKey,
organizationKey
);
const privateKeyArmored = await CryptoProxy.exportPrivateKey({
privateKey,
passphrase: token,
});
return {
encryptedToken,
signature,
organizationSignature,
privateKey,
privateKeyArmored,
ID,
};
})
);
const migratedDecryptedKeys = await Promise.all(
migratedKeys.map(async ({ ID, privateKey }) => ({
ID,
privateKey,
publicKey: await toPublicKeyReference(privateKey),
}))
);
const [signedKeyList, onSKLPublishSuccess] = await createSignedKeyListForMigration(
address,
migratedDecryptedKeys,
keyTransparencyVerify,
keyMigrationKTVerifier
);
return {
Address: address,
SignedKeyList: signedKeyList,
onSKLPublishSuccess: onSKLPublishSuccess,
AddressKeys: migratedKeys.map((migratedKey) => {
return {
ID: migratedKey.ID,
PrivateKey: migratedKey.privateKeyArmored,
Token: migratedKey.encryptedToken,
Signature: migratedKey.signature,
...(migratedKey.organizationSignature
? { OrgSignature: migratedKey.organizationSignature }
: undefined),
};
}),
};
})
);
}
export function getAddressKeysMigrationPayload<T extends MigrateAddressKeyPayload>(
addressKeysMigration: AddressKeyMigrationValue<T>[]
) {
return addressKeysMigration.reduce<MigrationResult<T>>(
(acc, { AddressKeys, Address, SignedKeyList }) => {
// Some addresses may not have keys and thus won't have generated a signed key list
if (AddressKeys.length > 0) {
acc.AddressKeys = acc.AddressKeys.concat(AddressKeys);
if (SignedKeyList) {
acc.SignedKeyLists[Address.ID] = SignedKeyList;
}
}
return acc;
},
{ AddressKeys: [], SignedKeyLists: {} }
);
}
interface MigrateAddressKeysArguments {
keyPassword: string;
user: User;
addresses: Address[];
organizationKey?: OrganizationKey;
preAuthKTVerify: PreAuthKTVerify;
keyMigrationKTVerifier: KeyMigrationKTVerifier;
}
export async function migrateAddressKeys(
args: MigrateAddressKeysArguments & {
organizationKey: OrganizationKey;
}
): Promise<AddressKeyMigrationValue<MigrateMemberAddressKeyPayload>[]>;
export async function migrateAddressKeys(
args: MigrateAddressKeysArguments
): Promise<AddressKeyMigrationValue<MigrateAddressKeyPayload>[]>;
export async function migrateAddressKeys({
user,
addresses,
keyPassword,
organizationKey,
preAuthKTVerify,
keyMigrationKTVerifier,
}: MigrateAddressKeysArguments) {
const userKeys = await getDecryptedUserKeysHelper(user, keyPassword);
const primaryUserKey = getPrimaryKey(userKeys)?.privateKey;
if (!primaryUserKey) {
throw new Error('Missing primary private user key');
}
const addressesKeys = await Promise.all(
addresses.map(async (address) => {
return {
address,
keys: await getDecryptedAddressKeysHelper(address.Keys, user, userKeys, keyPassword),
};
})
);
const keyTransparencyVerify = preAuthKTVerify(userKeys);
if (!organizationKey) {
return getAddressKeysMigration(addressesKeys, primaryUserKey, keyTransparencyVerify, keyMigrationKTVerifier);
}
const decryptedOrganizationKeyResult = await getDecryptedOrganizationKey(
organizationKey?.PrivateKey || '',
keyPassword
).catch(noop);
if (!decryptedOrganizationKeyResult) {
const error = new Error('Failed to decrypt organization key');
(error as any).ignore = true;
throw error;
}
return getAddressKeysMigration(
addressesKeys,
primaryUserKey,
keyTransparencyVerify,
keyMigrationKTVerifier,
decryptedOrganizationKeyResult.privateKey
);
}
interface MigrateMemberAddressKeysArguments {
api: Api;
keyPassword: string;
timeout?: number;
user: User;
organization: Organization;
keyTransparencyVerify: KeyTransparencyVerify;
keyMigrationKTVerifier: KeyMigrationKTVerifier;
}
export async function migrateMemberAddressKeys({
api,
keyPassword,
timeout = 120000,
user,
organization,
keyTransparencyVerify,
keyMigrationKTVerifier,
}: MigrateMemberAddressKeysArguments) {
if (organization.ToMigrate !== 1) {
return false;
}
if (user.Role !== USER_ROLES.ADMIN_ROLE) {
return;
}
// NOTE: The API following calls are done in a waterfall to lower the amount of unnecessary requests.
// Ensure scope...
const { Scopes } = await api<{ Scopes: string[] }>(queryScopes());
if (!Scopes.includes('organization')) {
return;
}
const organizationKey = await api<OrganizationKey>(getOrganizationKeys());
// Ensure that the organization key can be decrypted...
const decryptedOrganizationKeyResult = await getDecryptedOrganizationKey(
organizationKey?.PrivateKey ?? '',
keyPassword
).catch(noop);
if (!decryptedOrganizationKeyResult?.privateKey) {
return;
}
// Ensure that there are members to migrate...
const members = await getAllMembers(api);
const membersToMigrate = members.filter(({ ToMigrate, Private, Self }) => {
return !Self && ToMigrate === 1 && Private === MEMBER_PRIVATE.READABLE;
});
if (!membersToMigrate.length) {
return;
}
for (const member of membersToMigrate) {
// Some members might not be setup.
if (!member.Keys?.length) {
continue;
}
const memberAddresses = await getAllMemberAddresses(api, member.ID);
const memberUserKeys = await getDecryptedUserKeys(member.Keys, '', decryptedOrganizationKeyResult);
const primaryMemberUserKey = getPrimaryKey(memberUserKeys)?.privateKey;
if (!primaryMemberUserKey) {
throw new Error('Not able to decrypt the primary member user key');
}
const memberAddressesKeys = (
await Promise.all(
memberAddresses.map(async (address) => {
const result = {
address,
keys: await getDecryptedAddressKeys(
address.Keys,
memberUserKeys,
'',
decryptedOrganizationKeyResult
),
};
// Some non-private members don't have keys generated
if (!result.keys.length) {
return;
}
return result;
})
)
).filter(isTruthy);
// Some members might not have keys setup for the address.
if (!memberAddressesKeys.length) {
continue;
}
const migratedKeys = await getAddressKeysMigration(
memberAddressesKeys,
primaryMemberUserKey,
keyTransparencyVerify,
keyMigrationKTVerifier,
decryptedOrganizationKeyResult.privateKey
);
const payload = await getAddressKeysMigrationPayload(migratedKeys);
if (payload) {
await api({ ...migrateMembersAddressKeysRoute({ MemberID: member.ID, ...payload }), timeout });
await Promise.all(
migratedKeys.map(({ onSKLPublishSuccess }) =>
onSKLPublishSuccess ? onSKLPublishSuccess() : Promise.resolve()
)
);
}
}
}
export const migrateUser = async ({
api,
user,
addresses,
keyPassword,
timeout = 120000,
preAuthKTVerify,
keyMigrationKTVerifier,
}: {
api: Api;
user: User;
addresses: Address[];
keyPassword: string;
timeout?: number;
preAuthKTVerify: PreAuthKTVerify;
keyMigrationKTVerifier: KeyMigrationKTVerifier;
}) => {
if (user.ToMigrate !== 1 || getHasMigratedAddressKeys(addresses)) {
return false;
}
if (user.Private === MEMBER_PRIVATE.READABLE && user.Role === USER_ROLES.MEMBER_ROLE) {
return false;
}
if (user.Private === MEMBER_PRIVATE.READABLE && user.Role === USER_ROLES.ADMIN_ROLE) {
const [selfMember, organizationKey] = await Promise.all([
api<{ Member: Member }>(getMember('me')).then(({ Member }) => Member),
api<OrganizationKey>(getOrganizationKeys()),
]);
const migratedKeys = await migrateAddressKeys({
user,
organizationKey,
addresses,
keyPassword,
keyMigrationKTVerifier,
preAuthKTVerify,
});
const payload = await getAddressKeysMigrationPayload(migratedKeys);
await api({
...migrateMembersAddressKeysRoute({ MemberID: selfMember.ID, ...payload }),
timeout,
});
await Promise.all(
migratedKeys.map(({ onSKLPublishSuccess }) =>
onSKLPublishSuccess ? onSKLPublishSuccess() : Promise.resolve()
)
);
return true;
}
const migratedKeys = await migrateAddressKeys({
user,
addresses,
keyPassword,
preAuthKTVerify,
keyMigrationKTVerifier,
});
const payload = await getAddressKeysMigrationPayload(migratedKeys);
await api({ ...migrateAddressKeysRoute(payload), timeout });
await Promise.all(
migratedKeys.map(({ onSKLPublishSuccess }) => (onSKLPublishSuccess ? onSKLPublishSuccess() : Promise.resolve()))
);
return true;
};
| 8,651 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/keySource.ts | import { ApiAddressKeySource, ProcessedApiAddressKey } from '../interfaces';
export const getInternalKeys = (keys: ProcessedApiAddressKey[]) => {
return keys.filter(({ source }) => source === ApiAddressKeySource.PROTON);
};
export const getExternalKeys = (keys: ProcessedApiAddressKey[]) => {
return keys.filter(({ source }) => source !== ApiAddressKeySource.PROTON);
};
| 8,652 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/keys.ts | import { CryptoProxy, KeyReference, PrivateKeyReference, PublicKeyReference } from '@proton/crypto';
import { computeKeyPassword, generateKeySalt } from '@proton/srp';
import { extractEmailFromUserID } from '../helpers/email';
import { Key, KeyPair, KeySalt as tsKeySalt } from '../interfaces';
export const generateKeySaltAndPassphrase = async (password: string) => {
const salt = generateKeySalt();
return {
salt,
passphrase: await computeKeyPassword(password, salt),
};
};
/**
* Given a list of keys and joining key salts, get the primary key and the corresponding key salt.
* @param Keys - Keys as received from the API
* @param KeySalts - KeySalts as received from the API
*/
export const getPrimaryKeyWithSalt = (Keys: Key[] = [], KeySalts: tsKeySalt[] = []) => {
const [{ ID, PrivateKey } = { ID: '', PrivateKey: '' }] = Keys;
const { KeySalt } = KeySalts.find(({ ID: keySaltID }) => ID === keySaltID) || {};
// Not verifying that KeySalt exists because of old auth versions.
return {
PrivateKey,
KeySalt,
};
};
export const splitKeys = (keys: Partial<KeyPair>[] = []) => {
return keys.reduce<{ privateKeys: PrivateKeyReference[]; publicKeys: PublicKeyReference[] }>(
(acc, { privateKey, publicKey }) => {
if (!privateKey || !publicKey) {
return acc;
}
acc.publicKeys.push(publicKey);
acc.privateKeys.push(privateKey);
return acc;
},
{ publicKeys: [], privateKeys: [] }
);
};
export const decryptPrivateKeyWithSalt = async ({
password,
keySalt,
PrivateKey,
}: {
password: string;
keySalt?: string;
PrivateKey: string;
}) => {
const keyPassword = keySalt ? await computeKeyPassword(password, keySalt) : password;
return CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: keyPassword });
};
export const getEmailFromKey = (key: KeyReference) => {
const [userID] = key.getUserIDs();
return extractEmailFromUserID(userID);
};
| 8,653 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/memberKeys.ts | import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import { getDefaultKeyFlags } from '@proton/shared/lib/keys/keyFlags';
import { createMemberKeyRoute, setupMemberKeyRoute } from '../api/memberKeys';
import { MEMBER_PRIVATE } from '../constants';
import {
Api,
DecryptedKey,
EncryptionConfig,
KeyTransparencyVerify,
Address as tsAddress,
Key as tsKey,
Member as tsMember,
} from '../interfaces';
import { srpVerify } from '../srp';
import { generateAddressKey, generateAddressKeyTokens } from './addressKeys';
import { getActiveKeyObject, getActiveKeys, getNormalizedActiveKeys, getPrimaryFlag } from './getActiveKeys';
import { getHasMemberMigratedAddressKeys } from './keyMigration';
import { generateKeySaltAndPassphrase } from './keys';
import { decryptMemberToken, encryptMemberToken, generateMemberToken } from './memberToken';
import { generateMemberAddressKey } from './organizationKeys';
import { getSignedKeyListWithDeferredPublish } from './signedKeyList';
import { generateUserKey } from './userKeys';
export const getDecryptedMemberKey = async ({ Token, PrivateKey }: tsKey, organizationKey: PrivateKeyReference) => {
if (!Token) {
throw new Error('Member token invalid');
}
const decryptedToken = await decryptMemberToken(Token, [organizationKey], [organizationKey]);
return CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: decryptedToken });
};
interface SetupMemberKeySharedArguments {
api: Api;
member: tsMember;
memberAddresses: tsAddress[];
password: string;
organizationKey: PrivateKeyReference;
encryptionConfig: EncryptionConfig;
keyTransparencyVerify: KeyTransparencyVerify;
}
export const setupMemberKeyLegacy = async ({
api,
member,
memberAddresses,
password,
organizationKey,
encryptionConfig,
keyTransparencyVerify,
}: SetupMemberKeySharedArguments) => {
const { salt: keySalt, passphrase: memberMailboxPassword } = await generateKeySaltAndPassphrase(password);
const AddressKeysWithOnSKLPublish = await Promise.all(
memberAddresses.map(async (address) => {
const { privateKey, privateKeyArmored } = await generateAddressKey({
email: address.Email,
passphrase: memberMailboxPassword,
encryptionConfig,
});
const memberKeyToken = generateMemberToken();
const privateKeyArmoredOrganization = await CryptoProxy.exportPrivateKey({
privateKey,
passphrase: memberKeyToken,
});
const organizationToken = await encryptMemberToken(memberKeyToken, organizationKey);
const newActiveKey = await getActiveKeyObject(privateKey, {
ID: 'tmp',
primary: 1,
flags: getDefaultKeyFlags(address),
});
const updatedActiveKeys = getNormalizedActiveKeys(address, [newActiveKey]);
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
return {
addressKey: {
AddressID: address.ID,
SignedKeyList,
UserKey: privateKeyArmored,
MemberKey: privateKeyArmoredOrganization,
Token: organizationToken,
},
onSKLPublishSuccess,
};
})
);
const AddressKeys = AddressKeysWithOnSKLPublish.map(({ addressKey }) => addressKey);
const PrimaryKey = {
UserKey: AddressKeys[0].UserKey,
MemberKey: AddressKeys[0].MemberKey,
Token: AddressKeys[0].Token,
};
await srpVerify({
api,
credentials: { password },
config: setupMemberKeyRoute({
MemberID: member.ID,
AddressKeys,
PrimaryKey,
KeySalt: keySalt,
}),
});
await Promise.all(
AddressKeysWithOnSKLPublish.map(({ onSKLPublishSuccess }) =>
onSKLPublishSuccess ? onSKLPublishSuccess() : Promise.resolve()
)
);
};
export const setupMemberKeyV2 = async ({
api,
member,
memberAddresses,
password,
organizationKey,
encryptionConfig,
keyTransparencyVerify,
}: SetupMemberKeySharedArguments) => {
const { salt: keySalt, passphrase: memberKeyPassword } = await generateKeySaltAndPassphrase(password);
const { privateKey: userPrivateKey, privateKeyArmored: userPrivateKeyArmored } = await generateUserKey({
passphrase: memberKeyPassword,
encryptionConfig,
});
const memberKeyToken = generateMemberToken();
const privateKeyArmoredOrganization = await CryptoProxy.exportPrivateKey({
privateKey: userPrivateKey,
passphrase: memberKeyToken,
});
const organizationToken = await encryptMemberToken(memberKeyToken, organizationKey);
const AddressKeysWithOnSKLPublish = await Promise.all(
memberAddresses.map(async (address) => {
const { token, signature, organizationSignature, encryptedToken } = await generateAddressKeyTokens(
userPrivateKey,
organizationKey
);
const { privateKey: addressPrivateKey, privateKeyArmored: addressPrivateKeyArmored } =
await generateAddressKey({
email: address.Email,
passphrase: token,
encryptionConfig,
});
const newActiveKey = await getActiveKeyObject(addressPrivateKey, {
ID: 'tmp',
primary: 1,
flags: getDefaultKeyFlags(address),
});
const updatedActiveKeys = getNormalizedActiveKeys(address, [newActiveKey]);
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
return {
addressKey: {
AddressID: address.ID,
SignedKeyList,
PrivateKey: addressPrivateKeyArmored,
Token: encryptedToken,
Signature: signature,
OrgSignature: organizationSignature,
},
onSKLPublishSuccess,
};
})
);
const AddressKeys = AddressKeysWithOnSKLPublish.map(({ addressKey }) => addressKey);
await srpVerify({
api,
credentials: { password },
config: setupMemberKeyRoute({
MemberID: member.ID,
AddressKeys,
UserKey: {
PrivateKey: userPrivateKeyArmored,
OrgPrivateKey: privateKeyArmoredOrganization,
OrgToken: organizationToken,
},
KeySalt: keySalt,
}),
});
await Promise.all(
AddressKeysWithOnSKLPublish.map(({ onSKLPublishSuccess }) =>
onSKLPublishSuccess ? onSKLPublishSuccess() : Promise.resolve()
)
);
};
export const getShouldSetupMemberKeys = (member: tsMember | undefined) => {
return !member?.Self && member?.Keys.length === 0 && member.Private === MEMBER_PRIVATE.READABLE;
};
interface SetupMemberKeyArguments extends SetupMemberKeySharedArguments {
ownerAddresses: tsAddress[];
}
export const setupMemberKeys = async ({ ownerAddresses, ...rest }: SetupMemberKeyArguments) => {
// During member key setup, no address has keys, so we ignore checking it
if (getHasMemberMigratedAddressKeys([], ownerAddresses)) {
return setupMemberKeyV2(rest);
}
return setupMemberKeyLegacy(rest);
};
interface CreateMemberAddressKeysLegacyArguments {
api: Api;
member: tsMember;
memberAddress: tsAddress;
memberAddressKeys: DecryptedKey[];
memberUserKey: PrivateKeyReference;
organizationKey: PrivateKeyReference;
encryptionConfig: EncryptionConfig;
keyTransparencyVerify: KeyTransparencyVerify;
}
export const createMemberAddressKeysLegacy = async ({
api,
member,
memberAddress,
memberAddressKeys,
memberUserKey,
organizationKey,
encryptionConfig,
keyTransparencyVerify,
}: CreateMemberAddressKeysLegacyArguments) => {
const { privateKey, activationToken, privateKeyArmored, privateKeyArmoredOrganization, organizationToken } =
await generateMemberAddressKey({
email: memberAddress.Email,
primaryKey: memberUserKey,
organizationKey,
encryptionConfig,
});
const activeKeys = await getActiveKeys(
memberAddress,
memberAddress.SignedKeyList,
memberAddress.Keys,
memberAddressKeys
);
const newActiveKey = await getActiveKeyObject(privateKey, {
ID: 'tmp',
primary: getPrimaryFlag(activeKeys),
flags: getDefaultKeyFlags(memberAddress),
});
const updatedActiveKeys = getNormalizedActiveKeys(memberAddress, [...activeKeys, newActiveKey]);
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
memberAddress,
keyTransparencyVerify
);
const { primary } = newActiveKey;
const { MemberKey } = await api(
createMemberKeyRoute({
MemberID: member.ID,
AddressID: memberAddress.ID,
Activation: activationToken,
UserKey: privateKeyArmored,
Token: organizationToken,
MemberKey: privateKeyArmoredOrganization,
Primary: primary,
SignedKeyList,
})
);
await onSKLPublishSuccess();
newActiveKey.ID = MemberKey.ID;
return updatedActiveKeys;
};
interface CreateMemberAddressKeysV2Arguments {
api: Api;
member: tsMember;
memberAddress: tsAddress;
memberAddressKeys: DecryptedKey[];
memberUserKey: PrivateKeyReference;
organizationKey: PrivateKeyReference;
encryptionConfig: EncryptionConfig;
keyTransparencyVerify: KeyTransparencyVerify;
}
export const createMemberAddressKeysV2 = async ({
api,
member,
memberAddress,
memberAddressKeys,
memberUserKey,
organizationKey,
encryptionConfig,
keyTransparencyVerify,
}: CreateMemberAddressKeysV2Arguments) => {
const { token, signature, organizationSignature, encryptedToken } = await generateAddressKeyTokens(
memberUserKey,
organizationKey
);
const { privateKey: addressPrivateKey, privateKeyArmored: addressPrivateKeyArmored } = await generateAddressKey({
email: memberAddress.Email,
passphrase: token,
encryptionConfig,
});
const activeKeys = await getActiveKeys(
memberAddress,
memberAddress.SignedKeyList,
memberAddress.Keys,
memberAddressKeys
);
const newActiveKey = await getActiveKeyObject(addressPrivateKey, {
ID: 'tmp',
primary: getPrimaryFlag(activeKeys),
flags: getDefaultKeyFlags(memberAddress),
});
const updatedActiveKeys = getNormalizedActiveKeys(memberAddress, [...activeKeys, newActiveKey]);
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
memberAddress,
keyTransparencyVerify
);
const { primary } = newActiveKey;
const { MemberKey } = await api(
createMemberKeyRoute({
MemberID: member.ID,
AddressID: memberAddress.ID,
PrivateKey: addressPrivateKeyArmored,
Token: encryptedToken,
Signature: signature,
OrgSignature: organizationSignature,
Primary: primary,
SignedKeyList,
})
);
await onSKLPublishSuccess();
newActiveKey.ID = MemberKey.ID;
return updatedActiveKeys;
};
| 8,654 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/memberToken.ts | import { CryptoProxy, PrivateKeyReference, PublicKeyReference, VERIFICATION_STATUS } from '@proton/crypto';
import { uint8ArrayToBase64String } from '../helpers/encoding';
/**
* Decrypts a member token with the organization private key
*/
export const decryptMemberToken = async (
token: string,
privateKeys: PrivateKeyReference[],
publicKeys: PublicKeyReference[]
) => {
const { data: decryptedToken, verified } = await CryptoProxy.decryptMessage({
armoredMessage: token,
decryptionKeys: privateKeys,
verificationKeys: publicKeys,
});
if (verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) {
const error = new Error('Signature verification failed');
error.name = 'SignatureError';
throw error;
}
return `${decryptedToken}`;
};
/**
* Generates the member token to decrypt its member key
*/
export const generateMemberToken = () => {
const token = crypto.getRandomValues(new Uint8Array(128));
return uint8ArrayToBase64String(token);
};
/**
* Encrypt the member key password with a key.
* @param token - The member key token in base64
* @param privateKey - The key to encrypt the token with
*/
export const encryptMemberToken = async (token: string, privateKey: PrivateKeyReference) => {
const { message: encryptedToken } = await CryptoProxy.encryptMessage({
textData: token,
stripTrailingSpaces: true,
encryptionKeys: [privateKey],
signingKeys: [privateKey],
});
return encryptedToken;
};
| 8,655 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/missingKeysMemberProcess.ts | import { PrivateKeyReference } from '@proton/crypto';
import { Address, Api, EncryptionConfig, KeyTransparencyVerify, Member } from '../interfaces';
import { getHasMemberMigratedAddressKeys } from './keyMigration';
import { createMemberAddressKeysLegacy, createMemberAddressKeysV2, getDecryptedMemberKey } from './memberKeys';
type OnUpdateCallback = (ID: string, update: { status: 'loading' | 'error' | 'ok'; result?: string }) => void;
interface MissingKeysMemberProcessArguments {
api: Api;
encryptionConfig: EncryptionConfig;
onUpdate: OnUpdateCallback;
organizationKey: PrivateKeyReference;
ownerAddresses: Address[];
member: Member;
memberAddresses: Address[];
memberAddressesToGenerate: Address[];
keyTransparencyVerify: KeyTransparencyVerify;
}
export const missingKeysMemberProcess = async ({
api,
encryptionConfig,
onUpdate,
ownerAddresses,
member,
memberAddresses,
memberAddressesToGenerate,
organizationKey,
keyTransparencyVerify,
}: MissingKeysMemberProcessArguments) => {
const PrimaryKey = member.Keys.find(({ Primary }) => Primary === 1);
if (!PrimaryKey) {
throw new Error('Member keys are not set up');
}
const hasMigratedAddressKeys = getHasMemberMigratedAddressKeys(memberAddresses, ownerAddresses);
const primaryMemberUserKey = await getDecryptedMemberKey(PrimaryKey, organizationKey);
return Promise.all(
memberAddressesToGenerate.map(async (memberAddress) => {
try {
onUpdate(memberAddress.ID, { status: 'loading' });
if (hasMigratedAddressKeys) {
await createMemberAddressKeysV2({
api,
member,
memberAddress,
memberAddressKeys: [], // Assume no keys exist for this address since we are in this modal.
encryptionConfig,
memberUserKey: primaryMemberUserKey,
organizationKey,
keyTransparencyVerify,
});
} else {
await createMemberAddressKeysLegacy({
api,
member,
memberAddress,
memberAddressKeys: [], // Assume no keys exist for this address since we are in this modal.
encryptionConfig,
memberUserKey: primaryMemberUserKey,
organizationKey,
keyTransparencyVerify,
});
}
onUpdate(memberAddress.ID, { status: 'ok' });
} catch (e: any) {
onUpdate(memberAddress.ID, { status: 'error', result: e.message });
}
})
);
};
| 8,656 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/missingKeysSelfProcess.ts | import { Address, Api, DecryptedKey, EncryptionConfig, KeyTransparencyVerify } from '../interfaces';
import { createAddressKeyLegacy, createAddressKeyV2 } from './add';
import { getPrimaryKey } from './getPrimaryKey';
import { getHasMigratedAddressKeys } from './keyMigration';
type OnUpdateCallback = (ID: string, update: { status: 'loading' | 'error' | 'ok'; result?: string }) => void;
interface MissingKeysSelfProcessArguments {
api: Api;
userKeys: DecryptedKey[];
encryptionConfig: EncryptionConfig;
addresses: Address[];
addressesToGenerate: Address[];
password: string;
onUpdate: OnUpdateCallback;
keyTransparencyVerify: KeyTransparencyVerify;
}
export const missingKeysSelfProcess = ({
api,
userKeys,
encryptionConfig,
addresses,
addressesToGenerate,
password,
onUpdate,
keyTransparencyVerify,
}: MissingKeysSelfProcessArguments) => {
const hasMigratedAddressKeys = getHasMigratedAddressKeys(addresses);
const primaryUserKey = getPrimaryKey(userKeys)?.privateKey;
if (!primaryUserKey) {
throw new Error('Missing primary user key');
}
return Promise.all(
addressesToGenerate.map(async (address) => {
try {
onUpdate(address.ID, { status: 'loading' });
if (hasMigratedAddressKeys) {
await createAddressKeyV2({
api,
address,
encryptionConfig,
userKey: primaryUserKey,
activeKeys: [],
keyTransparencyVerify,
});
} else {
await createAddressKeyLegacy({
api,
address,
encryptionConfig,
passphrase: password,
activeKeys: [],
keyTransparencyVerify,
});
}
onUpdate(address.ID, { status: 'ok' });
} catch (e: any) {
onUpdate(address.ID, { status: 'error', result: e.message });
}
})
);
};
| 8,657 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/organizationKeys.ts | import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import { computeKeyPassword, generateKeySalt } from '@proton/srp';
import isTruthy from '@proton/utils/isTruthy';
import { getAllMemberAddresses } from '../api/members';
import { UpdateOrganizationKeysPayloadLegacy, UpdateOrganizationKeysPayloadV2 } from '../api/organization';
import { Api, EncryptionConfig, KeyPair, Member } from '../interfaces';
import { encryptAddressKeyToken, generateAddressKey, getAddressKeyToken } from './addressKeys';
import { getPrimaryKey } from './getPrimaryKey';
import { splitKeys } from './keys';
import { decryptMemberToken, encryptMemberToken, generateMemberToken } from './memberToken';
export const getBackupKeyData = async ({
backupPassword,
organizationKey,
}: {
backupPassword: string;
organizationKey: PrivateKeyReference;
}) => {
const backupKeySalt = generateKeySalt();
const backupKeyPassword = await computeKeyPassword(backupPassword, backupKeySalt);
const backupArmoredPrivateKey = await CryptoProxy.exportPrivateKey({
privateKey: organizationKey,
passphrase: backupKeyPassword,
});
return {
backupKeySalt,
backupArmoredPrivateKey,
};
};
export const ORGANIZATION_USERID = '[email protected]';
interface GenerateOrganizationKeysArguments {
keyPassword: string;
backupPassword: string;
encryptionConfig: EncryptionConfig;
}
export const generateOrganizationKeys = async ({
keyPassword,
backupPassword,
encryptionConfig,
}: GenerateOrganizationKeysArguments) => {
const privateKey = await CryptoProxy.generateKey({
userIDs: [{ name: ORGANIZATION_USERID, email: ORGANIZATION_USERID }],
...encryptionConfig,
});
const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase: keyPassword });
return {
privateKey,
privateKeyArmored,
...(await getBackupKeyData({ backupPassword, organizationKey: privateKey })),
};
};
export const reformatOrganizationKey = async (privateKey: PrivateKeyReference, passphrase: string) => {
const reformattedPrivateKey = await CryptoProxy.reformatKey({
userIDs: [{ name: ORGANIZATION_USERID, email: ORGANIZATION_USERID }],
privateKey: privateKey,
});
const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey: reformattedPrivateKey, passphrase });
return { privateKey: reformattedPrivateKey, privateKeyArmored };
};
interface ReEncryptOrganizationTokens {
api: Api;
publicMembers: Member[];
oldOrganizationKey: KeyPair;
newOrganizationKey: KeyPair;
}
export const getReEncryptedPublicMemberTokensPayloadV2 = async ({
api,
publicMembers = [],
oldOrganizationKey,
newOrganizationKey,
}: ReEncryptOrganizationTokens) => {
const result: UpdateOrganizationKeysPayloadV2['Members'] = [];
// Performed iteratively to not spam the API
for (const member of publicMembers) {
if (!member.Keys?.length) {
continue;
}
const memberAddresses = await getAllMemberAddresses(api, member.ID);
const memberKeysAndReEncryptedTokens = await Promise.all(
member.Keys.map(async ({ Token, PrivateKey, ID }) => {
if (!Token) {
throw new Error('Missing token');
}
const memberKeyToken = await decryptMemberToken(
Token,
[oldOrganizationKey.privateKey],
[oldOrganizationKey.publicKey]
);
const reEncryptedMemberKeyToken = await encryptMemberToken(
memberKeyToken,
newOrganizationKey.privateKey
);
const privateKey = await CryptoProxy.importPrivateKey({
armoredKey: PrivateKey,
passphrase: memberKeyToken,
});
const publicKey = await CryptoProxy.importPublicKey({
armoredKey: await CryptoProxy.exportPublicKey({ key: privateKey }),
});
return {
ID,
privateKey,
publicKey,
token: reEncryptedMemberKeyToken,
};
})
);
const memberUserKeys = splitKeys(memberKeysAndReEncryptedTokens);
const primaryMemberUserKey = getPrimaryKey(memberKeysAndReEncryptedTokens)?.privateKey;
if (!primaryMemberUserKey) {
throw new Error('Missing primary private user key');
}
const AddressKeyTokens = (
await Promise.all(
memberAddresses.map(async (address) => {
if (!address.Keys?.length) {
return;
}
return Promise.all(
address.Keys.map(async ({ ID, Token, Signature, PrivateKey }) => {
if (!Token) {
throw new Error('Missing token');
}
const token = await getAddressKeyToken({
Token,
Signature,
organizationKey: oldOrganizationKey,
privateKeys: memberUserKeys.privateKeys,
publicKeys: memberUserKeys.publicKeys,
});
await CryptoProxy.clearKey({
// To ensure it can get decrypted with this token
key: await CryptoProxy.importPrivateKey({
armoredKey: PrivateKey,
passphrase: token,
}),
});
const result = await encryptAddressKeyToken({
token,
organizationKey: newOrganizationKey.privateKey,
userKey: primaryMemberUserKey,
});
return {
ID,
Token: result.encryptedToken,
Signature: result.signature,
OrgSignature: result.organizationSignature!,
};
})
);
})
)
)
.filter(isTruthy)
.flat();
result.push({
ID: member.ID,
UserKeyTokens: memberKeysAndReEncryptedTokens.map(({ ID, token }) => {
return {
ID,
Token: token,
};
}),
AddressKeyTokens,
});
}
return result;
};
export const getReEncryptedPublicMemberTokensPayloadLegacy = async ({
publicMembers = [],
api,
oldOrganizationKey,
newOrganizationKey,
}: ReEncryptOrganizationTokens) => {
let result: UpdateOrganizationKeysPayloadLegacy['Tokens'] = [];
// Performed iteratively to not spam the API
for (const member of publicMembers) {
if (!member.Keys?.length) {
continue;
}
const memberAddresses = await getAllMemberAddresses(api, member.ID);
const memberUserAndAddressKeys = memberAddresses.reduce((acc, { Keys: AddressKeys }) => {
return acc.concat(AddressKeys);
}, member.Keys);
const memberResult = await Promise.all(
memberUserAndAddressKeys.map(async ({ ID, Token }) => {
if (!Token) {
throw new Error('Missing Token, should never happen');
}
const memberKeyToken = await decryptMemberToken(
Token,
[oldOrganizationKey.privateKey],
[oldOrganizationKey.publicKey]
);
const reEncryptedMemberKeyToken = await encryptMemberToken(
memberKeyToken,
newOrganizationKey.privateKey
);
return { ID, Token: reEncryptedMemberKeyToken };
})
);
result = result.concat(memberResult);
}
return result;
};
/**
* Generate member address for non-private users.
* It requires that the user has been set up with a primary key first.
* @param address - The address to generate keys for.
* @param primaryKey - The primary key of the member.
* @param organizationKey - The organization key.
* @param encryptionConfig - The selected encryption config.
*/
interface GenerateMemberAddressKeyArguments {
email: string;
primaryKey: PrivateKeyReference;
organizationKey: PrivateKeyReference;
encryptionConfig: EncryptionConfig;
}
export const generateMemberAddressKey = async ({
email,
primaryKey,
organizationKey,
encryptionConfig,
}: GenerateMemberAddressKeyArguments) => {
const memberKeyToken = generateMemberToken();
const orgKeyToken = generateMemberToken();
const { privateKey, privateKeyArmored } = await generateAddressKey({
email,
passphrase: memberKeyToken,
encryptionConfig,
});
const privateKeyArmoredOrganization = await CryptoProxy.exportPrivateKey({
privateKey,
passphrase: orgKeyToken,
});
const [activationToken, organizationToken] = await Promise.all([
encryptMemberToken(memberKeyToken, primaryKey),
encryptMemberToken(orgKeyToken, organizationKey),
]);
return {
privateKey,
privateKeyArmored,
activationToken,
privateKeyArmoredOrganization,
organizationToken,
};
};
| 8,658 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/publicKeys.ts | import { c } from 'ttag';
import { CryptoProxy, PublicKeyReference, serverTime } from '@proton/crypto';
import { KEY_FLAG, MIME_TYPES_MORE, PGP_SCHEMES_MORE, RECIPIENT_TYPES } from '../constants';
import { hasBit } from '../helpers/bitset';
import { canonicalizeEmailByGuess, canonicalizeInternalEmail, extractEmailFromUserID } from '../helpers/email';
import { toBitMap } from '../helpers/object';
import { ApiKeysConfig, ContactPublicKeyModel, ProcessedApiKey, PublicKeyConfigs, PublicKeyModel } from '../interfaces';
import { getKeyHasFlagsToEncrypt } from './keyFlags';
const { TYPE_INTERNAL } = RECIPIENT_TYPES;
const getIsFullyProcessedApiKey = (key: ProcessedApiKey): key is Required<ProcessedApiKey> => {
return !!key.publicKey;
};
/**
* Check if some API key data belongs to an internal user
*/
export const getIsInternalUser = ({ RecipientType }: ApiKeysConfig): boolean => RecipientType === TYPE_INTERNAL;
/**
* Test if no key is enabled
*/
export const isDisabledUser = (config: ApiKeysConfig): boolean =>
getIsInternalUser(config) && config.publicKeys.every(({ flags }) => !getKeyHasFlagsToEncrypt(flags));
export const getEmailMismatchWarning = (
publicKey: PublicKeyReference,
emailAddress: string,
isInternal: boolean
): string[] => {
const canonicalEmail = isInternal
? canonicalizeInternalEmail(emailAddress)
: canonicalizeEmailByGuess(emailAddress);
const userIDs = publicKey.getUserIDs();
const keyEmails = userIDs.reduce<string[]>((acc, userID) => {
const email = extractEmailFromUserID(userID) || userID;
// normalize the email
acc.push(email);
return acc;
}, []);
const canonicalKeyEmails = keyEmails.map((email) =>
isInternal ? canonicalizeInternalEmail(email) : canonicalizeEmailByGuess(email)
);
if (!canonicalKeyEmails.includes(canonicalEmail)) {
const keyUserIds = keyEmails.join(', ');
return [c('PGP key warning').t`Email address not found among user ids defined in sending key (${keyUserIds})`];
}
return [];
};
/**
* Sort list of keys retrieved from the API. Trusted keys take preference.
* For two keys such that both are either trusted or not, non-verify-only keys take preference
*/
export const sortApiKeys = ({
keys = [],
obsoleteFingerprints,
compromisedFingerprints,
trustedFingerprints,
}: {
keys: PublicKeyReference[];
obsoleteFingerprints: Set<string>;
compromisedFingerprints: Set<string>;
trustedFingerprints: Set<string>;
}): PublicKeyReference[] =>
keys
.reduce<PublicKeyReference[][]>(
(acc, key) => {
const fingerprint = key.getFingerprint();
// calculate order through a bitmap
const index = toBitMap({
isObsolete: obsoleteFingerprints.has(fingerprint),
isCompromised: compromisedFingerprints.has(fingerprint),
isNotTrusted: !trustedFingerprints.has(fingerprint),
});
acc[index].push(key);
return acc;
},
Array.from({ length: 8 }).map(() => [])
)
.flat();
/**
* Sort list of pinned keys retrieved from the API. Keys that can be used for sending take preference
*/
export const sortPinnedKeys = ({
keys = [],
obsoleteFingerprints,
compromisedFingerprints,
encryptionCapableFingerprints,
}: {
keys: PublicKeyReference[];
obsoleteFingerprints: Set<string>;
compromisedFingerprints: Set<string>;
encryptionCapableFingerprints: Set<string>;
}): PublicKeyReference[] =>
keys
.reduce<PublicKeyReference[][]>(
(acc, key) => {
const fingerprint = key.getFingerprint();
// calculate order through a bitmap
const index = toBitMap({
isObsolete: obsoleteFingerprints.has(fingerprint),
isCompromised: compromisedFingerprints.has(fingerprint),
cannotSend: !encryptionCapableFingerprints.has(fingerprint),
});
acc[index].push(key);
return acc;
},
Array.from({ length: 8 }).map(() => [])
)
.flat();
/**
* Given a public key, return true if it is capable of encrypting messages.
* This includes checking that the key is neither expired nor revoked.
*/
export const getKeyEncryptionCapableStatus = async (publicKey: PublicKeyReference, timestamp?: number) => {
const now = timestamp || +serverTime();
return CryptoProxy.canKeyEncrypt({ key: publicKey, date: new Date(now) });
};
/**
* Check if a public key is valid for sending according to the information stored in a public key model
* We rely only on the fingerprint of the key to do this check
*/
export const getIsValidForSending = (fingerprint: string, publicKeyModel: PublicKeyModel | ContactPublicKeyModel) => {
const { compromisedFingerprints, obsoleteFingerprints, encryptionCapableFingerprints } = publicKeyModel;
return (
!compromisedFingerprints.has(fingerprint) &&
!obsoleteFingerprints.has(fingerprint) &&
encryptionCapableFingerprints.has(fingerprint)
);
};
const getIsValidForVerifying = (fingerprint: string, compromisedFingerprints: Set<string>) => {
return !compromisedFingerprints.has(fingerprint);
};
export const getVerifyingKeys = (keys: PublicKeyReference[], compromisedFingerprints: Set<string>) => {
return keys.filter((key) => getIsValidForVerifying(key.getFingerprint(), compromisedFingerprints));
};
/**
* For a given email address and its corresponding public keys (retrieved from the API and/or the corresponding vCard),
* construct the contact public key model, which reflects the content of the vCard.
*/
export const getContactPublicKeyModel = async ({
emailAddress,
apiKeysConfig,
pinnedKeysConfig,
}: Omit<PublicKeyConfigs, 'mailSettings'>): Promise<ContactPublicKeyModel> => {
const {
pinnedKeys = [],
encryptToPinned,
encryptToUntrusted,
sign,
scheme: vcardScheme,
mimeType: vcardMimeType,
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
} = pinnedKeysConfig;
const trustedFingerprints = new Set<string>();
const encryptionCapableFingerprints = new Set<string>();
const obsoleteFingerprints = new Set<string>();
const compromisedFingerprints = new Set<string>();
// prepare keys retrieved from the API
const isInternalUser = getIsInternalUser(apiKeysConfig);
const isExternalUser = !isInternalUser;
const processedApiKeys = apiKeysConfig.publicKeys.filter(getIsFullyProcessedApiKey);
const apiKeys = processedApiKeys.map(({ publicKey }) => publicKey);
await Promise.all(
processedApiKeys.map(async ({ publicKey, flags }) => {
const fingerprint = publicKey.getFingerprint();
const canEncrypt = await getKeyEncryptionCapableStatus(publicKey);
if (canEncrypt) {
encryptionCapableFingerprints.add(fingerprint);
}
if (!hasBit(flags, KEY_FLAG.FLAG_NOT_COMPROMISED)) {
compromisedFingerprints.add(fingerprint);
}
if (!hasBit(flags, KEY_FLAG.FLAG_NOT_OBSOLETE)) {
obsoleteFingerprints.add(fingerprint);
}
})
);
// prepare keys retrieved from the vCard
await Promise.all(
pinnedKeys.map(async (publicKey) => {
const fingerprint = publicKey.getFingerprint();
const canEncrypt = await getKeyEncryptionCapableStatus(publicKey);
trustedFingerprints.add(fingerprint);
if (canEncrypt) {
encryptionCapableFingerprints.add(fingerprint);
}
})
);
const orderedPinnedKeys = sortPinnedKeys({
keys: pinnedKeys,
obsoleteFingerprints,
compromisedFingerprints,
encryptionCapableFingerprints,
});
const orderedApiKeys = sortApiKeys({
keys: apiKeys,
trustedFingerprints,
obsoleteFingerprints,
compromisedFingerprints,
});
let encrypt: boolean | undefined = undefined;
if (pinnedKeys.length > 0) {
// Some old contacts with pinned WKD keys did not store the `x-pm-encrypt` flag,
// since encryption was always enabled, so we treat an 'undefined' flag as 'true'.
encrypt = encryptToPinned !== false;
} else if (isExternalUser && apiKeys.length > 0) {
// Enable encryption by default for contacts with no `x-pm-encrypt-untrusted` flag.
encrypt = encryptToUntrusted !== false;
}
return {
encrypt,
sign,
scheme: vcardScheme || PGP_SCHEMES_MORE.GLOBAL_DEFAULT,
mimeType: vcardMimeType || MIME_TYPES_MORE.AUTOMATIC,
emailAddress,
publicKeys: {
apiKeys: orderedApiKeys,
pinnedKeys: orderedPinnedKeys,
verifyingPinnedKeys: getVerifyingKeys(orderedPinnedKeys, compromisedFingerprints),
},
isInternalWithDisabledE2EEForMail: !!apiKeysConfig.isInternalWithDisabledE2EEForMail,
trustedFingerprints,
obsoleteFingerprints,
compromisedFingerprints,
encryptionCapableFingerprints,
isPGPExternal: isExternalUser,
isPGPInternal: isInternalUser,
isPGPExternalWithWKDKeys: isExternalUser && !!apiKeys.length,
isPGPExternalWithoutWKDKeys: isExternalUser && !apiKeys.length,
pgpAddressDisabled: isDisabledUser(apiKeysConfig),
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
emailAddressWarnings: apiKeysConfig.Warnings,
emailAddressErrors: apiKeysConfig.Errors,
ktVerificationResult: apiKeysConfig.ktVerificationResult,
};
};
| 8,659 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/resetKeys.ts | import { DEFAULT_ENCRYPTION_CONFIG, ENCRYPTION_CONFIGS } from '../constants';
import { Address, AddressKeyPayloadV2, EncryptionConfig, PreAuthKTVerify } from '../interfaces';
import { generateAddressKey, generateAddressKeyTokens } from './addressKeys';
import { getActiveKeyObject, getNormalizedActiveKeys } from './getActiveKeys';
import { getDefaultKeyFlags } from './keyFlags';
import { OnSKLPublishSuccess, getSignedKeyListWithDeferredPublish } from './signedKeyList';
import { generateUserKey } from './userKeys';
export const getResetAddressesKeysV2 = async ({
addresses = [],
passphrase = '',
encryptionConfig = ENCRYPTION_CONFIGS[DEFAULT_ENCRYPTION_CONFIG],
preAuthKTVerify,
}: {
addresses: Address[];
passphrase: string;
encryptionConfig?: EncryptionConfig;
preAuthKTVerify: PreAuthKTVerify;
}): Promise<
| { userKeyPayload: string; addressKeysPayload: AddressKeyPayloadV2[]; onSKLPublishSuccess: OnSKLPublishSuccess }
| { userKeyPayload: undefined; addressKeysPayload: undefined; onSKLPublishSuccess: undefined }
> => {
if (!addresses.length) {
return { userKeyPayload: undefined, addressKeysPayload: undefined, onSKLPublishSuccess: undefined };
}
const { privateKey: userKey, privateKeyArmored: userKeyPayload } = await generateUserKey({
passphrase,
encryptionConfig,
});
const keyTransparencyVerify = preAuthKTVerify([
{ ID: userKey.getKeyID(), privateKey: userKey, publicKey: userKey },
]);
const addressKeysPayloadWithOnSKLPublish = await Promise.all(
addresses.map(async (address) => {
const { ID: AddressID, Email } = address;
const { token, encryptedToken, signature } = await generateAddressKeyTokens(userKey);
const { privateKey, privateKeyArmored } = await generateAddressKey({
email: Email,
passphrase: token,
encryptionConfig,
});
const newPrimaryKey = await getActiveKeyObject(privateKey, {
ID: 'tmp',
primary: 1,
flags: getDefaultKeyFlags(address),
});
const [signedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
getNormalizedActiveKeys(address, [newPrimaryKey]),
address,
keyTransparencyVerify
);
return {
addressKeyPayload: {
AddressID,
PrivateKey: privateKeyArmored,
SignedKeyList: signedKeyList,
Token: encryptedToken,
Signature: signature,
},
onSKLPublishSuccess,
};
})
);
const addressKeysPayload = addressKeysPayloadWithOnSKLPublish.map(({ addressKeyPayload }) => addressKeyPayload);
const onSKLPublishSuccessAll = async () => {
await Promise.all(addressKeysPayloadWithOnSKLPublish.map(({ onSKLPublishSuccess }) => onSKLPublishSuccess()));
};
return { userKeyPayload, addressKeysPayload, onSKLPublishSuccess: onSKLPublishSuccessAll };
};
| 8,660 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/sessionKey.ts | import { SessionKey } from '@proton/crypto';
import { AES256 } from '../constants';
import { base64StringToUint8Array } from '../helpers/encoding';
export const toSessionKey = (decryptedKeyPacket: string): SessionKey => {
return { algorithm: AES256, data: base64StringToUint8Array(decryptedKeyPacket) };
};
| 8,661 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/setupAddress.ts | import { c } from 'ttag';
import { AddressGeneration } from '@proton/components/containers/login/interface';
import { getLocalKey } from '@proton/shared/lib/api/auth';
import { queryAvailableDomains } from '@proton/shared/lib/api/domains';
import { getRequiresAddress, getRequiresProtonAddress } from '@proton/shared/lib/authentication/apps';
import { getKey } from '@proton/shared/lib/authentication/cryptoHelper';
import { LocalKeyResponse } from '@proton/shared/lib/authentication/interface';
import { getDecryptedBlob, getEncryptedBlob } from '@proton/shared/lib/authentication/sessionBlobCryptoHelper';
import { ADDRESS_TYPE, APP_NAMES, PRODUCT_BIT } from '@proton/shared/lib/constants';
import { hasBit } from '@proton/shared/lib/helpers/bitset';
import { getEmailParts, removePlusAliasLocalPart } from '@proton/shared/lib/helpers/email';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { isPrivate } from '@proton/shared/lib/user/helpers';
import noop from '@proton/utils/noop';
import { getAllAddresses } from '../api/addresses';
import { updateUsername } from '../api/settings';
import { getUser, queryCheckUsernameAvailability } from '../api/user';
import { Address, Api, PreAuthKTVerify, UserType, User as tsUser } from '../interfaces';
import { createAddressKeyLegacy, createAddressKeyV2 } from './add';
import { getDecryptedUserKeysHelper } from './getDecryptedUserKeys';
import { getPrimaryKey } from './getPrimaryKey';
import { getHasMigratedAddressKeys } from './keyMigration';
import { handleSetupAddress } from './setupAddressKeys';
import { handleSetupKeys } from './setupKeys';
export const getLocalPart = (email: string) => {
const [localPart] = getEmailParts(email);
return removePlusAliasLocalPart(localPart);
};
export enum ClaimableAddressType {
Fixed,
Any,
}
export interface ClaimableAddress {
username: string;
domain: string;
type: ClaimableAddressType;
}
export const getClaimableAddress = async ({
user,
api,
email = '',
domains,
}: {
user: tsUser;
api: Api;
email: string | undefined;
domains: string[];
}): Promise<ClaimableAddress> => {
const domain = domains[0];
// Username is already set, can't be changed.
if (user.Name) {
return {
username: user.Name,
domain,
type: ClaimableAddressType.Fixed,
};
}
const username = getLocalPart(email).trim();
await api(queryCheckUsernameAvailability(`${username}@${domain}`, true));
return { username, domain, type: ClaimableAddressType.Any };
};
export type AddressGenerationSetup =
| {
mode: 'ask';
}
| {
mode: 'setup';
loginPassword: string;
}
| {
mode: 'create';
keyPassword: string;
};
export interface AddressGenerationPayload {
username: string;
domain: string;
setup: AddressGenerationSetup;
preAuthKTVerify: PreAuthKTVerify;
}
export const getAddressSetupMode = ({
user,
keyPassword,
loginPassword,
}: {
user: tsUser;
keyPassword: string | undefined;
loginPassword: string | undefined;
}): AddressGenerationSetup => {
if (user.Keys.length > 0) {
if (!keyPassword) {
throw new Error('Missing key password, should never happen');
}
return {
mode: 'create',
keyPassword,
} as const;
}
if (!loginPassword) {
return {
mode: 'ask',
};
}
return {
mode: 'setup',
loginPassword,
};
};
export const getAddressGenerationSetup = async ({
user,
api,
addresses: maybeAddresses,
domains: maybeDomains,
loginPassword,
keyPassword,
}: {
user: tsUser;
api: Api;
addresses?: Address[];
domains?: string[];
loginPassword: string | undefined;
keyPassword: string | undefined;
}): Promise<AddressGeneration> => {
const [addresses, domains] = await Promise.all([
maybeAddresses || getAllAddresses(api),
maybeDomains || api<{ Domains: string[] }>(queryAvailableDomains()).then(({ Domains }) => Domains),
]);
const externalEmailAddress = addresses.find((address) => address.Type === ADDRESS_TYPE.TYPE_EXTERNAL);
const claimableAddress = await getClaimableAddress({
user,
api,
email: externalEmailAddress?.Email,
domains,
}).catch(noop);
return {
externalEmailAddress,
availableDomains: domains,
claimableAddress,
setup: getAddressSetupMode({
user,
loginPassword,
keyPassword,
}),
};
};
const handleSetupUsernameAndAddress = async ({
api,
username,
user,
domain,
}: {
api: Api;
username: string;
user: tsUser;
domain: string;
}) => {
if (!domain) {
throw new Error(c('Error').t`Domain not available, try again later`);
}
const hasSetUsername = !!user.Name;
// If the name is already set, fallback to what exists.
const actualUsername = hasSetUsername ? user.Name : username;
if (!hasSetUsername) {
await api(queryCheckUsernameAvailability(actualUsername));
await api(updateUsername({ Username: actualUsername }));
}
return handleSetupAddress({ api, domain, username: actualUsername });
};
export const handleCreateAddressAndKey = async ({
username,
domain,
api,
passphrase,
preAuthKTVerify,
}: {
username: string;
domain: string;
api: Api;
passphrase: string;
preAuthKTVerify: PreAuthKTVerify;
}) => {
if (!passphrase) {
throw new Error('Password required to generate keys');
}
const [user, addresses] = await Promise.all([
api<{ User: tsUser }>(getUser()).then(({ User }) => User),
getAllAddresses(api),
]);
const [address] = await handleSetupUsernameAndAddress({ api, username, user, domain });
const userKeys = await getDecryptedUserKeysHelper(user, passphrase);
const keyTransparencyVerify = preAuthKTVerify(userKeys);
if (getHasMigratedAddressKeys(addresses)) {
const primaryUserKey = getPrimaryKey(userKeys)?.privateKey;
if (!primaryUserKey) {
throw new Error('Missing primary user key');
}
await createAddressKeyV2({
api,
userKey: primaryUserKey,
address,
activeKeys: [],
keyTransparencyVerify,
});
} else {
await createAddressKeyLegacy({
api,
passphrase: passphrase,
address,
activeKeys: [],
keyTransparencyVerify,
});
}
return passphrase;
};
export const handleSetupAddressAndKey = async ({
username,
domain,
api,
password,
preAuthKTVerify,
}: {
username: string;
domain: string;
api: Api;
password: string;
preAuthKTVerify: PreAuthKTVerify;
}) => {
if (!password) {
throw new Error('Password required to setup keys');
}
const [user, addresses] = await Promise.all([
api<{ User: tsUser }>(getUser()).then(({ User }) => User),
getAllAddresses(api),
]);
const createdAddresses = await handleSetupUsernameAndAddress({ api, username, user, domain });
const addressesToSetup = [...addresses, ...createdAddresses];
return handleSetupKeys({
api,
addresses: addressesToSetup,
password,
preAuthKTVerify,
});
};
export const handleAddressGeneration = async ({
username,
domain,
setup,
api,
preAuthKTVerify,
}: AddressGenerationPayload & { api: Api }) => {
if (setup.mode === 'create') {
return handleCreateAddressAndKey({ username, domain, api, passphrase: setup.keyPassword, preAuthKTVerify });
}
if (setup.mode === 'setup') {
return handleSetupAddressAndKey({
username,
domain,
api,
password: setup.loginPassword,
preAuthKTVerify,
});
}
throw new Error('Unknown internal address setup mode');
};
export const getRequiresMailKeySetup = (user: tsUser | undefined) => {
if (!user) {
return false;
}
// The mail service product bit is used as a heuristic to determine if it's an account with addresses.
// If it was a VPN account, services would be 4
return (
user.Type === UserType.PROTON &&
!user.Keys.length &&
(user.Services === 0 || hasBit(user.Services, PRODUCT_BIT.Mail))
);
};
export const getIsVPNOnlyAccount = (user: tsUser | undefined) => {
if (!user) {
return false;
}
// The vpn service product bit is used as a heuristic to determine if it's an account without addresses
// NOTE: For vpn and pass bundle, Services gets incorrectly set to 12 = 4 + Pass
return (
user.Type === UserType.PROTON &&
!user.Keys.length &&
hasBit(user.Services, PRODUCT_BIT.VPN) &&
!hasBit(user.Services, PRODUCT_BIT.Mail)
);
};
export const getIsExternalAccount = (user: tsUser) => {
if (!user) {
return false;
}
return user.Type === UserType.EXTERNAL;
};
export const getRequiresPasswordSetup = (user: tsUser, setupVPN: boolean) => {
if (!user || user.Keys.length > 0 || !isPrivate(user)) {
return false;
}
return getRequiresMailKeySetup(user) || (getIsVPNOnlyAccount(user) && setupVPN) || getIsExternalAccount(user);
};
export const getRequiresAddressSetup = (toApp: APP_NAMES, user: tsUser) => {
if (!user || !isPrivate(user)) {
return false;
}
return (
(getRequiresProtonAddress(toApp) && getIsExternalAccount(user)) ||
(getRequiresAddress(toApp) && (getIsVPNOnlyAccount(user) || getRequiresMailKeySetup(user)))
);
};
interface SetupBlob {
loginPassword: string;
}
export const getEncryptedSetupBlob = async (api: Api, loginPassword: string) => {
const ClientKey = await api<LocalKeyResponse>(getLocalKey()).then(({ ClientKey }) => ClientKey);
const rawKey = base64StringToUint8Array(ClientKey);
const key = await getKey(rawKey);
const setupBlob: SetupBlob = {
loginPassword,
};
return getEncryptedBlob(key, JSON.stringify(setupBlob));
};
export const getDecryptedSetupBlob = async (api: Api, blob: string): Promise<SetupBlob | undefined> => {
const ClientKey = await api<LocalKeyResponse>(getLocalKey()).then(({ ClientKey }) => ClientKey);
const rawKey = base64StringToUint8Array(ClientKey);
const key = await getKey(rawKey);
const result = await getDecryptedBlob(key, blob);
try {
const json = JSON.parse(result);
if (!json?.loginPassword) {
return undefined;
}
return json;
} catch (e) {
return;
}
};
| 8,662 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/setupAddressKeys.ts | import { setupAddress as setupAddressRoute } from '../api/addresses';
import { Api, PreAuthKTVerify, Address as tsAddress } from '../interfaces';
import { handleSetupKeys } from './setupKeys';
interface SetupAddressArgs {
api: Api;
username: string;
domain: string;
}
export const handleSetupAddress = async ({ api, username, domain }: SetupAddressArgs) => {
if (!domain) {
throw new Error('Missing domain');
}
const { Address } = await api<{ Address: tsAddress }>(
setupAddressRoute({
Domain: domain,
DisplayName: username,
Signature: '',
})
);
return [Address];
};
interface SetupAddressKeysArgs {
password: string;
api: Api;
username: string;
addresses: tsAddress[];
domains: string[];
preAuthKTVerify: PreAuthKTVerify;
}
export const handleSetupAddressKeys = async ({
username,
password,
api,
addresses,
domains,
preAuthKTVerify,
}: SetupAddressKeysArgs) => {
const addressesToUse =
addresses?.length > 0 ? addresses : await handleSetupAddress({ api, domain: domains[0], username });
return handleSetupKeys({ api, addresses: addressesToUse, password, preAuthKTVerify });
};
| 8,663 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/setupKeys.ts | import { setupKeys } from '../api/keys';
import { Address, Api, PreAuthKTVerify } from '../interfaces';
import { srpVerify } from '../srp';
import { generateKeySaltAndPassphrase } from './keys';
import { getResetAddressesKeysV2 } from './resetKeys';
interface Args {
api: Api;
addresses: Address[];
password: string;
preAuthKTVerify: PreAuthKTVerify;
}
export const handleSetupKeys = async ({ api, addresses, password, preAuthKTVerify }: Args) => {
if (!addresses.length) {
throw new Error('An address is required to setup keys');
}
const { passphrase, salt } = await generateKeySaltAndPassphrase(password);
const { userKeyPayload, addressKeysPayload, onSKLPublishSuccess } = await getResetAddressesKeysV2({
addresses,
passphrase,
preAuthKTVerify,
});
if (!userKeyPayload || !addressKeysPayload) {
throw new Error('Invalid setup');
}
await srpVerify({
api,
credentials: { password },
config: setupKeys({
KeySalt: salt,
PrimaryKey: userKeyPayload,
AddressKeys: addressKeysPayload,
}),
});
if (onSKLPublishSuccess) {
await onSKLPublishSuccess();
}
return passphrase;
};
| 8,664 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/signedKeyList.ts | import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import { KT_SKL_SIGNING_CONTEXT } from '@proton/key-transparency/lib';
import isTruthy from '@proton/utils/isTruthy';
import { getIsAddressDisabled } from '../helpers/address';
import {
ActiveKey,
Address,
DecryptedKey,
KeyMigrationKTVerifier,
KeyTransparencyVerify,
SignedKeyList,
SignedKeyListItem,
} from '../interfaces';
import { SimpleMap } from '../interfaces/utils';
import { getActiveKeys, getNormalizedActiveKeys } from './getActiveKeys';
export const getSignedKeyListSignature = async (data: string, signingKey: PrivateKeyReference, date?: Date) => {
const signature = await CryptoProxy.signMessage({
textData: data,
stripTrailingSpaces: true,
signingKeys: [signingKey],
detached: true,
context: KT_SKL_SIGNING_CONTEXT,
date,
});
return signature;
};
export type OnSKLPublishSuccess = () => Promise<void>;
/**
* Generate the signed key list data and verify it for later commit to Key Transparency.
* The SKL is only considered in the later commit call if the returned OnSKLPublishSuccess closure
* has been called beforehand.
*/
export const getSignedKeyListWithDeferredPublish = async (
keys: ActiveKey[],
address: Address,
keyTransparencyVerify: KeyTransparencyVerify
): Promise<[SignedKeyList, OnSKLPublishSuccess]> => {
const transformedKeys = (
await Promise.all(
keys.map(async ({ privateKey, flags, primary, sha256Fingerprints, fingerprint }) => {
const result = await CryptoProxy.isE2EEForwardingKey({ key: privateKey });
if (result) {
return false;
}
return {
Primary: primary,
Flags: flags,
Fingerprint: fingerprint,
SHA256Fingerprints: sha256Fingerprints,
};
})
)
).filter(isTruthy);
const data = JSON.stringify(transformedKeys);
const signingKey = keys[0]?.privateKey;
if (!signingKey) {
throw new Error('Missing primary signing key');
}
// TODO: Could be filtered as well
const publicKeys = keys.map((key) => key.publicKey);
const signedKeyList: SignedKeyList = {
Data: data,
Signature: await getSignedKeyListSignature(data, signingKey),
};
const onSKLPublish = async () => {
if (!getIsAddressDisabled(address)) {
await keyTransparencyVerify(address, signedKeyList, publicKeys);
}
};
return [signedKeyList, onSKLPublish];
};
/**
* Generate the signed key list data and verify it for later commit to Key Transparency
*/
export const getSignedKeyList = async (
keys: ActiveKey[],
address: Address,
keyTransparencyVerify: KeyTransparencyVerify
): Promise<SignedKeyList> => {
const activeKeysWithoutForwarding = (
await Promise.all(
keys.map(async (key) => {
const result = await CryptoProxy.isE2EEForwardingKey({ key: key.privateKey });
return result ? false : key;
})
)
).filter(isTruthy);
const [signedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
activeKeysWithoutForwarding,
address,
keyTransparencyVerify
);
await onSKLPublishSuccess();
return signedKeyList;
};
export const createSignedKeyListForMigration = async (
address: Address,
decryptedKeys: DecryptedKey[],
keyTransparencyVerify: KeyTransparencyVerify,
keyMigrationKTVerifier: KeyMigrationKTVerifier
): Promise<[SignedKeyList | undefined, OnSKLPublishSuccess | undefined]> => {
let signedKeyList: SignedKeyList | undefined;
let onSKLPublishSuccess: OnSKLPublishSuccess | undefined;
if (!address.SignedKeyList || address.SignedKeyList.ObsolescenceToken) {
// Only create a new signed key list if the address does not have one already
// or the signed key list is obsolete.
await keyMigrationKTVerifier(address.Email, address.SignedKeyList);
const activeKeys = getNormalizedActiveKeys(
address,
await getActiveKeys(address, address.SignedKeyList, address.Keys, decryptedKeys)
);
if (activeKeys.length > 0) {
[signedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
activeKeys,
address,
keyTransparencyVerify
);
}
}
return [signedKeyList, onSKLPublishSuccess];
};
const signedKeyListItemParser = ({ Primary, Flags, Fingerprint, SHA256Fingerprints }: any) =>
(Primary === 0 || Primary === 1) &&
typeof Flags === 'number' &&
typeof Fingerprint === 'string' &&
Array.isArray(SHA256Fingerprints) &&
SHA256Fingerprints.every((fingerprint) => typeof fingerprint === 'string');
export const getParsedSignedKeyList = (data?: string | null): SignedKeyListItem[] | undefined => {
if (!data) {
return;
}
try {
const parsedData = JSON.parse(data);
if (!Array.isArray(parsedData)) {
return;
}
if (!parsedData.every(signedKeyListItemParser)) {
return;
}
return parsedData;
} catch (e: any) {
return undefined;
}
};
export const getSignedKeyListMap = (signedKeyListData?: SignedKeyListItem[]): SimpleMap<SignedKeyListItem> => {
if (!signedKeyListData) {
return {};
}
return signedKeyListData.reduce<SimpleMap<SignedKeyListItem>>((acc, cur) => {
acc[cur.Fingerprint] = cur;
return acc;
}, {});
};
| 8,665 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/upgradeKeysV2.ts | import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import { computeKeyPassword, generateKeySalt } from '@proton/srp';
import { UpgradeAddressKeyPayload, upgradeKeysRoute } from '../api/keys';
import { getOrganizationKeys } from '../api/organization';
import { USER_ROLES } from '../constants';
import { toMap } from '../helpers/object';
import {
Api,
CachedOrganizationKey,
DecryptedKey,
Key,
KeyMigrationKTVerifier,
KeyTransparencyVerify,
PreAuthKTVerify,
SignedKeyList,
User,
Address as tsAddress,
Key as tsKey,
OrganizationKey as tsOrganizationKey,
User as tsUser,
} from '../interfaces';
import { srpVerify } from '../srp';
import { generateAddressKeyTokens, reformatAddressKey } from './addressKeys';
import { getDecryptedAddressKeysHelper } from './getDecryptedAddressKeys';
import { getCachedOrganizationKey } from './getDecryptedOrganizationKey';
import { getDecryptedUserKeysHelper } from './getDecryptedUserKeys';
import { getHasMigratedAddressKeys } from './keyMigration';
import { reformatOrganizationKey } from './organizationKeys';
import { createSignedKeyListForMigration } from './signedKeyList';
import { USER_KEY_USERID } from './userKeys';
export const getV2KeyToUpgrade = (Key: tsKey) => {
return Key.Version < 3;
};
export const getV2KeysToUpgrade = (Keys?: tsKey[]) => {
if (!Keys) {
return [];
}
return Keys.filter(getV2KeyToUpgrade);
};
export const getHasV2KeysToUpgrade = (User: tsUser, Addresses: tsAddress[]) => {
return (
getV2KeysToUpgrade(User.Keys).length > 0 ||
Addresses.some((Address) => getV2KeysToUpgrade(Address.Keys).length > 0)
);
};
const reEncryptOrReformatKey = async (privateKey: PrivateKeyReference, Key: Key, email: string, passphrase: string) => {
if (Key && getV2KeyToUpgrade(Key)) {
return reformatAddressKey({
email,
passphrase,
privateKey,
});
}
const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase });
return { privateKey, privateKeyArmored };
};
const getReEncryptedKeys = (keys: DecryptedKey[], Keys: Key[], email: string, passphrase: string) => {
const keysMap = Keys.reduce<{ [key: string]: Key }>((acc, Key) => {
acc[Key.ID] = Key;
return acc;
}, {});
return Promise.all(
keys.map(async ({ privateKey, ID }) => {
const { privateKeyArmored } = await reEncryptOrReformatKey(privateKey, keysMap[ID], email, passphrase);
return {
ID,
PrivateKey: privateKeyArmored,
};
})
);
};
const getReformattedAddressKeysV2 = (
keys: DecryptedKey[],
Keys: Key[],
email: string,
userKey: PrivateKeyReference
) => {
const keysMap = Keys.reduce<{ [key: string]: Key }>((acc, Key) => {
acc[Key.ID] = Key;
return acc;
}, {});
return Promise.all(
keys.map(async ({ ID, privateKey: originalPrivateKey }) => {
const { token, encryptedToken, signature } = await generateAddressKeyTokens(userKey);
const { privateKey, privateKeyArmored } = await reEncryptOrReformatKey(
originalPrivateKey,
keysMap[ID],
email,
token
);
const publicKey = await CryptoProxy.importPublicKey({
binaryKey: await CryptoProxy.exportPublicKey({ key: privateKey, format: 'binary' }),
});
return {
decryptedKey: {
ID,
privateKey,
publicKey,
},
Key: {
ID,
PrivateKey: privateKeyArmored,
Token: encryptedToken,
Signature: signature,
},
};
})
);
};
interface UpgradeV2KeysLegacyArgs {
loginPassword: string;
clearKeyPassword: string;
api: Api;
isOnePasswordMode?: boolean;
user: User;
userKeys: DecryptedKey[];
organizationKey?: CachedOrganizationKey;
addressesKeys: {
address: tsAddress;
keys: DecryptedKey[];
}[];
}
export const upgradeV2KeysLegacy = async ({
user,
userKeys,
addressesKeys,
organizationKey,
loginPassword,
clearKeyPassword,
isOnePasswordMode,
api,
}: UpgradeV2KeysLegacyArgs) => {
const keySalt = generateKeySalt();
const newKeyPassword = await computeKeyPassword(clearKeyPassword, keySalt);
const [reformattedUserKeys, reformattedAddressesKeys, reformattedOrganizationKey] = await Promise.all([
getReEncryptedKeys(userKeys, user.Keys, USER_KEY_USERID, newKeyPassword),
Promise.all(
addressesKeys.map(({ address, keys }) => {
return getReEncryptedKeys(keys, address.Keys, address.Email, newKeyPassword);
})
),
organizationKey?.privateKey ? reformatOrganizationKey(organizationKey.privateKey, newKeyPassword) : undefined,
]);
const reformattedKeys = [...reformattedUserKeys, ...reformattedAddressesKeys.flat()];
const config = upgradeKeysRoute({
KeySalt: keySalt,
Keys: reformattedKeys,
OrganizationKey: reformattedOrganizationKey?.privateKeyArmored,
});
if (isOnePasswordMode) {
await srpVerify({
api,
credentials: { password: loginPassword },
config,
});
return newKeyPassword;
}
await api(config);
return newKeyPassword;
};
interface UpgradeV2KeysArgs extends UpgradeV2KeysLegacyArgs {
keyTransparencyVerify: KeyTransparencyVerify;
keyMigrationKTVerifier: KeyMigrationKTVerifier;
}
export const upgradeV2KeysV2 = async ({
user,
userKeys,
addressesKeys,
organizationKey,
loginPassword,
clearKeyPassword,
isOnePasswordMode,
api,
keyTransparencyVerify,
keyMigrationKTVerifier,
}: UpgradeV2KeysArgs) => {
if (!userKeys.length) {
return;
}
const keySalt = generateKeySalt();
const newKeyPassword: string = await computeKeyPassword(clearKeyPassword, keySalt);
const [reformattedUserKeys, reformattedOrganizationKey] = await Promise.all([
getReEncryptedKeys(userKeys, user.Keys, USER_KEY_USERID, newKeyPassword),
organizationKey?.privateKey ? reformatOrganizationKey(organizationKey.privateKey, newKeyPassword) : undefined,
]);
const primaryUserKey = await CryptoProxy.importPrivateKey({
armoredKey: reformattedUserKeys[0].PrivateKey,
passphrase: newKeyPassword,
});
const reformattedAddressesKeys = await Promise.all(
addressesKeys.map(async ({ address, keys }) => {
const reformattedAddressKeys = await getReformattedAddressKeysV2(
keys,
address.Keys,
address.Email,
primaryUserKey
);
const [decryptedKeys, addressKeys] = reformattedAddressKeys.reduce<
[DecryptedKey[], UpgradeAddressKeyPayload[]]
>(
(acc, cur) => {
acc[0].push(cur.decryptedKey);
acc[1].push(cur.Key);
return acc;
},
[[], []]
);
const [signedKeyList, onSKLPublishSuccess] = await createSignedKeyListForMigration(
address,
decryptedKeys,
keyTransparencyVerify,
keyMigrationKTVerifier
);
return {
address,
addressKeys,
signedKeyList: signedKeyList,
onSKLPublishSuccess: onSKLPublishSuccess,
};
})
);
const AddressKeys = reformattedAddressesKeys.map(({ addressKeys }) => addressKeys).flat();
const SignedKeyLists = reformattedAddressesKeys.reduce<{ [id: string]: SignedKeyList }>(
(acc, { address, signedKeyList }) => {
if (signedKeyList) {
acc[address.ID] = signedKeyList;
}
return acc;
},
{}
);
const config = upgradeKeysRoute({
KeySalt: keySalt,
UserKeys: reformattedUserKeys,
AddressKeys,
OrganizationKey: reformattedOrganizationKey?.privateKeyArmored,
SignedKeyLists,
});
await Promise.all(
reformattedAddressesKeys.map(({ onSKLPublishSuccess }) =>
onSKLPublishSuccess ? onSKLPublishSuccess() : Promise.resolve()
)
);
if (isOnePasswordMode) {
await srpVerify({
api,
credentials: { password: loginPassword },
config,
});
return newKeyPassword;
}
await api(config);
return newKeyPassword;
};
interface UpgradeV2KeysHelperArgs {
addresses: tsAddress[];
user: tsUser;
loginPassword: string;
clearKeyPassword: string;
keyPassword: string;
api: Api;
isOnePasswordMode?: boolean;
preAuthKTVerify: PreAuthKTVerify;
keyMigrationKTVerifier: KeyMigrationKTVerifier;
}
export const upgradeV2KeysHelper = async ({
user,
addresses,
loginPassword,
clearKeyPassword,
keyPassword,
isOnePasswordMode,
api,
preAuthKTVerify,
keyMigrationKTVerifier,
}: UpgradeV2KeysHelperArgs) => {
const userKeys = await getDecryptedUserKeysHelper(user, keyPassword);
const addressesKeys = await Promise.all(
addresses.map(async (address) => {
return {
address,
keys: await getDecryptedAddressKeysHelper(address.Keys, user, userKeys, keyPassword),
};
})
);
const organizationKey =
user.Role === USER_ROLES.ADMIN_ROLE
? await api<tsOrganizationKey>(getOrganizationKeys()).then((Key) => {
return getCachedOrganizationKey({ keyPassword, Key });
})
: undefined;
if (!clearKeyPassword || !loginPassword) {
throw new Error('Password required');
}
// Not allowed signed into member
if (user.OrganizationPrivateKey) {
return;
}
const userKeyMap = toMap(user.Keys, 'ID');
const hasDecryptedUserKeysToUpgrade = userKeys.some(({ privateKey, ID }) => {
const Key = userKeyMap[ID];
return Key && privateKey && getV2KeyToUpgrade(Key);
});
const hasDecryptedAddressKeyToUpgrade = addressesKeys.some(({ address, keys }) => {
const addressKeyMap = toMap(address.Keys, 'ID');
return keys.some(({ privateKey, ID }) => {
const Key = addressKeyMap[ID];
return Key && privateKey && getV2KeyToUpgrade(Key);
});
});
if (!hasDecryptedUserKeysToUpgrade && !hasDecryptedAddressKeyToUpgrade) {
return;
}
if (getHasMigratedAddressKeys(addresses)) {
const keyTransparencyVerify = preAuthKTVerify(userKeys);
return upgradeV2KeysV2({
api,
user,
userKeys,
addressesKeys,
organizationKey,
loginPassword,
clearKeyPassword,
isOnePasswordMode,
keyTransparencyVerify,
keyMigrationKTVerifier,
});
}
return upgradeV2KeysLegacy({
api,
user,
userKeys,
addressesKeys,
organizationKey,
loginPassword,
clearKeyPassword,
isOnePasswordMode,
});
};
| 8,666 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/userKeys.ts | import { GenerateAddressKeyArguments, generateAddressKey } from './addressKeys';
export const USER_KEY_USERID = '[email protected]';
export const generateUserKey = async (args: Omit<GenerateAddressKeyArguments, 'email' | 'name'>) => {
return generateAddressKey({ email: USER_KEY_USERID, ...args });
};
| 8,667 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/add/addAddressKeyHelper.ts | import { PrivateKeyReference } from '@proton/crypto';
import { getDefaultKeyFlags } from '@proton/shared/lib/keys';
import { createAddressKeyRoute, createAddressKeyRouteV2 } from '../../api/keys';
import { DEFAULT_ENCRYPTION_CONFIG, ENCRYPTION_CONFIGS } from '../../constants';
import { ActiveKey, Address, Api, EncryptionConfig, KeyTransparencyVerify } from '../../interfaces';
import { generateAddressKey, generateAddressKeyTokens } from '../addressKeys';
import { getActiveKeyObject, getNormalizedActiveKeys } from '../getActiveKeys';
import { getSignedKeyListWithDeferredPublish } from '../signedKeyList';
interface CreateAddressKeyLegacyArguments {
api: Api;
encryptionConfig?: EncryptionConfig;
address: Address;
passphrase: string;
activeKeys: ActiveKey[];
keyTransparencyVerify: KeyTransparencyVerify;
addressForwardingID?: string;
}
const removePrimary = (activeKey: ActiveKey): ActiveKey => {
if (activeKey.primary) {
return {
...activeKey,
primary: 0,
};
}
return activeKey;
};
export const createAddressKeyLegacy = async ({
api,
address,
encryptionConfig = ENCRYPTION_CONFIGS[DEFAULT_ENCRYPTION_CONFIG],
passphrase,
activeKeys,
keyTransparencyVerify,
addressForwardingID: AddressForwardingID,
}: CreateAddressKeyLegacyArguments) => {
const { privateKey, privateKeyArmored } = await generateAddressKey({
email: address.Email,
passphrase,
encryptionConfig,
});
const newActiveKey = await getActiveKeyObject(privateKey, {
ID: 'tmp',
primary: 1,
flags: getDefaultKeyFlags(address),
});
const updatedActiveKeys = getNormalizedActiveKeys(address, [newActiveKey, ...activeKeys.map(removePrimary)]);
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
const { Key } = await api(
createAddressKeyRoute({
AddressID: address.ID,
Primary: newActiveKey.primary,
PrivateKey: privateKeyArmored,
SignedKeyList,
AddressForwardingID,
})
);
await onSKLPublishSuccess();
newActiveKey.ID = Key.ID;
return [newActiveKey, updatedActiveKeys] as const;
};
interface CreateAddressKeyV2Arguments {
api: Api;
userKey: PrivateKeyReference;
encryptionConfig?: EncryptionConfig;
address: Address;
activeKeys: ActiveKey[];
keyTransparencyVerify: KeyTransparencyVerify;
}
export const createAddressKeyV2 = async ({
api,
userKey,
encryptionConfig = ENCRYPTION_CONFIGS[DEFAULT_ENCRYPTION_CONFIG],
address,
activeKeys,
keyTransparencyVerify,
}: CreateAddressKeyV2Arguments) => {
const { token, encryptedToken, signature } = await generateAddressKeyTokens(userKey);
const { privateKey, privateKeyArmored } = await generateAddressKey({
email: address.Email,
passphrase: token,
encryptionConfig,
});
const newActiveKey = await getActiveKeyObject(privateKey, {
ID: 'tmp',
primary: 1,
flags: getDefaultKeyFlags(address),
});
const updatedActiveKeys = getNormalizedActiveKeys(address, [newActiveKey, ...activeKeys.map(removePrimary)]);
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
const { Key } = await api(
createAddressKeyRouteV2({
AddressID: address.ID,
Primary: newActiveKey.primary,
PrivateKey: privateKeyArmored,
SignedKeyList,
Signature: signature,
Token: encryptedToken,
})
);
// Only once the SKL is successfully posted we add it to the KT commit state.
await onSKLPublishSuccess();
newActiveKey.ID = Key.ID;
return [newActiveKey, updatedActiveKeys] as const;
};
| 8,668 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/add/addKeysProcess.ts | import { CryptoProxy } from '@proton/crypto';
import { getReplacedAddressKeyTokens } from '@proton/shared/lib/keys';
import noop from '@proton/utils/noop';
import { createUserKeyRoute, replaceAddressTokens } from '../../api/keys';
import { DEFAULT_ENCRYPTION_CONFIG, ENCRYPTION_CONFIGS } from '../../constants';
import { Address, Api, DecryptedKey, EncryptionConfig, KeyTransparencyVerify, UserModel } from '../../interfaces';
import { storeDeviceRecovery } from '../../recoveryFile/deviceRecovery';
import { getActiveKeys } from '../getActiveKeys';
import { getPrimaryKey } from '../getPrimaryKey';
import { getHasMigratedAddressKeys } from '../keyMigration';
import { generateUserKey } from '../userKeys';
import { createAddressKeyLegacy, createAddressKeyV2 } from './addAddressKeyHelper';
interface AddAddressKeysProcessArguments {
api: Api;
addressKeys: DecryptedKey[];
userKeys: DecryptedKey[];
address: Address;
addresses: Address[];
encryptionConfig: EncryptionConfig;
keyPassword: string;
keyTransparencyVerify: KeyTransparencyVerify;
}
export const addAddressKeysProcess = async ({
api,
encryptionConfig,
addresses,
address,
addressKeys,
userKeys,
keyPassword,
keyTransparencyVerify,
}: AddAddressKeysProcessArguments) => {
const hasMigratedAddressKeys = getHasMigratedAddressKeys(addresses);
const activeKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, addressKeys);
if (hasMigratedAddressKeys) {
const userKey = getPrimaryKey(userKeys)?.privateKey;
if (!userKey) {
throw new Error('Missing primary user key');
}
return createAddressKeyV2({
api,
userKey,
encryptionConfig,
activeKeys,
address,
keyTransparencyVerify,
});
}
return createAddressKeyLegacy({
api,
address,
encryptionConfig,
passphrase: keyPassword,
activeKeys,
keyTransparencyVerify,
});
};
interface CreateAddressKeyLegacyArguments {
api: Api;
encryptionConfig?: EncryptionConfig;
user: UserModel;
userKeys: DecryptedKey[];
addresses: Address[];
passphrase: string;
isDeviceRecoveryAvailable?: boolean;
isDeviceRecoveryEnabled?: boolean;
call: () => Promise<void>;
}
export const addUserKeysProcess = async ({
api,
encryptionConfig = ENCRYPTION_CONFIGS[DEFAULT_ENCRYPTION_CONFIG],
user,
userKeys,
addresses,
passphrase,
isDeviceRecoveryAvailable,
isDeviceRecoveryEnabled,
call,
}: CreateAddressKeyLegacyArguments) => {
const { privateKey, privateKeyArmored } = await generateUserKey({
passphrase,
encryptionConfig,
});
await api(
createUserKeyRoute({
Primary: 1,
PrivateKey: privateKeyArmored,
})
);
if (getHasMigratedAddressKeys(addresses)) {
const replacedResult = await getReplacedAddressKeyTokens({ userKeys, addresses, privateKey });
if (replacedResult.AddressKeyTokens.length) {
await api(replaceAddressTokens(replacedResult)).catch(/*ignore failures */ noop);
}
}
// Store a new device recovery immediately to avoid having the storing trigger asynchronously which would cause red notification flashes
if (isDeviceRecoveryAvailable && isDeviceRecoveryEnabled) {
const publicKey = await CryptoProxy.importPublicKey({
binaryKey: await CryptoProxy.exportPublicKey({ key: privateKey, format: 'binary' }),
});
await storeDeviceRecovery({
api,
user,
userKeys: [{ ID: 'tmp-id', privateKey, publicKey }, ...userKeys],
});
}
await call();
return privateKey;
};
| 8,669 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/add/index.ts | export * from './addKeysProcess';
export * from './addAddressKeyHelper';
| 8,670 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/import/helper.ts | import { ActiveKey, InactiveKey } from '../../interfaces';
import { KeyReactivationData } from '../reactivation/interface';
import { KeyImportData } from './interface';
export const getFilteredImportRecords = (
keyImportRecords: KeyImportData[],
activeKeys: ActiveKey[],
inactiveKeys: InactiveKey[]
) => {
return keyImportRecords.reduce<[KeyReactivationData[], KeyImportData[], KeyImportData[]]>(
(acc, keyImportRecord) => {
const { privateKey: uploadedPrivateKey } = keyImportRecord;
const fingerprint = uploadedPrivateKey.getFingerprint();
const maybeInactiveKey = inactiveKeys.find(({ fingerprint: otherFingerprint }) => {
return otherFingerprint === fingerprint;
});
const maybeActiveKey = activeKeys.find(({ fingerprint: otherFingerprint }) => {
return otherFingerprint === fingerprint;
});
if (maybeActiveKey) {
acc[2].push(keyImportRecord);
} else if (maybeInactiveKey) {
acc[0].push({
id: keyImportRecord.id,
Key: maybeInactiveKey.Key,
privateKey: uploadedPrivateKey,
});
} else {
acc[1].push(keyImportRecord);
}
return acc;
},
[[], [], []]
);
};
| 8,671 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/import/importKeysProcess.ts | import { Address, DecryptedKey, KeyTransparencyVerify } from '../../interfaces';
import { getPrimaryKey } from '../getPrimaryKey';
import { getHasMigratedAddressKeys } from '../keyMigration';
import importKeysProcessLegacy, { ImportKeysProcessLegacyArguments } from './importKeysProcessLegacy';
import importKeysProcessV2, { ImportKeysProcessV2Arguments } from './importKeysProcessV2';
interface Arguments extends Omit<ImportKeysProcessV2Arguments, 'userKey'>, ImportKeysProcessLegacyArguments {
addresses: Address[];
userKeys: DecryptedKey[];
keyTransparencyVerify: KeyTransparencyVerify;
}
export const importKeysProcess = async ({
api,
userKeys,
address,
addressKeys,
addresses,
keyImportRecords,
keyPassword,
onImport,
keyTransparencyVerify,
}: Arguments) => {
const hasMigratedAddressKeys = getHasMigratedAddressKeys(addresses);
if (hasMigratedAddressKeys) {
const primaryPrivateUserKey = getPrimaryKey(userKeys)?.privateKey;
if (!primaryPrivateUserKey) {
throw new Error('Missing primary private user key');
}
return importKeysProcessV2({
api,
keyImportRecords,
keyPassword,
address,
addressKeys,
onImport,
userKey: primaryPrivateUserKey,
keyTransparencyVerify,
});
}
return importKeysProcessLegacy({
api,
keyImportRecords,
keyPassword,
address,
addressKeys,
onImport,
keyTransparencyVerify,
});
};
| 8,672 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/import/importKeysProcessLegacy.ts | import { CryptoProxy } from '@proton/crypto';
import { getDefaultKeyFlags } from '@proton/shared/lib/keys';
import { createAddressKeyRoute } from '../../api/keys';
import { Address, Api, DecryptedKey, KeyTransparencyVerify } from '../../interfaces';
import { getActiveKeyObject, getActiveKeys, getNormalizedActiveKeys, getPrimaryFlag } from '../getActiveKeys';
import { getInactiveKeys } from '../getInactiveKeys';
import reactivateKeysProcessLegacy from '../reactivation/reactivateKeysProcessLegacy';
import { getSignedKeyListWithDeferredPublish } from '../signedKeyList';
import { getFilteredImportRecords } from './helper';
import { KeyImportData, OnKeyImportCallback } from './interface';
export interface ImportKeysProcessLegacyArguments {
api: Api;
keyImportRecords: KeyImportData[];
onImport: OnKeyImportCallback;
keyPassword: string;
address: Address;
addressKeys: DecryptedKey[];
keyTransparencyVerify: KeyTransparencyVerify;
}
const importKeysProcessLegacy = async ({
api,
keyImportRecords,
keyPassword,
onImport,
address,
addressKeys,
keyTransparencyVerify,
}: ImportKeysProcessLegacyArguments) => {
const activeKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, addressKeys);
const inactiveKeys = await getInactiveKeys(address.Keys, activeKeys);
const [keysToReactivate, keysToImport, existingKeys] = getFilteredImportRecords(
keyImportRecords,
activeKeys,
inactiveKeys
);
existingKeys.forEach((keyImportRecord) => {
onImport(keyImportRecord.id, new Error('Key already active'));
});
let mutableActiveKeys = activeKeys;
for (const keyImportRecord of keysToImport) {
try {
const { privateKey } = keyImportRecord;
const privateKeyArmored = await CryptoProxy.exportPrivateKey({
privateKey,
passphrase: keyPassword,
});
const newActiveKey = await getActiveKeyObject(privateKey, {
ID: 'tmp',
primary: getPrimaryFlag(mutableActiveKeys),
flags: getDefaultKeyFlags(address),
});
const updatedActiveKeys = getNormalizedActiveKeys(address, [...mutableActiveKeys, newActiveKey]);
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
const { Key } = await api(
createAddressKeyRoute({
AddressID: address.ID,
Primary: newActiveKey.primary,
PrivateKey: privateKeyArmored,
SignedKeyList,
})
);
// Only once the SKL is successfully posted we add it to the KT commit state.
await onSKLPublishSuccess();
// Mutably update the key with the latest value from the real ID.
newActiveKey.ID = Key.ID;
mutableActiveKeys = updatedActiveKeys;
onImport(keyImportRecord.id, 'ok');
} catch (e: any) {
onImport(keyImportRecord.id, e);
}
}
await reactivateKeysProcessLegacy({
api,
keyPassword,
keyReactivationRecords: [
{
address,
keys: mutableActiveKeys,
keysToReactivate,
},
],
onReactivation: onImport,
keyTransparencyVerify,
});
};
export default importKeysProcessLegacy;
| 8,673 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/import/importKeysProcessV2.ts | import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import { getDefaultKeyFlags } from '@proton/shared/lib/keys';
import { createAddressKeyRouteV2 } from '../../api/keys';
import { Address, Api, DecryptedKey, KeyTransparencyVerify } from '../../interfaces';
import { generateAddressKeyTokens } from '../addressKeys';
import { getActiveKeyObject, getActiveKeys, getNormalizedActiveKeys, getPrimaryFlag } from '../getActiveKeys';
import { getInactiveKeys } from '../getInactiveKeys';
import { reactivateAddressKeysV2 } from '../reactivation/reactivateKeysProcessV2';
import { getSignedKeyListWithDeferredPublish } from '../signedKeyList';
import { getFilteredImportRecords } from './helper';
import { KeyImportData, OnKeyImportCallback } from './interface';
export interface ImportKeysProcessV2Arguments {
api: Api;
keyImportRecords: KeyImportData[];
onImport: OnKeyImportCallback;
keyPassword: string;
address: Address;
addressKeys: DecryptedKey[];
userKey: PrivateKeyReference;
keyTransparencyVerify: KeyTransparencyVerify;
}
const importKeysProcessV2 = async ({
api,
keyImportRecords,
onImport,
address,
addressKeys,
userKey,
keyTransparencyVerify,
}: ImportKeysProcessV2Arguments) => {
const activeKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, addressKeys);
const inactiveKeys = await getInactiveKeys(address.Keys, activeKeys);
const [keysToReactivate, keysToImport, existingKeys] = getFilteredImportRecords(
keyImportRecords,
activeKeys,
inactiveKeys
);
existingKeys.forEach((keyImportRecord) => {
onImport(keyImportRecord.id, new Error('Key already active'));
});
let mutableActiveKeys = activeKeys;
for (const keyImportRecord of keysToImport) {
try {
const { privateKey } = keyImportRecord;
const { token, encryptedToken, signature } = await generateAddressKeyTokens(userKey);
const privateKeyArmored = await CryptoProxy.exportPrivateKey({
privateKey,
passphrase: token,
});
const newActiveKey = await getActiveKeyObject(privateKey, {
ID: 'tmp',
primary: getPrimaryFlag(mutableActiveKeys),
flags: getDefaultKeyFlags(address),
});
const updatedActiveKeys = getNormalizedActiveKeys(address, [...mutableActiveKeys, newActiveKey]);
const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
const { Key } = await api(
createAddressKeyRouteV2({
AddressID: address.ID,
Primary: newActiveKey.primary,
PrivateKey: privateKeyArmored,
SignedKeyList,
Signature: signature,
Token: encryptedToken,
})
);
// Only once the SKL is successfully posted we add it to the KT commit state.
await onSKLPublishSuccess();
// Mutably update the key with the latest value from the real ID.
newActiveKey.ID = Key.ID;
mutableActiveKeys = updatedActiveKeys;
onImport(keyImportRecord.id, 'ok');
} catch (e: any) {
onImport(keyImportRecord.id, e);
}
}
await reactivateAddressKeysV2({
api,
address,
activeKeys: mutableActiveKeys,
userKey,
keysToReactivate,
onReactivation: onImport,
keyTransparencyVerify,
});
};
export default importKeysProcessV2;
| 8,674 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/import/index.ts | export * from './importKeysProcess';
export * from './interface';
| 8,675 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/import/interface.ts | import { PrivateKeyReference } from '@proton/crypto';
export interface KeyImportData {
id: string;
privateKey: PrivateKeyReference;
}
export type OnKeyImportCallback = (id: string, result: 'ok' | Error) => void;
| 8,676 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/reactivation/index.ts | export * from './reactivateKeysProcess';
export * from './interface';
| 8,677 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/reactivation/interface.ts | import { PrivateKeyReference } from '@proton/crypto';
import { Address, DecryptedKey, Key, User } from '../../interfaces';
export interface KeyReactivationData {
id: string;
Key: Key;
privateKey?: PrivateKeyReference;
}
export type KeyReactivationRecord =
| {
user: User;
address?: undefined;
keys: DecryptedKey[];
keysToReactivate: KeyReactivationData[];
}
| {
user?: undefined;
address: Address;
keys: DecryptedKey[];
keysToReactivate: KeyReactivationData[];
};
export type OnKeyReactivationCallback = (id: string, result: 'ok' | Error) => void;
| 8,678 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/reactivation/reactivateKeyHelper.ts | import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import unique from '@proton/utils/unique';
import {
DecryptedKey,
Key,
KeyPair,
KeyTransparencyVerify,
SignedKeyList,
Address as tsAddress,
User as tsUser,
} from '../../interfaces';
import { getActiveKeys, getNormalizedActiveKeys, getReactivatedKeyFlag } from '../getActiveKeys';
import { getDecryptedAddressKeysHelper } from '../getDecryptedAddressKeys';
import { OnSKLPublishSuccess, getSignedKeyListWithDeferredPublish } from '../signedKeyList';
interface GetReactivatedAddressKeys {
address: tsAddress;
oldUserKeys: KeyPair[];
newUserKeys: KeyPair[];
user: tsUser;
keyPassword: string;
keyTransparencyVerify: KeyTransparencyVerify;
}
type GetReactivateAddressKeysReturnValue =
| {
address: tsAddress;
reactivatedKeys?: undefined;
signedKeyList?: undefined;
onSKLPublishSuccess?: undefined;
}
| {
address: tsAddress;
reactivatedKeys: DecryptedKey[];
signedKeyList: SignedKeyList;
onSKLPublishSuccess: OnSKLPublishSuccess;
};
export const getReactivatedAddressKeys = async ({
address,
user,
oldUserKeys,
newUserKeys,
keyPassword,
keyTransparencyVerify,
}: GetReactivatedAddressKeys): Promise<GetReactivateAddressKeysReturnValue> => {
const empty = {
address,
reactivatedKeys: undefined,
signedKeyList: undefined,
} as const;
const oldDecryptedAddressKeys = await getDecryptedAddressKeysHelper(address.Keys, user, oldUserKeys, keyPassword);
// All keys were able to decrypt previously, can just return.
if (oldDecryptedAddressKeys.length === address.Keys.length) {
return empty;
}
const newDecryptedAddressKeys = await getDecryptedAddressKeysHelper(address.Keys, user, newUserKeys, keyPassword);
// No difference in how many keys were able to get decrypted
if (oldDecryptedAddressKeys.length === newDecryptedAddressKeys.length) {
return empty;
}
if (newDecryptedAddressKeys.length < oldDecryptedAddressKeys.length) {
throw new Error('More old decryptable keys than new, should never happen');
}
// New keys were able to get decrypted
const oldDecryptedAddressKeysSet = new Set<string>(oldDecryptedAddressKeys.map(({ ID }) => ID));
const reactivatedKeys = newDecryptedAddressKeys.filter(({ ID }) => !oldDecryptedAddressKeysSet.has(ID));
const reactivatedKeysSet = new Set<string>(reactivatedKeys.map(({ ID }) => ID));
if (!reactivatedKeysSet.size) {
return empty;
}
const oldAddressKeysMap = new Map<string, Key>(address.Keys.map((Key) => [Key.ID, Key]));
const newActiveKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, newDecryptedAddressKeys);
const newActiveKeysFormatted = getNormalizedActiveKeys(
address,
newActiveKeys.map((activeKey) => {
if (!reactivatedKeysSet.has(activeKey.ID)) {
return activeKey;
}
return {
...activeKey,
flags: getReactivatedKeyFlag(address, oldAddressKeysMap.get(activeKey.ID)?.Flags),
};
})
);
const [signedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
newActiveKeysFormatted,
address,
keyTransparencyVerify
);
return {
address,
reactivatedKeys,
signedKeyList: signedKeyList,
onSKLPublishSuccess: onSKLPublishSuccess,
};
};
export const getAddressReactivationPayload = (results: GetReactivateAddressKeysReturnValue[]) => {
const AddressKeyFingerprints = unique(
results.reduce<KeyPair[]>((acc, { reactivatedKeys }) => {
if (!reactivatedKeys) {
return acc;
}
return acc.concat(reactivatedKeys);
}, [])
).map(({ privateKey }) => privateKey.getFingerprint());
const SignedKeyLists = results.reduce<{ [key: string]: SignedKeyList }>((acc, result) => {
if (!result.reactivatedKeys?.length || !result.signedKeyList) {
throw new Error('Missing reactivated keys');
}
acc[result.address.ID] = result.signedKeyList;
return acc;
}, {});
return {
AddressKeyFingerprints,
SignedKeyLists,
};
};
interface GetReactivatedAddressesKeys {
addresses: tsAddress[];
oldUserKeys: KeyPair[];
newUserKeys: KeyPair[];
user: tsUser;
keyPassword: string;
keyTransparencyVerify: KeyTransparencyVerify;
}
export const getReactivatedAddressesKeys = async ({
addresses,
oldUserKeys,
newUserKeys,
user,
keyPassword,
keyTransparencyVerify,
}: GetReactivatedAddressesKeys) => {
const promises = addresses.map((address) =>
getReactivatedAddressKeys({
address,
oldUserKeys,
newUserKeys,
user,
keyPassword,
keyTransparencyVerify,
})
);
const results = await Promise.all(promises);
return results.filter(({ reactivatedKeys }) => {
if (!reactivatedKeys) {
return false;
}
return reactivatedKeys.length > 0;
});
};
export const resetUserId = async (Key: Key, reactivatedKey: PrivateKeyReference) => {
// Before the new key format imposed after key migration, the address and user key were the same key.
// Users may have exported one of the two. Upon reactivation the fingerprint could match a user key
// to the corresponding address key or vice versa. For that reason, the userids are reset to the userids
// of the old key.
const inactiveKey = await CryptoProxy.importPublicKey({ armoredKey: Key.PrivateKey });
// Warning: This function mutates the target key.
await CryptoProxy.replaceUserIDs({ sourceKey: inactiveKey, targetKey: reactivatedKey });
};
| 8,679 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/reactivation/reactivateKeysProcess.ts | import { getHasMigratedAddressKeys } from '../keyMigration';
import reactivateKeysProcessLegacy, { ReactivateKeysProcessLegacyArguments } from './reactivateKeysProcessLegacy';
import reactivateKeysProcessV2, { ReactivateKeysProcessV2Arguments } from './reactivateKeysProcessV2';
interface Arguments extends ReactivateKeysProcessV2Arguments, ReactivateKeysProcessLegacyArguments {}
export const reactivateKeysProcess = async ({
api,
user,
userKeys,
addresses,
keyReactivationRecords,
keyPassword,
onReactivation,
keyTransparencyVerify,
}: Arguments) => {
const hasMigratedAddressKeys = getHasMigratedAddressKeys(addresses);
if (hasMigratedAddressKeys) {
return reactivateKeysProcessV2({
api,
keyReactivationRecords,
keyPassword,
user,
userKeys,
addresses,
onReactivation,
keyTransparencyVerify,
});
}
return reactivateKeysProcessLegacy({
api,
keyReactivationRecords,
keyPassword,
onReactivation,
keyTransparencyVerify,
});
};
| 8,680 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/reactivation/reactivateKeysProcessLegacy.ts | import { CryptoProxy } from '@proton/crypto';
import { getDefaultKeyFlags } from '@proton/shared/lib/keys';
import { reactivateKeyRoute } from '../../api/keys';
import { Address, Api, DecryptedKey, Key, KeyTransparencyVerify } from '../../interfaces';
import { getActiveKeyObject, getActiveKeys, getNormalizedActiveKeys, getPrimaryFlag } from '../getActiveKeys';
import { getSignedKeyListWithDeferredPublish } from '../signedKeyList';
import { KeyReactivationData, KeyReactivationRecord, OnKeyReactivationCallback } from './interface';
import { resetUserId } from './reactivateKeyHelper';
interface ReactivateKeysProcessArguments {
api: Api;
keyPassword: string;
keysToReactivate: KeyReactivationData[];
address?: Address;
onReactivation: OnKeyReactivationCallback;
keys: DecryptedKey[];
Keys: Key[];
keyTransparencyVerify: KeyTransparencyVerify;
}
export const reactivateKeysProcess = async ({
api,
keyPassword,
keysToReactivate,
address,
onReactivation,
keys,
Keys,
keyTransparencyVerify,
}: ReactivateKeysProcessArguments) => {
const activeKeys = await getActiveKeys(address, address?.SignedKeyList, Keys, keys);
let mutableActiveKeys = activeKeys;
for (const keyToReactivate of keysToReactivate) {
const { id, Key, privateKey: reactivatedKey } = keyToReactivate;
const { ID } = Key;
try {
if (!reactivatedKey) {
throw new Error('Missing key');
}
await resetUserId(Key, reactivatedKey);
const privateKeyArmored = await CryptoProxy.exportPrivateKey({
privateKey: reactivatedKey,
passphrase: keyPassword,
});
const newActiveKey = await getActiveKeyObject(reactivatedKey, {
ID,
primary: getPrimaryFlag(mutableActiveKeys),
flags: getDefaultKeyFlags(address),
});
const updatedActiveKeys = getNormalizedActiveKeys(address, [...mutableActiveKeys, newActiveKey]);
const [SignedKeyList, onSKLPublishSuccess] = address
? await getSignedKeyListWithDeferredPublish(updatedActiveKeys, address, keyTransparencyVerify)
: [undefined, undefined];
await api(
reactivateKeyRoute({
ID,
PrivateKey: privateKeyArmored,
SignedKeyList,
})
);
if (onSKLPublishSuccess) {
await onSKLPublishSuccess();
}
mutableActiveKeys = updatedActiveKeys;
onReactivation(id, 'ok');
} catch (e: any) {
onReactivation(id, e);
}
}
};
export interface ReactivateKeysProcessLegacyArguments {
api: Api;
keyReactivationRecords: KeyReactivationRecord[];
onReactivation: OnKeyReactivationCallback;
keyPassword: string;
keyTransparencyVerify: KeyTransparencyVerify;
}
const reactivateKeysProcessLegacy = async ({
keyReactivationRecords,
api,
onReactivation,
keyPassword,
keyTransparencyVerify,
}: ReactivateKeysProcessLegacyArguments) => {
for (const keyReactivationRecord of keyReactivationRecords) {
const { user, address, keysToReactivate, keys } = keyReactivationRecord;
try {
const Keys = address ? address.Keys : user?.Keys || [];
await reactivateKeysProcess({
api,
keyPassword,
keysToReactivate,
address,
onReactivation,
keys,
Keys,
keyTransparencyVerify,
});
} catch (e: any) {
keysToReactivate.forEach(({ id }) => onReactivation(id, e));
}
}
};
export default reactivateKeysProcessLegacy;
| 8,681 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys | petrpan-code/ProtonMail/WebClients/packages/shared/lib/keys/reactivation/reactivateKeysProcessV2.ts | import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import { getDefaultKeyFlags } from '@proton/shared/lib/keys';
import { getApiError } from '../../api/helpers/apiErrorHelper';
import { reactivateUserKeyRouteV2, reactiveLegacyAddressKeyRouteV2 } from '../../api/keys';
import { HTTP_STATUS_CODE } from '../../constants';
import {
ActiveKey,
Address,
Api,
DecryptedKey,
KeyTransparencyVerify,
Address as tsAddress,
User as tsUser,
} from '../../interfaces';
import { SimpleMap } from '../../interfaces/utils';
import { generateAddressKeyTokens } from '../addressKeys';
import {
getActiveKeyObject,
getActiveKeys,
getNormalizedActiveKeys,
getPrimaryFlag,
getReactivatedKeyFlag,
} from '../getActiveKeys';
import { getDecryptedAddressKeysHelper } from '../getDecryptedAddressKeys';
import { getPrimaryKey } from '../getPrimaryKey';
import { getHasMigratedAddressKey } from '../keyMigration';
import { getSignedKeyListWithDeferredPublish } from '../signedKeyList';
import { KeyReactivationData, KeyReactivationRecord, OnKeyReactivationCallback } from './interface';
import { getAddressReactivationPayload, getReactivatedAddressesKeys, resetUserId } from './reactivateKeyHelper';
interface ReactivateUserKeysArguments {
addressRecordsInV2Format: KeyReactivationRecord[];
api: Api;
addresses: Address[];
user: tsUser;
activeKeys: ActiveKey[];
onReactivation: OnKeyReactivationCallback;
keysToReactivate: KeyReactivationData[];
keyPassword: string;
keyTransparencyVerify: KeyTransparencyVerify;
}
export const reactivateUserKeys = async ({
addressRecordsInV2Format,
api,
addresses,
user,
activeKeys,
keysToReactivate,
onReactivation,
keyPassword,
keyTransparencyVerify,
}: ReactivateUserKeysArguments) => {
const keyReactivationDataMap = addressRecordsInV2Format.reduce<SimpleMap<KeyReactivationData>>((acc, record) => {
record.keysToReactivate.forEach((keyData) => {
acc[keyData.Key.ID] = keyData;
});
return acc;
}, {});
const reactivatedAddressKeysMap: SimpleMap<boolean> = {};
const allReactivatedAddressKeysMap: SimpleMap<boolean> = {};
let mutableActiveKeys = activeKeys;
let mutableAddresses = addresses;
for (const keyToReactivate of keysToReactivate) {
const { id, Key, privateKey: reactivatedKey } = keyToReactivate;
const { ID } = Key;
try {
if (!reactivatedKey) {
throw new Error('Missing key');
}
await resetUserId(Key, reactivatedKey);
const privateKeyArmored = await CryptoProxy.exportPrivateKey({
privateKey: reactivatedKey,
passphrase: keyPassword,
});
const newActiveKey = await getActiveKeyObject(reactivatedKey, {
ID,
primary: getPrimaryFlag(mutableActiveKeys),
flags: getDefaultKeyFlags(undefined),
});
const updatedActiveKeys = getNormalizedActiveKeys(undefined, [...mutableActiveKeys, newActiveKey]);
const reactivatedAddressKeysResult = await getReactivatedAddressesKeys({
addresses,
oldUserKeys: mutableActiveKeys,
newUserKeys: updatedActiveKeys,
user,
keyPassword,
keyTransparencyVerify,
});
const addressReactivationPayload = getAddressReactivationPayload(reactivatedAddressKeysResult);
mutableAddresses = mutableAddresses.map((address) => {
const updatedSignedKeyList = addressReactivationPayload.SignedKeyLists[address.ID];
if (updatedSignedKeyList) {
return {
...address,
SignedKeyList: {
...updatedSignedKeyList,
MinEpochID: null,
MaxEpochID: null,
},
};
}
return address;
});
await api(
reactivateUserKeyRouteV2({
ID,
PrivateKey: privateKeyArmored,
...addressReactivationPayload,
})
);
// Only once the SKLs have been successfully posted we add it to the KT commit state.
await Promise.all(
reactivatedAddressKeysResult.map(({ onSKLPublishSuccess }) =>
onSKLPublishSuccess ? onSKLPublishSuccess() : Promise.resolve()
)
);
mutableActiveKeys = updatedActiveKeys;
onReactivation(id, 'ok');
// Notify all the address keys that got reactivated from this user key
reactivatedAddressKeysResult.forEach(({ reactivatedKeys }) => {
reactivatedKeys?.forEach(({ ID }) => {
allReactivatedAddressKeysMap[ID] = true;
const reactivationData = keyReactivationDataMap[ID];
if (reactivationData) {
onReactivation(reactivationData.id, 'ok');
reactivatedAddressKeysMap[reactivationData.id] = true;
}
});
});
} catch (e: any) {
onReactivation(id, e);
const { status } = getApiError(e);
if (status === HTTP_STATUS_CODE.FORBIDDEN) {
// The password prompt has been cancelled. No need to attempt to reactivate the other keys.
break;
}
}
}
addressRecordsInV2Format.forEach(({ keysToReactivate }) => {
keysToReactivate.forEach(({ id, privateKey }) => {
if (!reactivatedAddressKeysMap[id] && !privateKey) {
onReactivation(id, new Error('User key inactivate'));
}
});
});
return {
userKeys: mutableActiveKeys,
addresses: mutableAddresses,
allReactivatedAddressKeysMap,
};
};
interface ReactivateAddressKeysV2Arguments {
api: Api;
address: Address;
activeKeys: ActiveKey[];
userKey: PrivateKeyReference;
onReactivation: OnKeyReactivationCallback;
keysToReactivate: KeyReactivationData[];
keyTransparencyVerify: KeyTransparencyVerify;
}
export const reactivateAddressKeysV2 = async ({
api,
address,
activeKeys,
keysToReactivate,
onReactivation,
userKey,
keyTransparencyVerify,
}: ReactivateAddressKeysV2Arguments) => {
let mutableActiveKeys = activeKeys;
for (const keyToReactivate of keysToReactivate) {
const { id, Key, privateKey: reactivatedKey } = keyToReactivate;
const { ID, Flags } = Key;
try {
if (!reactivatedKey) {
throw new Error('Missing key');
}
await resetUserId(Key, reactivatedKey);
const { token, encryptedToken, signature } = await generateAddressKeyTokens(userKey);
const privateKeyArmored = await CryptoProxy.exportPrivateKey({
privateKey: reactivatedKey,
passphrase: token,
});
const newActiveKey = await getActiveKeyObject(reactivatedKey, {
ID,
primary: getPrimaryFlag(mutableActiveKeys),
flags: getReactivatedKeyFlag(address, Flags),
});
const updatedActiveKeys = getNormalizedActiveKeys(address, [...mutableActiveKeys, newActiveKey]);
const [signedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
updatedActiveKeys,
address,
keyTransparencyVerify
);
await api(
reactiveLegacyAddressKeyRouteV2({
ID,
PrivateKey: privateKeyArmored,
SignedKeyList: signedKeyList,
Token: encryptedToken,
Signature: signature,
})
);
await onSKLPublishSuccess();
mutableActiveKeys = updatedActiveKeys;
onReactivation(id, 'ok');
} catch (e: any) {
onReactivation(id, e);
}
}
return mutableActiveKeys;
};
export interface ReactivateKeysProcessV2Arguments {
api: Api;
user: tsUser;
keyPassword: string;
addresses: tsAddress[];
userKeys: DecryptedKey[];
keyReactivationRecords: KeyReactivationRecord[];
onReactivation: OnKeyReactivationCallback;
keyTransparencyVerify: KeyTransparencyVerify;
}
const reactivateKeysProcessV2 = async ({
api,
user,
keyReactivationRecords,
onReactivation,
keyPassword,
addresses: oldAddresses,
userKeys: oldUserKeys,
keyTransparencyVerify,
}: ReactivateKeysProcessV2Arguments) => {
const { userRecord, addressRecordsInV2Format, addressRecordsInLegacyFormatOrWithBackup } =
keyReactivationRecords.reduce<{
addressRecordsInV2Format: KeyReactivationRecord[];
addressRecordsInLegacyFormatOrWithBackup: KeyReactivationRecord[];
userRecord?: KeyReactivationRecord;
}>(
(acc, record) => {
const { user, address, keysToReactivate, keys } = record;
if (user) {
acc.userRecord = record;
}
if (address) {
const keysInV2Format = keysToReactivate.filter(
({ privateKey, Key }) => !privateKey && getHasMigratedAddressKey(Key)
);
const keysInLegacyFormatOrWithBackup = keysToReactivate.filter(
({ privateKey, Key }) => privateKey || !getHasMigratedAddressKey(Key)
);
if (keysInV2Format.length) {
acc.addressRecordsInV2Format.push({
address,
keys,
keysToReactivate: keysInV2Format,
});
}
if (keysInLegacyFormatOrWithBackup.length) {
acc.addressRecordsInLegacyFormatOrWithBackup.push({
address,
keys,
keysToReactivate: keysInLegacyFormatOrWithBackup,
});
}
}
return acc;
},
{ addressRecordsInV2Format: [], addressRecordsInLegacyFormatOrWithBackup: [], userRecord: undefined }
);
let userKeys = oldUserKeys;
let addresses = oldAddresses;
let allReactivatedAddressKeysMap: SimpleMap<boolean> = {};
if (userRecord) {
try {
const activeUserKeys = await getActiveKeys(undefined, null, user.Keys, userKeys);
const userKeysReactivationResult = await reactivateUserKeys({
api,
user,
activeKeys: activeUserKeys,
addresses: oldAddresses,
keysToReactivate: userRecord.keysToReactivate,
onReactivation,
keyPassword,
addressRecordsInV2Format,
keyTransparencyVerify,
});
userKeys = userKeysReactivationResult.userKeys;
addresses = userKeysReactivationResult.addresses;
allReactivatedAddressKeysMap = userKeysReactivationResult.allReactivatedAddressKeysMap;
} catch (e: any) {
userRecord.keysToReactivate.forEach(({ id }) => onReactivation(id, e));
addressRecordsInV2Format.forEach(({ keysToReactivate }) => {
keysToReactivate.forEach(({ id }) => onReactivation(id, e));
});
}
}
const primaryPrivateUserKey = getPrimaryKey(userKeys)?.privateKey;
for (const { address: oldAddress, keysToReactivate } of addressRecordsInLegacyFormatOrWithBackup) {
const keysLeftToReactivate: KeyReactivationData[] = [];
keysToReactivate.forEach((x) => {
// Even if this key was uploaded, it may have gotten reactivated from a user key earlier, and so it
// should not be attempted to be reactivated again
const alreadyReactivated = allReactivatedAddressKeysMap[x.Key.ID] === true;
if (alreadyReactivated) {
onReactivation(x.id, 'ok');
} else {
keysLeftToReactivate.push(x);
}
});
try {
const address = addresses.find(({ ID: otherID }) => oldAddress?.ID === otherID);
if (!address || !primaryPrivateUserKey) {
throw new Error('Missing dependency');
}
const addressKeys = await getDecryptedAddressKeysHelper(address.Keys, user, userKeys, '');
const activeAddressKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, addressKeys);
await reactivateAddressKeysV2({
api,
address,
activeKeys: activeAddressKeys,
userKey: primaryPrivateUserKey,
onReactivation,
keysToReactivate: keysLeftToReactivate,
keyTransparencyVerify,
});
} catch (e: any) {
keysLeftToReactivate.forEach(({ id }) => onReactivation(id, e));
}
}
};
export default reactivateKeysProcessV2;
| 8,682 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/logical/logical.tsx | const ending = '.ltr.css';
const getIsNonEnding = (src: string) => {
const targetOrigin = window.location.origin;
const url = new URL(src, targetOrigin);
return url.origin === targetOrigin && url.pathname.endsWith('.css') && !url.pathname.endsWith(ending);
};
export const queryLocalLinkElements = () => {
return [...document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')].filter((node) => {
return getIsNonEnding(node.href);
});
};
const mutateLinkElement = (el: HTMLLinkElement) => {
el.href = el.href.replace(/\.css/, ending);
};
const getIsNonEndingLinkElement = (node: Node): node is HTMLLinkElement => {
return (
node &&
node.nodeType === 1 &&
node instanceof HTMLLinkElement &&
node.tagName === 'LINK' &&
node.rel === 'stylesheet' &&
getIsNonEnding(node.href)
);
};
const initLogicalProperties = () => {
if (CSS.supports('(border-start-start-radius: 1em)')) {
return;
}
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (getIsNonEndingLinkElement(node)) {
mutateLinkElement(node);
}
});
});
});
queryLocalLinkElements().forEach(mutateLinkElement);
observer.observe(document.head, {
childList: true,
subtree: true,
});
};
export default initLogicalProperties;
| 8,683 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/addresses.ts | import { addPlusAlias, canonicalizeInternalEmail } from '../helpers/email';
import { Address } from '../interfaces';
/**
* Get address from email
* Remove + alias and transform to lower case
*/
export const getByEmail = (addresses: Address[], email = '') => {
const value = canonicalizeInternalEmail(email);
return addresses.find(({ Email }) => canonicalizeInternalEmail(Email) === value);
};
/**
* Detect if the email address is a valid plus alias and returns the address model appropriate
*/
export const getAddressFromPlusAlias = (addresses: Address[], email = ''): Address | undefined => {
const plusIndex = email.indexOf('+');
const atIndex = email.indexOf('@');
if (plusIndex === -1 || atIndex === -1) {
return;
}
// Remove the plus alias part to find a match with existing addresses
const address = getByEmail(addresses, email);
const { Status, Receive, Send } = address || {};
if (!Status || !Receive || !Send) {
// pm.me addresses on free accounts (Send = 0)
return;
}
const plusPart = email.substring(plusIndex + 1, atIndex);
// Returns an address where the Email is build to respect the existing capitalization and add the plus part
return { ...(address as Address), Email: addPlusAlias(address?.Email, plusPart) };
};
export const getSupportedPlusAlias = ({
selfAttendeeEmail,
selfAddressEmail,
}: {
selfAttendeeEmail: string;
selfAddressEmail: string;
}) => {
if (!selfAttendeeEmail) {
return selfAddressEmail;
}
const plusIndex = selfAttendeeEmail.indexOf('+');
const atIndex = selfAttendeeEmail.indexOf('@');
const plusPart = selfAttendeeEmail.substring(plusIndex + 1, atIndex);
if (plusIndex === -1) {
return selfAddressEmail;
}
return addPlusAlias(selfAddressEmail, plusPart);
};
| 8,684 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/autocrypt.ts | import { binaryStringToArray, decodeBase64 } from '@proton/crypto/lib/utils';
const MANDATORY_FIELDS = ['keydata', 'addr'];
const OPTIONAL_FIELDS = ['prefer-encrypt'];
const CRITICAL_FIELDS = OPTIONAL_FIELDS.concat(MANDATORY_FIELDS);
export interface AutocryptHeader {
addr: string;
keydata: Uint8Array;
'prefer-encrypt'?: 'mutual';
// Non-critical optional fields
[_key: string]: undefined | string | Uint8Array;
}
// Parse according to https://autocrypt.org/level1.html#the-autocrypt-header
export const getParsedAutocryptHeader = (header = '', sender = ''): AutocryptHeader | undefined => {
let invalid = false;
const result: AutocryptHeader = Object.fromEntries(
header
.split(';')
.map((keyValue) => {
const trimmedKeyValue = keyValue.trim();
// For ease of parsing, the keydata attribute MUST be the last attribute in this header. Avoid splitting by = since it's base64
if (trimmedKeyValue.startsWith('keydata=')) {
try {
const keydataStringValue = trimmedKeyValue.slice('keydata='.length);
const keydataValue = binaryStringToArray(decodeBase64(keydataStringValue));
return ['keydata', keydataValue];
} catch (e: any) {
return ['', ''];
}
}
const [parsedKey = '', parsedValue = ''] = keyValue.split('=');
const key = parsedKey.trim();
// It MUST treat the entire Autocrypt header as invalid if it encounters a “critical” attribute that it doesn’t support.
if (!CRITICAL_FIELDS.includes(key) && !key.startsWith('_')) {
invalid = true;
return ['', ''];
}
return [key, parsedValue.trim()];
})
.filter(([key, value]) => {
return key && value;
})
);
// The mandatory fields must be present.
if (MANDATORY_FIELDS.some((field) => !result[field]) || invalid) {
return;
}
// If addr differs from the addr in the From header, the entire Autocrypt header MUST be treated as invalid.
if (result.addr.toLowerCase() !== sender.toLowerCase()) {
return;
}
// The prefer-encrypt attribute is optional and can only occur with the value mutual.
// Its presence in the Autocrypt header indicates an agreement to enable encryption by default.
if (result['prefer-encrypt'] !== 'mutual') {
return;
}
return result;
};
| 8,685 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/constants.ts | import JSBI from 'jsbi';
export const MESSAGE_FLAGS = {
FLAG_RECEIVED: Math.pow(2, 0), // whether a message is received
FLAG_SENT: Math.pow(2, 1), // whether a message is sent
FLAG_INTERNAL: Math.pow(2, 2), // whether the message is between Proton Mail recipients
FLAG_E2E: Math.pow(2, 3), // whether the message is end-to-end encrypted
FLAG_AUTO: Math.pow(2, 4), // whether the message is an autoresponse
FLAG_REPLIED: Math.pow(2, 5), // whether the message is replied to
FLAG_REPLIEDALL: Math.pow(2, 6), // whether the message is replied all to
FLAG_FORWARDED: Math.pow(2, 7), // whether the message is forwarded
FLAG_AUTOREPLIED: Math.pow(2, 8), // whether the message has been responded to with an autoresponse
FLAG_IMPORTED: Math.pow(2, 9), // whether the message is an import
FLAG_OPENED: Math.pow(2, 10), // whether the message has ever been opened by the user
FLAG_RECEIPT_SENT: Math.pow(2, 11), // whether a read receipt has been sent in response to the message
FLAG_RECEIPT_REQUEST: Math.pow(2, 16), // whether to request a read receipt for the message
FLAG_PUBLIC_KEY: Math.pow(2, 17), // whether to attach the public key
FLAG_SIGN: Math.pow(2, 18), // whether to sign the message
FLAG_UNSUBSCRIBED: Math.pow(2, 19), // Unsubscribed from newsletter
FLAG_SCHEDULED_SEND: Math.pow(2, 20), // Messages that have been delayed send
FLAG_UNSUBSCRIBABLE: Math.pow(2, 21), // Messages that are unsubscribable
FLAG_DMARC_FAIL: Math.pow(2, 26), // Incoming mail failed dmarc authentication.
FLAG_HAM_MANUAL: Math.pow(2, 27), // The message is in spam and the user moves it to a new location that is not spam or trash (e.g. inbox or archive).
FLAG_PHISHING_AUTO: Math.pow(2, 30), // Incoming mail is marked as phishing by anti-spam filters.
FLAG_FROZEN_EXPIRATION: JSBI.BigInt(Math.pow(2, 32)), // Messages where the expiration time cannot be changed
FLAG_SUSPICIOUS: JSBI.BigInt(Math.pow(2, 33)), // System flagged this message as a suspicious email
FLAG_AUTO_FORWARDER: JSBI.BigInt(Math.pow(2, 34)), // Message is auto-forwarded
FLAG_AUTO_FORWARDEE: JSBI.BigInt(Math.pow(2, 35)), // Message is auto-forwarded
};
export enum VERIFICATION_STATUS {
NOT_VERIFIED = -1,
NOT_SIGNED,
SIGNED_AND_VALID,
SIGNED_AND_INVALID,
SIGNED_NO_PUB_KEY = 3,
}
// Protonmail enforces signing outgoing messages since January 1, 2019. It does not sign bulk messages yet
export const SIGNATURE_START = {
USER: 1546300800,
BULK: Infinity,
};
export enum BLOCK_SENDER_CONFIRMATION {
DO_NOT_ASK = 1,
}
export const ATTACHMENT_MAX_COUNT = 100;
export enum ATTACHMENT_DISPOSITION {
ATTACHMENT = 'attachment',
INLINE = 'inline',
}
| 8,686 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/encryptionPreferences.ts | import { c } from 'ttag';
import { PublicKeyReference } from '@proton/crypto';
import { extractDraftMIMEType, extractScheme, extractSign } from '../api/helpers/mailSettings';
import { BRAND_NAME, CONTACT_MIME_TYPES, PGP_SCHEMES } from '../constants';
import {
ContactPublicKeyModel,
KeyTransparencyVerificationResult,
MailSettings,
PublicKeyModel,
SelfSend,
} from '../interfaces';
import { getEmailMismatchWarning, getIsValidForSending } from '../keys/publicKeys';
export enum ENCRYPTION_PREFERENCES_ERROR_TYPES {
EMAIL_ADDRESS_ERROR,
INTERNAL_USER_DISABLED,
INTERNAL_USER_NO_API_KEY,
PRIMARY_CANNOT_SEND,
PRIMARY_NOT_PINNED,
WKD_USER_NO_VALID_WKD_KEY,
EXTERNAL_USER_NO_VALID_PINNED_KEY,
CONTACT_SIGNATURE_NOT_VERIFIED,
}
export class EncryptionPreferencesError extends Error {
type: ENCRYPTION_PREFERENCES_ERROR_TYPES;
constructor(type: ENCRYPTION_PREFERENCES_ERROR_TYPES, message: string) {
super(message);
this.type = type;
Object.setPrototypeOf(this, EncryptionPreferencesError.prototype);
}
}
export interface EncryptionPreferences {
encrypt: boolean;
sign: boolean;
scheme: PGP_SCHEMES;
mimeType: CONTACT_MIME_TYPES;
isInternalWithDisabledE2EEForMail: boolean; // both `encrypt` and `isInternalWithDisabledE2EEForMail` might be true at this stage
sendKey?: PublicKeyReference;
isSendKeyPinned?: boolean;
apiKeys: PublicKeyReference[];
pinnedKeys: PublicKeyReference[];
verifyingPinnedKeys: PublicKeyReference[];
isInternal: boolean;
hasApiKeys: boolean;
hasPinnedKeys: boolean;
isContact: boolean;
isContactSignatureVerified?: boolean;
contactSignatureTimestamp?: Date;
warnings?: string[];
error?: EncryptionPreferencesError;
emailAddressWarnings?: string[];
ktVerificationResult?: KeyTransparencyVerificationResult;
}
const extractEncryptionPreferencesOwnAddress = (
publicKeyModel: PublicKeyModel,
selfSend: SelfSend
): EncryptionPreferences => {
const {
publicKeys: { apiKeys },
emailAddress,
scheme,
mimeType,
isInternalWithDisabledE2EEForMail,
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
emailAddressWarnings,
emailAddressErrors,
ktVerificationResult,
} = publicKeyModel;
const { address, publicKey, canSend } = selfSend;
const hasApiKeys = !!address.HasKeys;
const canAddressReceive = !!address.Receive;
const result = {
encrypt: true,
sign: true,
scheme,
mimeType,
isInternal: true,
apiKeys,
pinnedKeys: [],
verifyingPinnedKeys: [],
hasApiKeys,
hasPinnedKeys: false,
isInternalWithDisabledE2EEForMail: isInternalWithDisabledE2EEForMail, // this may be true if own addresses are disabled
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
emailAddressWarnings,
ktVerificationResult,
};
if (emailAddressErrors?.length) {
const errorString = emailAddressErrors[0];
return {
...result,
error: new EncryptionPreferencesError(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR, errorString),
};
}
if (!canAddressReceive) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.INTERNAL_USER_DISABLED,
c('Error').t`Email address disabled`
),
};
}
if (!hasApiKeys) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.INTERNAL_USER_NO_API_KEY,
// Proton users should always have keys, so this case should never happen in practice. Therefore we don't translate the error message
`No key was found for the ${BRAND_NAME} user`
),
};
}
if (!publicKey || !canSend) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_CANNOT_SEND,
c('Error').t`Primary key is not valid for sending`
),
};
}
const warnings = getEmailMismatchWarning(publicKey, emailAddress, true);
return { ...result, sendKey: publicKey, isSendKeyPinned: false, warnings };
};
const extractEncryptionPreferencesInternal = (publicKeyModel: PublicKeyModel): EncryptionPreferences => {
const {
emailAddress,
publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys },
scheme,
mimeType,
trustedFingerprints,
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
emailAddressWarnings,
emailAddressErrors,
ktVerificationResult,
} = publicKeyModel;
const hasApiKeys = !!apiKeys.length;
const hasPinnedKeys = !!pinnedKeys.length;
const result = {
encrypt: true,
sign: true,
scheme,
mimeType,
apiKeys,
pinnedKeys,
verifyingPinnedKeys,
isInternal: true,
hasApiKeys,
hasPinnedKeys,
isInternalWithDisabledE2EEForMail: false,
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
emailAddressWarnings,
ktVerificationResult,
};
if (emailAddressErrors?.length) {
const errorString = emailAddressErrors[0];
return {
...result,
error: new EncryptionPreferencesError(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR, errorString),
};
}
if (isContact && isContactSignatureVerified === false) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.CONTACT_SIGNATURE_NOT_VERIFIED,
c('Error').t`Contact signature could not be verified`
),
};
}
if (!hasApiKeys) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.INTERNAL_USER_NO_API_KEY,
// Proton users should always have keys, so this case should never happen in practice. Therefore we don't translate the error message
`No key was found for the ${BRAND_NAME} user`
),
};
}
// API keys are ordered in terms of user preference. The primary key (first in the list) will be used for sending
const [primaryKey] = apiKeys;
const primaryKeyFingerprint = primaryKey.getFingerprint();
if (!getIsValidForSending(primaryKeyFingerprint, publicKeyModel)) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_CANNOT_SEND,
c('Error').t`Primary key retrieved for ${BRAND_NAME} user is not valid for sending`
),
};
}
if (!hasPinnedKeys) {
const warnings = getEmailMismatchWarning(primaryKey, emailAddress, true);
return { ...result, sendKey: primaryKey, isSendKeyPinned: false, warnings };
}
// if there are pinned keys, make sure the primary API key is trusted and valid for sending
const isPrimaryTrustedAndValid =
trustedFingerprints.has(primaryKeyFingerprint) && getIsValidForSending(primaryKeyFingerprint, publicKeyModel);
const sendKey = pinnedKeys.find((key) => key.getFingerprint() === primaryKeyFingerprint);
if (!isPrimaryTrustedAndValid || !sendKey) {
return {
...result,
sendKey: primaryKey,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_NOT_PINNED,
c('Error').t`Trusted keys are not valid for sending`
),
};
}
const warnings = getEmailMismatchWarning(sendKey, emailAddress, true);
// return the pinned key, not the API one
return { ...result, sendKey, isSendKeyPinned: true, warnings };
};
const extractEncryptionPreferencesExternalWithWKDKeys = (publicKeyModel: PublicKeyModel): EncryptionPreferences => {
const {
encrypt,
sign,
emailAddress,
publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys },
scheme,
mimeType,
trustedFingerprints,
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
emailAddressWarnings,
emailAddressErrors,
ktVerificationResult,
} = publicKeyModel;
const hasApiKeys = true;
const hasPinnedKeys = !!pinnedKeys.length;
const result = {
encrypt,
sign,
scheme,
mimeType,
apiKeys,
pinnedKeys,
verifyingPinnedKeys,
isInternal: false,
hasApiKeys,
hasPinnedKeys,
isInternalWithDisabledE2EEForMail: false,
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
emailAddressWarnings,
ktVerificationResult,
};
if (emailAddressErrors?.length) {
const errorString = emailAddressErrors[0];
return {
...result,
error: new EncryptionPreferencesError(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR, errorString),
};
}
if (isContact && isContactSignatureVerified === false) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.CONTACT_SIGNATURE_NOT_VERIFIED,
c('Error').t`Contact signature could not be verified`
),
};
}
// WKD keys are ordered in terms of user preference. The primary key (first in the list) will be used for sending
const [primaryKey] = apiKeys;
const primaryKeyFingerprint = primaryKey.getFingerprint();
const validApiSendKey = apiKeys.find((key) => getIsValidForSending(key.getFingerprint(), publicKeyModel));
if (!validApiSendKey) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.WKD_USER_NO_VALID_WKD_KEY,
c('Error').t`No WKD key retrieved for user is valid for sending`
),
};
}
if (!hasPinnedKeys) {
const warnings = getEmailMismatchWarning(primaryKey, emailAddress, false);
return { ...result, sendKey: primaryKey, isSendKeyPinned: false, warnings };
}
// if there are pinned keys, make sure the primary API key is trusted and valid for sending
const isPrimaryTrustedAndValid =
trustedFingerprints.has(primaryKeyFingerprint) && getIsValidForSending(primaryKeyFingerprint, publicKeyModel);
const sendKey = pinnedKeys.find((key) => key.getFingerprint() === primaryKeyFingerprint);
if (!isPrimaryTrustedAndValid || !sendKey) {
return {
...result,
sendKey: validApiSendKey,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_NOT_PINNED,
c('Error').t`Trusted keys are not valid for sending`
),
};
}
const warnings = getEmailMismatchWarning(sendKey, emailAddress, false);
// return the pinned key, not the API one
return { ...result, sendKey, isSendKeyPinned: true, warnings };
};
const extractEncryptionPreferencesExternalWithoutWKDKeys = (publicKeyModel: PublicKeyModel): EncryptionPreferences => {
const {
emailAddress,
publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys },
encrypt,
sign,
scheme,
mimeType,
isInternalWithDisabledE2EEForMail,
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
emailAddressWarnings,
emailAddressErrors,
ktVerificationResult,
} = publicKeyModel;
const hasPinnedKeys = !!pinnedKeys.length;
const result = {
encrypt,
sign,
mimeType,
scheme,
apiKeys,
pinnedKeys,
verifyingPinnedKeys,
isInternal: false,
hasApiKeys: false,
hasPinnedKeys,
isInternalWithDisabledE2EEForMail: isInternalWithDisabledE2EEForMail,
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
emailAddressWarnings,
ktVerificationResult,
};
if (emailAddressErrors?.length) {
const errorString = emailAddressErrors[0];
return {
...result,
error: new EncryptionPreferencesError(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR, errorString),
};
}
if (isContact && isContactSignatureVerified === false) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.CONTACT_SIGNATURE_NOT_VERIFIED,
c('Error').t`Contact signature could not be verified`
),
};
}
if (!hasPinnedKeys || !encrypt) {
return result;
}
// Pinned keys are ordered in terms of preference. Make sure the first is valid
const [sendKey] = pinnedKeys;
if (!getIsValidForSending(sendKey.getFingerprint(), publicKeyModel)) {
return {
...result,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.EXTERNAL_USER_NO_VALID_PINNED_KEY,
c('Error').t`The sending key is not valid`
),
};
}
const warnings = getEmailMismatchWarning(sendKey, emailAddress, false);
return { ...result, sendKey, isSendKeyPinned: true, warnings };
};
/**
* Extract the encryption preferences from a public-key model corresponding to a certain email address
*/
const extractEncryptionPreferences = (
model: ContactPublicKeyModel,
mailSettings: MailSettings,
selfSend?: SelfSend
): EncryptionPreferences => {
// Determine encrypt and sign flags, plus PGP scheme and MIME type.
// Take mail settings into account if they are present
const encrypt = !!model.encrypt;
const sign = extractSign(model, mailSettings);
const scheme = extractScheme(model, mailSettings);
const mimeType = extractDraftMIMEType(model, mailSettings);
const publicKeyModel = {
...model,
encrypt,
sign: encrypt || sign,
scheme,
mimeType,
};
// case of own address
if (selfSend) {
return extractEncryptionPreferencesOwnAddress(publicKeyModel, selfSend);
}
// case of internal user
if (model.isPGPInternal) {
return extractEncryptionPreferencesInternal(publicKeyModel);
}
// case of external user with WKD keys
if (model.isPGPExternalWithWKDKeys) {
return extractEncryptionPreferencesExternalWithWKDKeys(publicKeyModel);
}
// case of external user without WKD keys
return extractEncryptionPreferencesExternalWithoutWKDKeys(publicKeyModel);
};
export default extractEncryptionPreferences;
| 8,687 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/images.ts | import { MailSettings } from '@proton/shared/lib/interfaces';
import { SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings';
export const hasShowEmbedded = ({ HideEmbeddedImages }: Partial<MailSettings> = {}) =>
HideEmbeddedImages === SHOW_IMAGES.SHOW;
export const hasShowRemote = ({ HideRemoteImages }: Partial<MailSettings> = {}) =>
HideRemoteImages === SHOW_IMAGES.SHOW;
| 8,688 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/mailSettings.ts | import { MIME_TYPES } from '../constants';
import { MailSettings } from '../interfaces';
export const MAX_RECIPIENTS = 100;
export type DRAFT_MIME_TYPES = MIME_TYPES.PLAINTEXT | MIME_TYPES.DEFAULT;
export enum SHOW_MOVED {
NONE = 0,
DRAFTS = 1,
SENT = 2,
DRAFTS_AND_SENT = 3,
}
export enum HIDE_SENDER_IMAGES {
SHOW = 0,
HIDE = 1,
}
export enum SHOW_IMAGES {
SHOW = 0,
HIDE = 1,
}
export enum IMAGE_PROXY_FLAGS {
NONE = 0,
INCORPORATOR = 1,
PROXY = 2,
ALL = 3,
}
export enum VIEW_LAYOUT {
COLUMN = 0,
ROW = 1,
}
export enum VIEW_MODE {
GROUP = 0,
SINGLE = 1,
}
export enum COMPOSER_MODE {
POPUP = 0,
MAXIMIZED = 1,
}
export enum MESSAGE_BUTTONS {
READ_UNREAD = 0,
UNREAD_READ = 1,
}
export enum CONFIRM_LINK {
DISABLED = 0,
CONFIRM = 1,
}
export enum AUTO_SAVE_CONTACTS {
DISABLED = 0,
ENABLED = 1,
}
export enum SHORTCUTS {
DISABLED = 0,
ENABLED = 1,
}
export enum PM_SIGNATURE {
DISABLED = 0,
ENABLED = 1,
}
export enum PM_SIGNATURE_REFERRAL {
DISABLED = 0,
ENABLED = 1,
}
export enum FOLDER_COLOR {
DISABLED = 0,
ENABLED = 1,
}
export enum INHERIT_PARENT_FOLDER_COLOR {
DISABLED = 0,
ENABLED = 1,
}
export enum ATTACH_PUBLIC_KEY {
DISABLED = 0,
ENABLED = 1,
}
export enum SIGN {
DISABLED = 0,
ENABLED = 1,
}
export enum PACKAGE_TYPE {
SEND_PM = 1,
SEND_EO = 2,
SEND_CLEAR = 4,
SEND_PGP_INLINE = 8,
SEND_PGP_MIME = 16,
SEND_CLEAR_MIME = 32,
}
export enum PROMPT_PIN {
DISABLED = 0,
ENABLED = 1,
}
export enum STICKY_LABELS {
DISABLED = 0,
ENABLED = 1,
}
export enum DELAY_IN_SECONDS {
NONE = 0,
SMALL = 5,
MEDIUM = 10,
LARGE = 20,
}
export enum UNREAD_FAVICON {
DISABLED = 0,
ENABLED = 1,
}
export enum DIRECTION {
LEFT_TO_RIGHT = 0,
RIGHT_TO_LEFT = 1,
}
export enum ALMOST_ALL_MAIL {
DISABLED = 0,
ENABLED = 1,
}
export enum AUTO_DELETE_SPAM_AND_TRASH_DAYS {
ACTIVE = 30,
DISABLED = 0,
}
export enum SPAM_ACTION {
JustSpam = 0,
SpamAndUnsub = 1,
}
export enum MAIL_PAGE_SIZE {
FIFTY = 50,
ONE_HUNDRED = 100,
TWO_HUNDRED = 200,
}
export enum KEY_TRANSPARENCY_SETTING {
DISABLED = 0,
ENABLED = 1,
}
export const DEFAULT_MAILSETTINGS: MailSettings = {
DisplayName: '',
Signature: '',
Theme: '',
AutoResponder: {
StartTime: 0,
EndTime: 0,
Repeat: 0,
DaysSelected: [],
Subject: 'Auto',
Message: '',
IsEnabled: false,
Zone: 'Europe/Zurich',
},
AutoSaveContacts: AUTO_SAVE_CONTACTS.ENABLED,
ComposerMode: COMPOSER_MODE.POPUP,
MessageButtons: MESSAGE_BUTTONS.READ_UNREAD,
HideRemoteImages: SHOW_IMAGES.SHOW,
HideEmbeddedImages: SHOW_IMAGES.SHOW,
ShowMoved: SHOW_MOVED.NONE,
ViewMode: VIEW_MODE.GROUP,
ViewLayout: VIEW_LAYOUT.ROW,
SwipeLeft: 3,
SwipeRight: 0,
Shortcuts: SHORTCUTS.ENABLED,
PMSignature: PM_SIGNATURE.DISABLED,
ImageProxy: IMAGE_PROXY_FLAGS.PROXY,
RightToLeft: DIRECTION.LEFT_TO_RIGHT,
AttachPublicKey: ATTACH_PUBLIC_KEY.DISABLED,
Sign: SIGN.DISABLED,
PGPScheme: PACKAGE_TYPE.SEND_PGP_MIME,
PromptPin: PROMPT_PIN.DISABLED,
NumMessagePerPage: 50,
DraftMIMEType: MIME_TYPES.DEFAULT,
StickyLabels: STICKY_LABELS.DISABLED,
ConfirmLink: CONFIRM_LINK.CONFIRM,
DelaySendSeconds: DELAY_IN_SECONDS.MEDIUM,
EnableFolderColor: FOLDER_COLOR.DISABLED,
InheritParentFolderColor: INHERIT_PARENT_FOLDER_COLOR.ENABLED,
FontFace: null,
FontSize: null,
PMSignatureReferralLink: PM_SIGNATURE_REFERRAL.DISABLED,
SpamAction: null,
BlockSenderConfirmation: null,
HideSenderImages: HIDE_SENDER_IMAGES.SHOW,
AutoDeleteSpamAndTrashDays: null,
UnreadFavicon: UNREAD_FAVICON.DISABLED,
RecipientLimit: MAX_RECIPIENTS,
AlmostAllMail: ALMOST_ALL_MAIL.DISABLED,
ReceiveMIMEType: MIME_TYPES.DEFAULT,
ShowMIMEType: MIME_TYPES.DEFAULT,
KT: KEY_TRANSPARENCY_SETTING.DISABLED,
};
| 8,689 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/messages.ts | import JSBI from 'jsbi';
import { c } from 'ttag';
import identity from '@proton/utils/identity';
import { MAILBOX_LABEL_IDS, MIME_TYPES } from '../constants';
import { clearBit, hasBit, hasBitBigInt, setBit, toggleBit } from '../helpers/bitset';
import { canonicalizeInternalEmail, getEmailParts } from '../helpers/email';
import { isICS } from '../helpers/mimetype';
import { AttachmentInfo, Message } from '../interfaces/mail/Message';
import { MESSAGE_FLAGS, SIGNATURE_START } from './constants';
const { PLAINTEXT, MIME } = MIME_TYPES;
const {
FLAG_RECEIVED,
FLAG_SENT,
FLAG_RECEIPT_REQUEST,
FLAG_RECEIPT_SENT,
FLAG_IMPORTED,
FLAG_REPLIED,
FLAG_REPLIEDALL,
FLAG_FORWARDED,
FLAG_INTERNAL,
FLAG_AUTO,
FLAG_E2E,
FLAG_SIGN,
FLAG_PUBLIC_KEY,
FLAG_UNSUBSCRIBED,
FLAG_SCHEDULED_SEND,
FLAG_DMARC_FAIL,
FLAG_PHISHING_AUTO,
FLAG_HAM_MANUAL,
FLAG_FROZEN_EXPIRATION,
FLAG_SUSPICIOUS,
FLAG_AUTO_FORWARDEE,
FLAG_AUTO_FORWARDER,
} = MESSAGE_FLAGS;
const AUTOREPLY_HEADERS = ['X-Autoreply', 'X-Autorespond', 'X-Autoreply-From', 'X-Mail-Autoreply'];
const LIST_HEADERS = [
'List-Id',
'List-Unsubscribe',
'List-Subscribe',
'List-Post',
'List-Help',
'List-Owner',
'List-Archive',
];
/**
* Check if a message has a mime type
*/
export const hasMimeType = (type: MIME_TYPES) => (message?: Partial<Message>) => message?.MIMEType === type;
export const isMIME = hasMimeType(MIME);
export const isPlainText = hasMimeType(PLAINTEXT);
export const isHTML = hasMimeType(MIME_TYPES.DEFAULT);
/**
* Check if a message has a flag in the flags bitmap
*/
export const hasFlag = (flag: number) => (message?: Partial<Message>) => hasBit(message?.Flags, flag);
export const hasBigFlag = (flag: JSBI) => (message?: Partial<Message>) =>
hasBitBigInt(JSBI.BigInt(message?.Flags || 0), flag);
export const setFlag = (flag: number) => (message?: Partial<Message>) => setBit(message?.Flags, flag);
export const clearFlag = (flag: number) => (message?: Partial<Message>) => clearBit(message?.Flags, flag);
export const toggleFlag = (flag: number) => (message?: Partial<Message>) => toggleBit(message?.Flags, flag);
export const isRequestReadReceipt = hasFlag(FLAG_RECEIPT_REQUEST);
export const isReadReceiptSent = hasFlag(FLAG_RECEIPT_SENT);
export const isImported = hasFlag(FLAG_IMPORTED);
export const isInternal = hasFlag(FLAG_INTERNAL);
export const isExternal = (message?: Partial<Message>) => !isInternal(message);
export const isAuto = hasFlag(FLAG_AUTO);
export const isReceived = hasFlag(FLAG_RECEIVED);
export const isSent = hasFlag(FLAG_SENT);
export const isReplied = hasFlag(FLAG_REPLIED);
export const isRepliedAll = hasFlag(FLAG_REPLIEDALL);
export const isForwarded = hasFlag(FLAG_FORWARDED);
export const isSentAndReceived = hasFlag(FLAG_SENT | FLAG_RECEIVED);
export const isDraft = (message?: Partial<Message>) =>
message?.Flags !== undefined && !isSent(message) && !isReceived(message);
export const isOutbox = (message?: Partial<Message>) => message?.LabelIDs?.includes(MAILBOX_LABEL_IDS.OUTBOX);
export const isExpiring = (message?: Partial<Message>) => !!message?.ExpirationTime;
export const isScheduled = (message?: Partial<Message>) => message?.LabelIDs?.includes(MAILBOX_LABEL_IDS.SCHEDULED);
export const isSnoozed = (message?: Partial<Message>) => message?.LabelIDs?.includes(MAILBOX_LABEL_IDS.SNOOZED);
export const isScheduledSend = hasFlag(FLAG_SCHEDULED_SEND);
export const isE2E = hasFlag(FLAG_E2E);
export const isSentEncrypted = hasFlag(FLAG_E2E | FLAG_SENT);
export const isInternalEncrypted = hasFlag(FLAG_E2E | FLAG_INTERNAL);
export const isSign = hasFlag(FLAG_SIGN);
export const isFrozenExpiration = hasBigFlag(FLAG_FROZEN_EXPIRATION);
export const isAttachPublicKey = hasFlag(FLAG_PUBLIC_KEY);
export const isUnsubscribed = hasFlag(FLAG_UNSUBSCRIBED);
export const isUnsubscribable = (message?: Partial<Message>) => {
const unsubscribeMethods = message?.UnsubscribeMethods || {};
return !!unsubscribeMethods.OneClick; // Only method supported by API
};
export const isDMARCValidationFailure = hasFlag(FLAG_DMARC_FAIL);
export const isAutoFlaggedPhishing = hasFlag(FLAG_PHISHING_AUTO);
export const isSuspicious = hasBigFlag(FLAG_SUSPICIOUS);
export const isManualFlaggedHam = hasFlag(FLAG_HAM_MANUAL);
export const isAutoForwarder = hasBigFlag(FLAG_AUTO_FORWARDER);
export const isAutoForwardee = hasBigFlag(FLAG_AUTO_FORWARDEE);
export const isExternalEncrypted = (message: Message) => isE2E(message) && !isInternal(message);
export const isPGPEncrypted = (message: Message) => isExternal(message) && isReceived(message) && isE2E(message);
export const inSigningPeriod = ({ Time = 0 }: Pick<Message, 'Time'>) =>
Time >= Math.max(SIGNATURE_START.USER, SIGNATURE_START.BULK);
export const isPGPInline = (message: Message) => isPGPEncrypted(message) && !isMIME(message);
export const isEO = (message?: Partial<Message>) => !!message?.Password;
export const addReceived = (Flags = 0) => setBit(Flags, MESSAGE_FLAGS.FLAG_RECEIVED);
export const isBounced = (message: Pick<Message, 'Sender' | 'Subject'>) => {
// we don't have a great way of determining when a message is bounced as the BE cannot offer us neither
// a specific header nor a specific flag. We hard-code the typical sender (the local part) and subject keywords
const { Sender, Subject } = message;
const matchesSender = getEmailParts(canonicalizeInternalEmail(Sender.Address))[0] === 'mailerdaemon';
const matchesSubject = [/delivery/i, /undelivered/i, /returned/i, /failure/i].some((regex) => regex.test(Subject));
return matchesSender && matchesSubject;
};
export const getSender = (message?: Pick<Message, 'Sender'>) => message?.Sender;
export const hasSimpleLoginSender = (message?: Pick<Message, 'Sender'>) => !!message?.Sender?.IsSimpleLogin;
export const hasProtonSender = (message?: Pick<Message, 'Sender'>) => !!message?.Sender?.IsProton;
export const getRecipients = (message?: Partial<Message>) => {
const { ToList = [], CCList = [], BCCList = [] } = message || {};
return [...ToList, ...CCList, ...BCCList];
};
export const getRecipientsAddresses = (message: Partial<Message>) =>
getRecipients(message)
.map(({ Address }) => Address || '')
.filter(identity);
/**
* Get date from message
*/
export const getDate = ({ Time = 0 }: Message) => new Date(Time * 1000);
export const getParsedHeaders = (message: Partial<Message> | undefined, parameter: string) => {
const { ParsedHeaders = {} } = message || {};
return ParsedHeaders[parameter];
};
export const getParsedHeadersFirstValue = (message: Partial<Message> | undefined, parameter: string) => {
const value = getParsedHeaders(message, parameter);
return Array.isArray(value) ? value[0] : value;
};
export const getParsedHeadersAsArray = (message: Partial<Message> | undefined, parameter: string) => {
const value = getParsedHeaders(message, parameter);
return value === undefined ? undefined : Array.isArray(value) ? value : [value];
};
export const getOriginalTo = (message?: Partial<Message>) => {
return getParsedHeadersFirstValue(message, 'X-Original-To') || '';
};
export const requireReadReceipt = (message?: Partial<Message>) => {
const dispositionNotificationTo = getParsedHeaders(message, 'Disposition-Notification-To') || ''; // ex: Andy <[email protected]>
if (!dispositionNotificationTo || isSent(message)) {
return false;
}
return true;
};
export const getListUnsubscribe = (message?: Message) => getParsedHeadersAsArray(message, 'List-Unsubscribe');
export const getListUnsubscribePost = (message?: Message) => getParsedHeadersAsArray(message, 'List-Unsubscribe-Post');
export const getAttachments = (message?: Partial<Message>) => message?.Attachments || [];
export const hasAttachments = (message?: Partial<Message>) => !!(message?.NumAttachments && message.NumAttachments > 0);
export const attachmentsSize = (message?: Partial<Message>) =>
getAttachments(message).reduce((acc, { Size = 0 } = {}) => acc + +Size, 0);
export const getHasOnlyIcsAttachments = (attachmentInfo?: Partial<Record<MIME_TYPES, AttachmentInfo>>) => {
if (!!attachmentInfo) {
const keys = Object.keys(attachmentInfo);
return keys.length > 0 && !keys.some((key) => !isICS(key));
}
return false;
};
export const isAutoReply = (message?: Partial<Message>) => {
const ParsedHeaders = message?.ParsedHeaders || {};
return AUTOREPLY_HEADERS.some((h) => h in ParsedHeaders);
};
export const isSentAutoReply = ({ Flags, ParsedHeaders = {} }: Message) => {
if (!isSent({ Flags })) {
return false;
}
if (isAuto({ Flags })) {
return true;
}
const autoReplyHeaderValues = [
['Auto-Submitted', 'auto-replied'],
['Precedence', 'auto_reply'],
['X-Precedence', 'auto_reply'],
['Delivered-To', 'autoresponder'],
];
// These headers are not always available. But we should check them to support
// outlook / mail autoresponses.
return (
AUTOREPLY_HEADERS.some((header) => header in ParsedHeaders) ||
autoReplyHeaderValues.some(([header, searchedValue]) =>
getParsedHeadersAsArray({ ParsedHeaders }, header)?.some((foundValue) => foundValue === searchedValue)
)
);
};
/**
* Format the subject to add the prefix only when the subject
* doesn't start with it
*/
export const formatSubject = (subject = '', prefix = '') => {
const hasPrefix = new RegExp(`^${prefix}`, 'i');
return hasPrefix.test(subject) ? subject : `${prefix} ${subject}`;
};
export const DRAFT_ID_PREFIX = 'draft';
export const ORIGINAL_MESSAGE = `------- Original Message -------`;
export const FORWARDED_MESSAGE = `------- Forwarded Message -------`;
export const RE_PREFIX = c('Message').t`Re:`;
export const FW_PREFIX = c('Message').t`Fw:`;
export const isNewsLetter = (message?: Pick<Message, 'ParsedHeaders'>) => {
const ParsedHeaders = message?.ParsedHeaders || {};
return LIST_HEADERS.some((h) => h in ParsedHeaders);
};
| 8,690 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/recipient.ts | import isTruthy from '@proton/utils/isTruthy';
import { validateEmailAddress } from '../helpers/email';
import { Recipient } from '../interfaces';
import { ContactEmail } from '../interfaces/contacts';
import { unescapeFromString } from '../sanitize/escape';
export const REGEX_RECIPIENT = /(.*?)\s*<([^>]*)>/;
const SEPARATOR_REGEX = /[,;]/;
/**
* Trim and remove surrounding chevrons
*/
export const clearValue = (value: string) => {
const trimmed = value.trim();
if (trimmed.startsWith('<') && trimmed.endsWith('>')) {
return trimmed.slice(1, -1);
}
return trimmed;
};
/**
* Split input content by comma or semicolon
*/
export const splitBySeparator = (input: string) => {
return input
.split(SEPARATOR_REGEX)
.map((value) => clearValue(value))
.filter(isTruthy);
};
/**
* Find in a string potential recipients separated by a space
*/
export const findRecipientsWithSpaceSeparator = (input: string) => {
// Do nothing if the input does not contain a space
// Otherwise, executing the logic might break the behaviour we have
// For example it will detect as valid input "[email protected]", but the user might want to type "[email protected]"
if (!input.includes(' ')) {
return [];
}
const emails = input.split(' ');
const clearedEmails = emails.map((email) => email.trim()).filter((email) => email.length > 0);
const isValid = clearedEmails.every((email) => validateEmailAddress(email));
return isValid ? clearedEmails : [];
};
export const inputToRecipient = (input: string) => {
// Remove potential unwanted HTML entities such as '­' from the string
const cleanInput = unescapeFromString(input);
const trimmedInput = cleanInput.trim();
const match = REGEX_RECIPIENT.exec(trimmedInput);
if (match !== null && (match[1] || match[2])) {
const trimmedMatches = match.map((match) => match.trim());
return {
Name: trimmedMatches[1],
Address: trimmedMatches[2] || trimmedMatches[1],
};
}
return {
Name: trimmedInput,
Address: trimmedInput,
};
};
/**
* Used in AddressesAutocomplete and AddressesAutocomplete v2 to detect recipients strings inside the input
*/
export const handleRecipientInputChange = (
newValue: string,
hasEmailPasting: boolean,
onAddRecipients: (recipients: Recipient[]) => void,
setInput: (val: string) => void
) => {
if (newValue === ';' || newValue === ',') {
return;
}
if (!hasEmailPasting) {
setInput(newValue);
return;
}
const values = newValue.split(SEPARATOR_REGEX).map((value) => clearValue(value));
if (values.length > 1) {
onAddRecipients(values.map(inputToRecipient));
setInput('');
return;
}
// Try to find recipients with space separator e.g. "[email protected] [email protected]"
const valuesWithSpaceBar = newValue.split(' ').map((val) => val.trim());
if (valuesWithSpaceBar.length > 0) {
const recipientsWithSpaceSeparator = findRecipientsWithSpaceSeparator(newValue);
if (recipientsWithSpaceSeparator.length > 0) {
onAddRecipients(recipientsWithSpaceSeparator.map(inputToRecipient));
setInput('');
return;
}
}
setInput(newValue);
};
export const contactToRecipient = (contact: ContactEmail, groupPath?: string) => ({
Name: contact.Name,
Address: contact.Email,
ContactID: contact.ContactID,
Group: groupPath,
});
export const majorToRecipient = (email: string) => ({
Name: email,
Address: email,
});
export const recipientToInput = (recipient: Recipient): string => {
if (recipient.Address && recipient.Name && recipient.Address !== recipient.Name) {
return `${recipient.Name} <${recipient.Address}>`;
}
if (recipient.Address === recipient.Name) {
return recipient.Address || '';
}
return `${recipient.Name} ${recipient.Address}`;
};
export const contactToInput = (contact: ContactEmail): string => recipientToInput(contactToRecipient(contact));
| 8,691 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/signature.ts | import { c } from 'ttag';
import { APPS, APPS_CONFIGURATION } from '../constants';
interface Options {
isReferralProgramLinkEnabled?: boolean;
referralProgramUserLink?: string;
}
export const getProtonMailSignature = ({
isReferralProgramLinkEnabled = false,
referralProgramUserLink,
}: Options = {}) => {
const link =
isReferralProgramLinkEnabled && referralProgramUserLink ? referralProgramUserLink : 'https://proton.me/';
// translator: full sentence is: "Sent with Proton Mail secure email"
const signature = c('Info').t`Sent with <a href="${link}" target="_blank">${
APPS_CONFIGURATION[APPS.PROTONMAIL].name
}</a> secure email.`;
return signature;
};
| 8,692 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/trackers.ts | import { TidyURL } from '@protontech/tidy-url';
import { captureMessage } from '@proton/shared/lib/helpers/sentry';
import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers';
export const getUTMTrackersFromURL = (originalURL: string) => {
// originalURL can be an mailto: link
try {
// Only parse http(s) URLs
try {
// new URL(originalURL) may crash if the URL is invalid on Safari
const { protocol } = new URL(originalURL);
if (!protocol.includes('http')) {
return undefined;
}
} catch {
return undefined;
}
/**
* Allow amp links. By default, they are being cleaned but too many links were broken.
* For example:
* - https://something.me/L0/https:%2F%2Fsomething-else.amazonaws.com%randomID
* Was cleaned to:
* - https://something-else.amazonaws.com/randomID
* Which was not working as expected when being opened.
*/
TidyURL.allow_amp = true;
const { url, info } = TidyURL.clean(originalURL);
/*
If we found removed elements or there is a difference between original link and cleaned link,
we have a tracker that we need to display in the privacy dropdown.
The original URL might also contain uppercase letters in the first part of the URL that will be updated by the library
e.g. https://Proton.me would become https://proton.me, and we don't want it to be detected as a tracker
*/
if (originalURL.toLowerCase() !== url.toLowerCase()) {
const utmTracker: MessageUTMTracker = {
originalURL,
cleanedURL: url,
removed: info.removed,
};
return { url, info, utmTracker };
}
return { url: originalURL, info, utmTracker: undefined };
} catch {
captureMessage('Failed to parse URL with trackers');
return undefined;
}
};
| 8,693 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/transformLinkify.ts | import LinkifyIt from 'linkify-it';
import { getUTMTrackersFromURL } from '@proton/shared/lib/mail/trackers';
import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers';
const linkifyInstance = new LinkifyIt();
const htmlEntities = (str = '') => {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
/**
* Convert plain text content with links to content with html links
* Input : `hello http://www.protonmail.com`
* Output : `hello <a target="_blank" rel="noreferrer nofollow noopener" href="http://protonmail.com">http://protonmail.com</a>`
*/
export const transformLinkify = ({
content = '',
target = '_blank',
rel = 'noreferrer nofollow noopener',
canCleanUTMTrackers = false,
onCleanUTMTrackers,
}: {
content?: string;
target?: string;
rel?: string;
canCleanUTMTrackers?: boolean;
onCleanUTMTrackers?: (utmTrackers: MessageUTMTracker[]) => void;
}) => {
const matches = linkifyInstance.match(content);
if (!matches) {
return htmlEntities(content);
}
const utmTrackers: MessageUTMTracker[] = [];
let last = 0;
const result = matches.reduce<string[]>((result, match) => {
if (last < match.index) {
result.push(htmlEntities(content.slice(last, match.index)));
}
result.push(`<a target="${target}" rel="${rel}" href="`);
const UTMTrackersResult = canCleanUTMTrackers ? getUTMTrackersFromURL(match.url) : undefined;
// Clean trackers in plaintext messages
if (UTMTrackersResult) {
result.push(UTMTrackersResult.url);
if (UTMTrackersResult.utmTracker) {
utmTrackers.push(UTMTrackersResult.utmTracker);
}
} else {
result.push(match.url);
}
result.push('">');
result.push(match.text);
result.push('</a>');
last = match.lastIndex;
return result;
}, []);
// Push all trackers found to mail redux store
if (utmTrackers.length > 0) {
onCleanUTMTrackers?.(utmTrackers);
}
if (last < content.length) {
result.push(htmlEntities(content.slice(last)));
}
return result.join('');
};
| 8,694 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/eo/constants.ts | import { Address, MailSettings, UserSettings } from '../../interfaces';
import { AUTO_SAVE_CONTACTS, DEFAULT_MAILSETTINGS, IMAGE_PROXY_FLAGS, SHOW_IMAGES } from '../mailSettings';
export const eoDefaultUserSettings = {
Referral: undefined,
} as UserSettings;
export const EO_REPLY_NUM_ATTACHMENTS_LIMIT = 10;
export const EO_DEFAULT_MAILSETTINGS: MailSettings = {
...DEFAULT_MAILSETTINGS,
AutoSaveContacts: AUTO_SAVE_CONTACTS.DISABLED,
HideRemoteImages: SHOW_IMAGES.HIDE,
HideEmbeddedImages: SHOW_IMAGES.HIDE,
ImageProxy: IMAGE_PROXY_FLAGS.NONE,
};
export const eoDefaultAddress = {} as Address[];
| 8,695 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/legacyMessagesMigration/helpers.ts | import { fromUnixTime } from 'date-fns';
import { CryptoProxy, enums } from '@proton/crypto';
import chunk from '@proton/utils/chunk';
import { getApiError } from '../../api/helpers/apiErrorHelper';
import { getMessage, markAsBroken, queryMessageMetadata, updateBody } from '../../api/messages';
import { API_CODES, MINUTE, SECOND } from '../../constants';
import { HTTP_ERROR_CODES } from '../../errors';
import { ApiError } from '../../fetch/ApiError';
import { wait } from '../../helpers/promise';
import { Api, SimpleMap } from '../../interfaces';
import { GetAddressKeys } from '../../interfaces/hooks/GetAddressKeys';
import { GetMessageResponse, MarkAsBrokenResponse, QueryMessageMetadataResponse } from '../../interfaces/mail/Message';
import { getPrimaryKey, splitKeys } from '../../keys';
const LABEL_LEGACY_MESSAGE = '11';
const QUERY_LEGACY_MESSAGES_MAX_PAGESIZE = 150;
const LEGACY_MESSAGES_CHUNK_SIZE = 5; // How many messages we want to decrypt and encrypt simultaneously
const RELAX_TIME = 5 * SECOND; // 5s . Time to wait (for other operations) after a batch of legacy messages has been migrated
const MAX_RETRIES = 5; // Maximum number of retries allowed for the migration to restart after an unexpected error
// For constant-time decryption we need to specify which ciphers might have been used to encrypt the legacy message.
// It is likely that only AES was used, but we are not 100% certain, so we go all the way.
const SUPPORTED_CIPHERS: Set<enums.symmetric> = new Set([
// idea = 1,
2, // tripledes
3, // cast5
// blowfish = 4,
7, // aes128
8, // aes192
9, // aes256
// twofish = 10,
]);
enum MIGRATION_STATUS {
NONE,
SUCCESS,
BROKEN,
ERROR,
SKIP, // message already migrated or deleted
}
/**
* Given a list of legacy message IDs, fetch, decrypt, re-encrypt and send them to API.
* If decryption fails, mark the message as broken.
*/
export const migrateSingle = async ({
id,
api,
getAddressKeys,
statusMap,
}: {
id: string;
api: Api;
getAddressKeys: GetAddressKeys;
statusMap: SimpleMap<MIGRATION_STATUS>;
}) => {
try {
// Get message and private keys
const { Message } = await api<GetMessageResponse>(getMessage(id));
if (!Message) {
throw new Error('Failed to get message');
}
const { ID, Time, Body, AddressID } = Message;
const addressKeys = await getAddressKeys(AddressID);
const { privateKeys } = splitKeys(addressKeys);
const { publicKey: primaryPublicKey } = getPrimaryKey(addressKeys) || {};
if (!primaryPublicKey) {
throw new Error('Failed to decrypt primary address key');
}
let decryptedBody: string;
try {
const decryptionResult = await CryptoProxy.decryptMessageLegacy({
armoredMessage: Body,
messageDate: fromUnixTime(Time),
decryptionKeys: privateKeys,
config: {
constantTimePKCS1Decryption: true,
constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: SUPPORTED_CIPHERS,
},
});
// Simple sanity check to prevent migrating standard messages.
// We cannot simply look at the armoring headers before decryption because the backend has marked messages as "legacy"
// as long as they failed to parse, and we need to report them as "broken" if we fail to decrypt them
if (decryptionResult.signatures.length > 0) {
throw new Error('Legacy message expected');
}
decryptedBody = decryptionResult.data;
} catch {
// mark as broken
const { Code, Error: error } = await api<MarkAsBrokenResponse>(markAsBroken(id));
if (error || Code !== API_CODES.SINGLE_SUCCESS) {
throw new Error('Failed to mark message as broken');
}
// nothing more to do
return;
}
// Re-encrypt message body. Use the primary key (first in the array) for re-encryption
// We cannot sign the message, since we cannot determine its authenticity. Any original signature is lost.
const { message: newEncryptedBody } = await CryptoProxy.encryptMessage({
textData: decryptedBody,
encryptionKeys: primaryPublicKey,
});
// Send re-encrypted message to API
await api({
...updateBody(ID, { Body: newEncryptedBody }),
// lowest priority
headers: { Priority: 'u=7' },
});
} catch (e) {
// Status '422' is returned if the message is already migrated or it has been deleted.
// The former case could happen when the user has logged into multiple devices, and multiple instances
// of the migration process are running in parallel.
// In both cases, we do not want to retry the migration on the affected messages.
const shouldSkip = e instanceof ApiError && getApiError(e).status === HTTP_ERROR_CODES.UNPROCESSABLE_ENTITY;
statusMap[id] = shouldSkip ? MIGRATION_STATUS.SKIP : MIGRATION_STATUS.ERROR;
}
};
/**
* Re-encrypt the given legacy messages in batches, and send them to API
*/
export const migrateMultiple = async ({
messageIDs: originalMessageIDs,
api,
getAddressKeys,
}: {
messageIDs: string[];
api: Api;
getAddressKeys: GetAddressKeys;
}): Promise<void> => {
let messageIDs = [...originalMessageIDs];
for (let retryNumber = 0; retryNumber < MAX_RETRIES; retryNumber++) {
const statusMap = messageIDs.reduce<SimpleMap<MIGRATION_STATUS>>((acc, id) => {
acc[id] = MIGRATION_STATUS.NONE;
return acc;
}, {});
// proceed to migrate in batches of messages, waiting some time in between each batch,
// we are not in a hurry and we don't want to burn the user's machine decrypting and re-encrypting
const batches = chunk(messageIDs, LEGACY_MESSAGES_CHUNK_SIZE);
for (const batch of batches) {
await Promise.all(
batch.map((id) =>
migrateSingle({
id,
api,
getAddressKeys,
statusMap,
})
)
);
await wait(RELAX_TIME);
}
messageIDs = messageIDs.filter((id) => statusMap[id] === MIGRATION_STATUS.ERROR);
// no more messages to migrate
if (!messageIDs.length) {
return;
}
// if some messages failed to be migrated (most likely due to API reachability issues),
// we wait before retrying
await wait(MINUTE);
}
};
/**
* Fetch legacy message IDs from the API. This is only meant to be used as part of the migration.
* @returns iterator-like object fetching a new page of results at every `next()` call.
*/
export const makeLegacyMessageIDsFetcher = (api: Api, pageSize = QUERY_LEGACY_MESSAGES_MAX_PAGESIZE) => {
const pageIterator = {
async next() {
const { Messages = [] } = await api<QueryMessageMetadataResponse>({
...queryMessageMetadata({
LabelID: [LABEL_LEGACY_MESSAGE],
// we always fetch page 0 because we assume the returned message IDs are migrated
// between one `next()` call and the following one.
Page: 0,
PageSize: pageSize,
}),
// lowest priority
headers: { Priority: 'u=7' },
});
if (Messages.length > 0) {
return { value: Messages, done: false };
}
return { value: [], done: true };
},
};
return pageIterator;
};
| 8,696 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/send/attachments.ts | import JSBI from 'jsbi';
import { CryptoProxy, PrivateKeyReference, PublicKeyReference, SessionKey } from '@proton/crypto';
import { binaryStringToArray, decodeBase64 } from '@proton/crypto/lib/utils';
import { MIME_TYPES } from '../../constants';
import { hasBitBigInt } from '../../helpers/bitset';
import { Attachment } from '../../interfaces/mail/Message';
import { Packets } from '../../interfaces/mail/crypto';
import { MESSAGE_FLAGS } from '../constants';
export const encryptAttachment = async (
data: Uint8Array | string,
{ name, type, size }: File = {} as File,
inline: boolean,
publicKeys: PublicKeyReference[],
privateKeys: PrivateKeyReference[] = []
): Promise<Packets> => {
const dataType = data instanceof Uint8Array ? 'binaryData' : 'textData';
const sessionKey = await CryptoProxy.generateSessionKey({ recipientKeys: publicKeys });
// we encrypt using `sessionKey` directly instead of `encryptionKeys` so that returned message only includes
// symmetrically encrypted data
const { message: encryptedData, signature } = await CryptoProxy.encryptMessage({
format: 'binary',
detached: privateKeys.length > 0, // Only relevant if private keys are given
[dataType]: data,
stripTrailingSpaces: dataType === 'textData',
sessionKey,
signingKeys: privateKeys,
});
const encryptedSessionKey = await CryptoProxy.encryptSessionKey({
...sessionKey,
encryptionKeys: publicKeys[0],
format: 'binary',
});
return {
Filename: name,
MIMEType: type as MIME_TYPES,
FileSize: size,
Inline: inline,
signature: signature,
Preview: data,
keys: encryptedSessionKey,
data: encryptedData,
};
};
export const getSessionKey = async (
attachment: Pick<Attachment, 'KeyPackets'>,
privateKeys: PrivateKeyReference[],
messageFlags?: number
): Promise<SessionKey> => {
// if (attachment.sessionKey) {
// return attachment;
// }
const keyPackets = binaryStringToArray(decodeBase64(attachment.KeyPackets) || '');
const options = {
binaryMessage: keyPackets,
decryptionKeys: privateKeys,
config: {
allowForwardedMessages: hasBitBigInt(JSBI.BigInt(messageFlags || 0), MESSAGE_FLAGS.FLAG_AUTO_FORWARDEE),
},
};
// if (isOutside()) {
// options.passwords = [eoStore.getPassword()];
// } else {
// options.privateKeys = keysModel.getPrivateKeys(message.AddressID);
// }
const sessionKey = await CryptoProxy.decryptSessionKey(options);
if (sessionKey === undefined) {
throw new Error('Error while decrypting session keys');
}
return sessionKey;
};
export const getEOSessionKey = async (attachment: Attachment, password: string): Promise<SessionKey> => {
const keyPackets = binaryStringToArray(decodeBase64(attachment.KeyPackets) || '');
const options = { binaryMessage: keyPackets, passwords: [password] };
const sessionKey = await CryptoProxy.decryptSessionKey(options);
if (sessionKey === undefined) {
throw new Error('Error while decrypting session keys');
}
return sessionKey;
};
| 8,697 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/send/generatePackages.ts | import { PrivateKeyReference, PublicKeyReference } from '@proton/crypto';
import { Attachment, Message } from '../../interfaces/mail/Message';
import { AttachmentDirect, PackageDirect, SendPreferences } from '../../interfaces/mail/crypto';
import { RequireOnly, SimpleMap } from '../../interfaces/utils';
import { encryptPackages } from './sendEncrypt';
import { attachSubPackages } from './sendSubPackages';
import { generateTopPackages } from './sendTopPackages';
const generatePackages = async ({
message,
emails,
sendPreferencesMap,
attachments,
attachmentData,
publicKeys,
privateKeys,
}: {
message: RequireOnly<Message, 'Body' | 'MIMEType'>;
emails: string[];
sendPreferencesMap: SimpleMap<SendPreferences>;
attachments: Attachment[];
attachmentData: { attachment: AttachmentDirect; data: string };
publicKeys: PublicKeyReference[];
privateKeys: PrivateKeyReference[];
}): Promise<SimpleMap<PackageDirect>> => {
// There are two packages to be generated for the payload.
// The Packages in the request body, called here top-level packages
// The Packages inside Packages.addresses, called subpackages here
let packages = generateTopPackages({
message,
sendPreferencesMap,
attachmentData,
});
packages = await attachSubPackages({
packages,
attachments,
emails,
sendPreferencesMap,
});
return encryptPackages({
packages,
attachments,
publicKeys,
privateKeys,
message,
});
};
export default generatePackages;
| 8,698 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail | petrpan-code/ProtonMail/WebClients/packages/shared/lib/mail/send/getSendPreferences.ts | import { Message } from '../../interfaces/mail/Message';
import { SendPreferences } from '../../interfaces/mail/crypto';
import { EncryptionPreferences } from '../encryptionPreferences';
import { isEO, isSign } from '../messages';
import { getPGPSchemeAndMimeType } from './sendPreferences';
/**
* Get the send preferences for sending a message based on the encryption preferences
* for sending to an email address, and the message preferences.
*/
const getSendPreferences = (
encryptionPreferences: EncryptionPreferences,
message?: Partial<Message>
): SendPreferences => {
const {
encrypt,
sign,
sendKey,
isSendKeyPinned,
hasApiKeys,
hasPinnedKeys,
warnings,
error,
ktVerificationResult,
isInternalWithDisabledE2EEForMail,
} = encryptionPreferences;
const isEncryptedToOutside = isEO(message);
// override encrypt if necessary
const newEncrypt = isInternalWithDisabledE2EEForMail ? false : encrypt || isEncryptedToOutside;
// override sign if necessary
// (i.e. when the contact sign preference is false and the user toggles "Sign" on the composer)
const newSign = isEncryptedToOutside || isInternalWithDisabledE2EEForMail ? false : sign || isSign(message);
// cast PGP scheme into what API expects. Override if necessary
const { pgpScheme, mimeType } = getPGPSchemeAndMimeType({ ...encryptionPreferences, sign: newSign }, message);
return {
encrypt: newEncrypt,
sign: newSign,
pgpScheme,
mimeType,
publicKeys: sendKey ? [sendKey] : undefined,
isPublicKeyPinned: isSendKeyPinned,
hasApiKeys,
hasPinnedKeys,
warnings,
error,
ktVerificationResult,
encryptionDisabled: isInternalWithDisabledE2EEForMail,
};
};
export default getSendPreferences;
| 8,699 |
Subsets and Splits