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/key-transparency/lib/verification
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/self-audit/sklAudit.ts
import { PublicKeyReference } from '@proton/crypto'; import { FetchedSignedKeyList } from '@proton/shared/lib/interfaces'; import { Epoch, Proof } from '../../interfaces'; import { verifySKLSignature } from '../verifyKeys'; import { verifyProofOfAbsenceForRevision, verifyProofOfExistenceOrObsolescence } from '../verifyProofs'; export enum SKLAuditStatus { Deleted, Obsolete, ExistentUnverified, ExistentVerified, } export interface SKLAuditResult { revision: number; status: SKLAuditStatus; sklCreationTimestamp?: Date; signedKeyList: FetchedSignedKeyList | null; } export const auditSKL = async ( email: string, addressVerificationKeys: PublicKeyReference[], revision: number, signedKeyList: FetchedSignedKeyList | null, epoch: Epoch, proof: Proof ): Promise<SKLAuditResult> => { if (!signedKeyList) { await verifyProofOfAbsenceForRevision(proof, email, epoch.TreeHash, revision); return { revision, status: SKLAuditStatus.Deleted, signedKeyList }; } await verifyProofOfExistenceOrObsolescence(proof, email, epoch.TreeHash, signedKeyList); if (signedKeyList.Data && signedKeyList.Signature) { let sklCreationTimestamp = await verifySKLSignature( addressVerificationKeys, signedKeyList.Data, signedKeyList.Signature ); if (sklCreationTimestamp === null) { return { revision, status: SKLAuditStatus.ExistentUnverified, signedKeyList }; } else { return { revision, status: SKLAuditStatus.ExistentVerified, sklCreationTimestamp, signedKeyList }; } } else { return { revision, status: SKLAuditStatus.Obsolete, signedKeyList }; } };
7,400
0
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/self-audit/verifyLocalStorage.ts
import { PrivateKeyReference } from '@proton/crypto'; import { Api, KTLocalStorageAPI } from '@proton/shared/lib/interfaces'; import { getParsedSignedKeyList } from '@proton/shared/lib/keys'; import { fetchProof, fetchSignedKeyList } from '../../helpers/apiHelpers'; import { KeyTransparencyError, getEmailDomain, isTimestampOlderThanThreshold, isTimestampTooOld, throwKTError, } from '../../helpers/utils'; import { Epoch, KTBlobContent, KTBlobValuesWithInfo, KTPROOF_TYPE, LocalStorageAuditResult } from '../../interfaces'; import { encryptKTtoLS, getAllKTBlobValuesWithInfo, removeKTFromLS } from '../../storage/storageHelpers'; import { verifyProofOfExistenceOrObsolescence } from './../verifyProofs'; enum LocalStorageAuditStatus { Success, Failure, RetryLater, } const fetchSKLWithRevision = async (api: Api, email: string, revision: number, data: string) => { const includedSKL = await fetchSignedKeyList(api, revision, email); if (!includedSKL) { return throwKTError('Could not find new SKL with same revision', { email, revision }); } if (includedSKL.Data != data && includedSKL.ObsolescenceToken != data) { return throwKTError('SKL data has changed for revision', { email, revision, savedData: data, includedSKL, }); } return includedSKL; }; const getPrimaryKeyFingerprint = (blob: KTBlobContent) => { const sklItems = getParsedSignedKeyList(blob.data); if (sklItems?.length) { return sklItems[0].Fingerprint; } }; /** * Verify that the SKL(s) stored in one (or more) localStorage blob(s) * are correctly committed to KT */ const verifyKTBlobContent = async ( epoch: Epoch, ktBlobContent: KTBlobContent, api: Api ): Promise<LocalStorageAuditStatus> => { try { const { email, expectedMinEpochID, data, revision, creationTimestamp, isCatchall } = ktBlobContent; if (!isTimestampTooOld(creationTimestamp) && expectedMinEpochID > epoch.EpochID) { return LocalStorageAuditStatus.RetryLater; } const identifier = isCatchall ? getEmailDomain(email) : email; const proof = await fetchProof(epoch.EpochID, identifier, revision, api); if (proof.Type === KTPROOF_TYPE.ABSENCE) { if (isTimestampOlderThanThreshold(creationTimestamp)) { // Revision is old, might have been garbage collected return LocalStorageAuditStatus.Success; } else { if (isTimestampTooOld(creationTimestamp)) { return throwKTError('SKL revision was ignored after more than max allowed interval', { email, revision, }); } else { return LocalStorageAuditStatus.RetryLater; } } } const includedSKL = await fetchSKLWithRevision(api, identifier, revision, data); await verifyProofOfExistenceOrObsolescence(proof, identifier, epoch.TreeHash, includedSKL); return LocalStorageAuditStatus.Success; } catch (error: any) { if (error instanceof KeyTransparencyError) { return LocalStorageAuditStatus.Failure; } throw error; } }; /** * Check local storage for any previously stored KT blobs * that need to be verified */ export const checkLSBlobs = async ( userID: string, userPrivateKeys: PrivateKeyReference[], ktLSAPI: KTLocalStorageAPI, epoch: Epoch, api: Api ): Promise<LocalStorageAuditResult[]> => { const ktBlobsMap = await getAllKTBlobValuesWithInfo(userID, userPrivateKeys, ktLSAPI); let results = []; for (const { addressID, ktBlobsContent } of ktBlobsMap.values()) { let blobsToSave = []; for (const ktBlobContent of ktBlobsContent) { const result = await verifyKTBlobContent(epoch, ktBlobContent, api); if (result === LocalStorageAuditStatus.RetryLater) { blobsToSave.push(ktBlobContent); } else { results.push({ email: ktBlobContent.email, primaryKeyFingerprint: getPrimaryKeyFingerprint(ktBlobContent), success: result === LocalStorageAuditStatus.Success, }); } } await removeKTFromLS(userID, addressID, ktLSAPI); if (blobsToSave.length) { let blobs: KTBlobValuesWithInfo = { userID, addressID, ktBlobsContent: blobsToSave }; await encryptKTtoLS(blobs, userPrivateKeys[0], ktLSAPI); } } return results; };
7,401
0
petrpan-code/ProtonMail/WebClients/packages/key-transparency
petrpan-code/ProtonMail/WebClients/packages/key-transparency/test/index.spec.js
import { CryptoProxy } from '@proton/crypto'; import { Api as CryptoApi } from '@proton/crypto/lib/worker/api'; // Initialize CryptoProxy using a non-worker endpoint CryptoProxy.setEndpoint(new CryptoApi(), (endpoint) => endpoint.clearKeyStore()); const testsContext = require.context('.', true, /.spec.(js|tsx?)$/); testsContext.keys().forEach(testsContext);
7,402
0
petrpan-code/ProtonMail/WebClients/packages/key-transparency
petrpan-code/ProtonMail/WebClients/packages/key-transparency/test/karma.conf.js
const karmaJasmine = require('karma-jasmine'); const karmaWebpack = require('karma-webpack'); const karmaChromeLauncher = require('karma-chrome-launcher'); const { chromium } = require('playwright'); process.env.CHROME_BIN = chromium.executablePath(); module.exports = (config) => { config.set({ basePath: '..', frameworks: ['jasmine', 'webpack'], plugins: [karmaJasmine, karmaWebpack, karmaChromeLauncher], files: ['test/index.spec.js'], preprocessors: { 'test/index.spec.js': ['webpack'], }, webpack: { mode: 'development', resolve: { extensions: ['.js', '.ts', '.tsx'], fallback: { crypto: false, buffer: false, stream: false, }, // Mock JSBI to avoid using BigInt alias: { jsbi: 'jsbi/dist/jsbi-cjs.js', }, }, module: { rules: [ { test: /\.tsx?$/, use: [ { loader: 'ts-loader', options: { transpileOnly: true }, }, ], exclude: /node_modules\/(?!.*(bip39|pmcrypto))/, }, ], }, devtool: 'inline-source-map', }, mime: { 'text/x-typescript': ['ts', 'tsx'], }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, customLaunchers: { ChromeHeadlessCI: { base: 'ChromeHeadless', flags: ['--no-sandbox'], }, }, browsers: ['ChromeHeadlessCI'], singleRun: true, concurrency: Infinity, }); };
7,403
0
petrpan-code/ProtonMail/WebClients/packages/key-transparency
petrpan-code/ProtonMail/WebClients/packages/key-transparency/test/verifyCertificate.data.js
export const zeroSSLCertificateChain = `-----BEGIN CERTIFICATE-----\nMIIG8TCCBNmgAwIBAgIRAOkg8/OsI7NHzKoSZW40OIYwDQYJKoZIhvcNAQEMBQAw\nSzELMAkGA1UEBhMCQVQxEDAOBgNVBAoTB1plcm9TU0wxKjAoBgNVBAMTIVplcm9T\nU0wgUlNBIERvbWFpbiBTZWN1cmUgU2l0ZSBDQTAeFw0yMzA2MjAwMDAwMDBaFw0y\nMzA5MTgyMzU5NTlaMCcxJTAjBgNVBAMTHGVwb2NoLjEuMS5rZXl0cmFuc3BhcmVu\nY3kuY2gwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCyznpL7ybSqOIh\ndGrE8LL242v8HRGEKJ33NkJPSM7/EpOr4l15pPUs0Zp9vuEnzDrOmgennzBPs6Kt\nLnZJOvS1Mpf8QCf9AKP3Ps1fKMhJB6rnOAXLJFItQfkIGUZ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nPRmP6zjzZN7IKw0KKP/32+IVQtQi0Cdd4Xn+GOdwiK1O5tmLOsbdJ1Fu/7xk9TND\nTwIDAQABo4IBRjCCAUIwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYw\nSwYIKwYBBQUHAQEEPzA9MDsGCCsGAQUFBzAChi9odHRwOi8vYXBwcy5pZGVudHJ1\nc3QuY29tL3Jvb3RzL2RzdHJvb3RjYXgzLnA3YzAfBgNVHSMEGDAWgBTEp7Gkeyxx\n+tvhS5B1/8QVYIWJEDBUBgNVHSAETTBLMAgGBmeBDAECATA/BgsrBgEEAYLfEwEB\nATAwMC4GCCsGAQUFBwIBFiJodHRwOi8vY3BzLnJvb3QteDEubGV0c2VuY3J5cHQu\nb3JnMDwGA1UdHwQ1MDMwMaAvoC2GK2h0dHA6Ly9jcmwuaWRlbnRydXN0LmNvbS9E\nU1RST09UQ0FYM0NSTC5jcmwwHQYDVR0OBBYEFHm0WeZ7tuXkAXOACIjIGlj26Ztu\nMA0GCSqGSIb3DQEBCwUAA4IBAQAKcwBslm7/DlLQrt2M51oGrS+o44+/yQoDFVDC\n5WxCu2+b9LRPwkSICHXM6webFGJueN7sJ7o5XPWioW5WlHAQU7G75K/QosMrAdSW\n9MUgNTP52GE24HGNtLi1qoJFlcDyqSMo59ahy2cI2qBDLKobkx/J3vWraV0T9VuG\nWCLKTVXkcGdtwlfFRjlBz4pYg1htmf5X6DYO8A4jqv2Il9DjXA6USbW1FzXSLr9O\nhe8Y4IWS6wY7bCkjCWDcRQJMEhg76fsO3txE+FiYruq9RUWhiF1myv4Q6W+CyBFC\nDfvp7OOGAN6dEOM4+qR9sdjoSYKEBpsr6GtPAQw4dy753ec5\n-----END CERTIFICATE-----`;
7,404
0
petrpan-code/ProtonMail/WebClients/packages/key-transparency
petrpan-code/ProtonMail/WebClients/packages/key-transparency/test/verifyCertificates.spec.js
import { Integer as asn1jsInteger } from 'asn1js'; import { HOUR, SECOND, YEAR } from '@proton/shared/lib/constants'; import { KT_CERTIFICATE_ISSUER } from '../lib'; import { parseCertChain, parseCertificate, verifyAltName, verifyCertChain, verifySCT, } from '../lib/verification/verifyCertificates'; import { letsEncryptCertificateChain, zeroSSLCertificateChain } from './verifyCertificate.data'; import { epoch } from './verifyKeys.data'; describe('certificate transparency', () => { it('should fail to parse with corrupt certificate', () => { let errorThrown = true; try { parseCertificate('corrupt'); errorThrown = false; } catch (err) { expect(err.message).toEqual("Object's schema was not verified against input data for Certificate"); } expect(errorThrown).toEqual(true); }); it('should fail in verifyAltName with missing extensions', () => { const { Certificate, ChainHash, EpochID, CertificateTime } = epoch; const [cert] = parseCertChain(Certificate); const { extensions, ...certNoExt } = cert; let errorThrown = true; try { verifyAltName(certNoExt, ChainHash, EpochID, CertificateTime); errorThrown = false; } catch (err) { expect(err.message).toEqual('Epoch certificate does not have extensions'); } expect(errorThrown).toEqual(true); }); it('should fail in verifyAltName with missing AltName extension', () => { const { Certificate, ChainHash, EpochID, CertificateTime } = epoch; const [cert] = parseCertChain(Certificate); const corruptExt = cert.extensions.filter((ext) => ext.extnID !== '2.5.29.17'); let errorThrown = true; try { verifyAltName({ ...cert, extensions: corruptExt }, ChainHash, EpochID, CertificateTime); errorThrown = false; } catch (err) { expect(err.message).toEqual('Epoch certificate does not have AltName extension'); } expect(errorThrown).toEqual(true); }); it('should fail in verifySCT with corrupt certificate', async () => { const { Certificate } = epoch; const certChain = parseCertChain(Certificate); const epochCert = certChain[0]; const issuerCert = certChain[1]; epochCert.serialNumber = new asn1jsInteger(); let errorThrown = true; try { await verifySCT(epochCert, issuerCert); errorThrown = false; } catch (err) { expect(err.message).toEqual('The number of verified SCTs does not reach the number of operator threshold'); } expect(errorThrown).toEqual(true); }); }); describe('certificate chain verification', () => { it('Should verify 0SSL certificate', async () => { const now = new Date(1687219298 * SECOND + 24 * HOUR); // 24h after epoch was published. let error; try { await verifyCertChain(parseCertChain(zeroSSLCertificateChain), KT_CERTIFICATE_ISSUER.ZEROSSL, now); } catch (err) { error = err; } expect(error).toBeUndefined(); }); it('Should verify LE certificate', async () => { const now = new Date(1687259057 * SECOND + 24 * HOUR); // 24h after epoch was published. let error; try { await verifyCertChain(parseCertChain(letsEncryptCertificateChain), KT_CERTIFICATE_ISSUER.LETSENCRYPT, now); } catch (err) { error = err; } expect(error).toBeUndefined(); }); it('Should fail on expiry', async () => { const now = new Date(1687259057 * SECOND + 1 * YEAR); // 1year after epoch was published. let error; try { await verifyCertChain(parseCertChain(letsEncryptCertificateChain), KT_CERTIFICATE_ISSUER.LETSENCRYPT, now); } catch (err) { error = err; } expect(error).toBeDefined(); expect(error.message).toEqual("Epoch certificate did not pass verification against issuer's certificate chain"); }); it('Should fail if the certificate is in the future', async () => { const now = new Date(1687259057 * SECOND - 1 * YEAR); // 1year before epoch was published. let error; try { await verifyCertChain(parseCertChain(letsEncryptCertificateChain), KT_CERTIFICATE_ISSUER.LETSENCRYPT, now); } catch (err) { error = err; } expect(error).toBeDefined(); expect(error.message).toEqual("Epoch certificate did not pass verification against issuer's certificate chain"); }); it('Should fail if the certificate chain is broken', async () => { const now = new Date(1687259057 * SECOND + 24 * HOUR); // 24h after epoch was published. let error; try { const zeroSSLChain = parseCertChain(zeroSSLCertificateChain); const letsEncryptChain = parseCertChain(letsEncryptCertificateChain); const chain = [letsEncryptChain[0], ...zeroSSLChain.slice(1)]; await verifyCertChain(chain, KT_CERTIFICATE_ISSUER.LETSENCRYPT, now); } catch (err) { error = err; } expect(error).toBeDefined(); expect(error.message).toEqual("Epoch certificate did not pass verification against issuer's certificate chain"); }); });
7,405
0
petrpan-code/ProtonMail/WebClients/packages/key-transparency
petrpan-code/ProtonMail/WebClients/packages/key-transparency/test/verifyKeys.data.js
export const testEmail = 'testkt@kt.proton.black'; export const keyList = [ { Flags: 3, PublicKey: '-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: ProtonMail\n\nxjMEYV78vBYJKwYBBAHaRw8BAQdATzuHJEfffnkkxR6voPu8hMI30ZleJZ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mU9jXvIFgLSZSUKR/neLC1SY7BneIQtGsnW38o\n5vteZAqhCqAFITdxCfbIRZtUB56nBCjrRFj/vr6nVUUOUFHf/RZ6FFOmLbsl\nHwON9EUpRK8/JVFt6yLryuSbGRGYLSh8glAAx30oOvn3aOa8kQfal7viUj1u\nWv38RXhApDvtX1hQq6OThD20i+/mPHx5i4HOrRF6B3vwv2zlLKFy9TlDAtni\nN49MsN4tTXVl7yDBcKlwpE1oNiT33PfNk0cBTCwKXVMbE/GTnJFknA0JcQd8\nINfMXLuO5T6+gWgxf5boqSqltycTAZbgCcg+zgriXWuy6znuGbsG33UWY413\n5Is79U/IWqxp7sSmlS7V3egfjf3MX8hNkMSK+ctuBi/9hkeL8l3QpVFv+mqF\nr8M4WGAXRgdIQ0AOIaeyfmQqdHDqaUX72afcfmv7xrbzNN3OZsMjyc6MxFNG\n527vnyxq9fuVFVyTJLyVt+OYVaVKXSbW9Epr1JkcvZVnGNg5IVxZlv2R+ZmS\n4g6iBjn7pFJNJgL2rk6ncw==\n=14Zn\n-----END PGP PUBLIC KEY BLOCK-----\n', }, ]; export const skl = { MinEpochID: 32, MaxEpochID: 35, Data: '[{"Primary":1,"Flags":3,"Fingerprint":"0914a0b4373101b0e4cf43b724d52f7a8c354499","SHA256Fingerprints":["99dfe8acfa4e091fb81c88dca947cf05fc2e764332cd20484ddea016f3ef1c35","ac0f9568fc061b980cb02fb5b29471460f065353a2375c6f30fc4465c903f26e"]},{"Primary":0,"Flags":3,"Fingerprint":"59f1af56b673645834574e705ffcf74f485dc81a","SHA256Fingerprints":["8ccca8278be421752a659eadffd0b1d3a7a0cf778d97254b2cea2f4ab7faef93","9e967080956e786bb098423853062b9c26193de48fb83107df8332828d0973c3"]},{"Primary":0,"Flags":3,"Fingerprint":"68ec39a2f0c0bf87c1a3ee6c03301a8551e6040c","SHA256Fingerprints":["57d5299ce1d187f1b606b6a7f45d8b21a4154fcd94e87d39cdd60aa11207129a","490afb29e10416fcac60889a3e8841b7063eb4eeb6f843abf6ffc83d14d7c1ea"]}]', Signature: '-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwnUEARYKAAYFAmFfBeIAIQkQJNUveow1RJkWIQQJFKC0NzEBsOTPQ7ck1S96\r\njDVEmWQ1AQC1mZcKKhL9Ub9gX/HI6s3QeCG40zKG57g64BhmcNM2dAD/UhZv\r\nT2eWnpQ5JeboHlSsw1m+RRGwtqQ+u4al9F6o7Ac=\r\n=CiSs\r\n-----END PGP SIGNATURE-----\r\n', }; export const epoch = { EpochID: 1693, TreeHash: '3b835a76edff5e1976438e2ac2f2e0631adbe52764f19b551dcc5521fe53144f', ChainHash: '8a99830caa5c0c0212f62677da46da14333fa307d5f02549571fe62a129b6052', ClaimedTime: 1675950298, Certificate: '-----BEGIN CERTIFICATE-----\nMIIGrjCCBZagAwIBAgISA423yCKymci5m7/5elvaRu+cMA0GCSqGSIb3DQEBCwUA\nMDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD\nEwJSMzAeFw0yMzAyMDkxMjQ0NTdaFw0yMzA1MTAxMjQ0NTZaMCoxKDAmBgNVBAMT\nH2Vwb2NoLjE2OTMuMC5rZXl0cmFuc3BhcmVuY3kuY2gwggIiMA0GCSqGSIb3DQEB\nAQUAA4ICDwAwggIKAoICAQDgaKSzIDrdrSRS/C0G7/V0yri/8+Zcfua1gRbs7Uev\nwbRc1bdKzBBdeOx8dxCytiOGtr+VGWHbewkODOC8jUqz5Uo3tqbU19ilv6q8Ajcr\n5tnFODN/T+5DaIuBh75IT+W7b0smlkyEWiK4EZCV8gyeUXB7j8f80MU9igK/sNie\n1C3wH1tmvXbK5VEAvx+/YpYSdgUC61UkndKz2FZiA3kdjtRxSn3gzDlvwkW91s9d\n/3yx/CceMgPkZTXTrtU8HEtkK132VpwIftb59EzE2xSaZXT1jKzUTvU7X+uF2bL4\n4kzxzxNYDl2/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BDLKobkx/J3vWraV0T9VuG\nWCLKTVXkcGdtwlfFRjlBz4pYg1htmf5X6DYO8A4jqv2Il9DjXA6USbW1FzXSLr9O\nhe8Y4IWS6wY7bCkjCWDcRQJMEhg76fsO3txE+FiYruq9RUWhiF1myv4Q6W+CyBFC\nDfvp7OOGAN6dEOM4+qR9sdjoSYKEBpsr6GtPAQw4dy753ec5\n-----END CERTIFICATE-----', CertificateIssuer: 0, CertificateTime: 1675950262, Domain: 'keytransparency.ch', PrevChainHash: 'a4b099108a6c6159e4f4f3c0e2f8f58c3feec2b127e7e2895551e78dcc8d9b2c', }; export const proof = { Code: 1000, Neighbors: [ 'c047210ea071ed441640ccbe8ac83ac4bdcba5776d16cde713cd349d58787afd', 'faf52f94c2103e8122138b0995672972393d411ffb203001e37eda12a69ab04c', 'aa52b5f7010b9d2111c9cf1ae8e630a87abe20bd26c5dd0fb06b974691fbc20c', 'b8fa3fc08a158cf139bffb30c9c1fc859df7b215adcce8a336a54181b39b22fa', null, 'e10253e36a62a07ec8690913ee50190a9e15de8de63452f4bb5d40e5feae1139', null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, ], Revision: 0, Proof: '02178c71a71dd0bcef6cb0d5a159b1c61a95159ca2b7ab501a31bec67e1acd0013b4d5b4af760c24b6e7d2752095a0bf8245ba44859369756215f92413196930bc251f3074e8b73a5fef7630420d9d2e18', Name: '178c71a71dd0bcef6cb0d5a159b1c61a95159ca2b7ab501a31bec67e1acd0013', };
7,406
0
petrpan-code/ProtonMail/WebClients/packages/key-transparency
petrpan-code/ProtonMail/WebClients/packages/key-transparency/test/vrf.data.js
/** * Test vectors as per appendix A section A.3., ECVRF-EDWARDS25519-SHA512-TAI, of draft-irtf-cfrg-vrf-10 */ export const testVectors = [ { pk: 'd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a', alpha: '', beta: '90cf1df3b703cce59e2a35b925d411164068269d7b2d29f3301c03dd757876ff66b71dda49d2de59d03450451af026798e8f81cd2e333de5cdf4f3e140fdd8ae', pi: '8657106690b5526245a92b003bb079ccd1a92130477671f6fc01ad16f26f723f5e8bd1839b414219e8626d393787a192241fc442e6569e96c462f62b8079b9ed83ff2ee21c90c7c398802fdeebea4001', }, { pk: '3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c', alpha: '72', beta: 'eb4440665d3891d668e7e0fcaf587f1b4bd7fbfe99d0eb2211ccec90496310eb5e33821bc613efb94db5e5b54c70a848a0bef4553a41befc57663b56373a5031', pi: 'f3141cd382dc42909d19ec5110469e4feae18300e94f304590abdced48aed593f7eaf3eb2f1a968cba3f6e23b386aeeaab7b1ea44a256e811892e13eeae7c9f6ea8992557453eac11c4d5476b1f35a08', }, { pk: 'fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025', alpha: 'af82', beta: '645427e5d00c62a23fb703732fa5d892940935942101e456ecca7bb217c61c452118fec1219202a0edcf038bb6373241578be7217ba85a2687f7a0310b2df19f', pi: '9bc0f79119cc5604bf02d23b4caede71393cedfbb191434dd016d30177ccbf80e29dc513c01c3a980e0e545bcd848222d08a6c3e3665ff5a4cab13a643bef812e284c6b2ee063a2cb4f456794723ad0a', }, ];
7,407
0
petrpan-code/ProtonMail/WebClients/packages/key-transparency
petrpan-code/ProtonMail/WebClients/packages/key-transparency/test/vrf.spec.js
import { arrayToHexString, hexStringToArray } from '@proton/crypto/lib/utils'; import { vrfVerify } from '../lib/verification/vrf'; import { testVectors } from './vrf.data'; describe('vrf', () => { it('should verify the test vectors', async () => { for (const testVector of testVectors) { const beta = await vrfVerify( hexStringToArray(testVector.alpha), hexStringToArray(testVector.pi), hexStringToArray(testVector.pk) ); expect(arrayToHexString(beta)).toEqual(testVector.beta); } }); });
7,408
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/.eslintrc.js
module.exports = { extends: ['@proton/eslint-config-proton'], parser: '@typescript-eslint/parser', parserOptions: { tsconfigRootDir: __dirname, project: './tsconfig.json', }, ignorePatterns: ['.eslintrc.js'], };
7,409
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/README.internal.md
# Metrics internal docs Docs for internal use can be found on [confluence](https://confluence.protontech.ch/pages/viewpage.action?pageId=121927830).
7,410
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/README.md
# Metrics A package to allow predefined metrics to be observed.
7,411
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/constants.ts
/** * Number of metrics to batch into a single request */ export const METRICS_BATCH_SIZE = 10; /** * Time in seconds between metrics requests */ export const METRICS_REQUEST_FREQUENCY_SECONDS = 5; /** * Maximum number of times an API call * will be retried before abandoning the request */ export const METRICS_MAX_ATTEMPTS = 10; /** * Time in seconds between retries if `retry-after` response header is empty */ export const METRICS_DEFAULT_RETRY_SECONDS = 5; /** * Time in seconds before a request timeouts */ export const METRICS_REQUEST_TIMEOUT_SECONDS = 15;
7,412
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/global.d.ts
import 'jest-fetch-mock';
7,413
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/index.ts
import { SECOND } from '@proton/shared/lib/constants'; import { METRICS_BATCH_SIZE, METRICS_REQUEST_FREQUENCY_SECONDS } from './constants'; import Counter from './lib/Counter'; import MetricsApi from './lib/MetricsApi'; import MetricsBase from './lib/MetricsBase'; import MetricsRequestService from './lib/MetricsRequestService'; import IMetricsRequestService from './lib/types/IMetricsRequestService'; import { WebCoreSessionRecoveryAbortTotal } from './types/web_core_session_recovery_abort_total_v1.schema'; import { WebCoreSessionRecoveryCancellationModalLoadTotal } from './types/web_core_session_recovery_cancellation_modal_load_total_v1.schema'; import { WebCoreSessionRecoveryConsumeTotal } from './types/web_core_session_recovery_consume_total_v1.schema'; import { WebCoreSessionRecoveryInitiationModalLoadTotal } from './types/web_core_session_recovery_initiation_modal_load_total_v1.schema'; import { WebCoreSessionRecoveryInitiationTotal } from './types/web_core_session_recovery_initiation_total_v1.schema'; import { WebCoreSessionRecoveryPasswordResetAvailableAccountModalLoadTotal } from './types/web_core_session_recovery_password_reset_available_account_modal_load_total_v1.schema'; import { WebCoreSessionRecoverySettingsUpdateTotal } from './types/web_core_session_recovery_settings_update_total_v1.schema'; import { WebCoreSignupAccountStepAccountCreationTotal } from './types/web_core_signup_accountStep_accountCreation_total_v2.schema.d'; import { WebCoreSignupBackButtonTotal } from './types/web_core_signup_backButton_total_v1.schema.d'; import { WebCoreSignupCongratulationsStepDisplayNameChoiceTotal } from './types/web_core_signup_congratulationsStep_displayNameChoice_total_v2.schema.d'; import { WebCoreSignupExploreStepLoginTotal } from './types/web_core_signup_exploreStep_login_total_v2.schema.d'; import { WebCoreSignupLoadingStepAccountSetupTotal } from './types/web_core_signup_loadingStep_accountSetup_total_v2.schema.d'; import { WebCoreSignupPageLoadTotal } from './types/web_core_signup_pageLoad_total_v1.schema.d'; import { WebCoreSignupPaymentStepPaymentTotal } from './types/web_core_signup_paymentStep_payment_total_v2.schema.d'; import { WebCoreSignupRecoveryStepSetRecoveryMethodTotal } from './types/web_core_signup_recoveryStep_setRecoveryMethod_total_v2.schema.d'; import { WebCoreSignupReferralStepPlanSelectionTotal } from './types/web_core_signup_referralStep_planSelection_total_v2.schema.d'; import { WebCoreSignupUpsellStepPlanSelectionTotal } from './types/web_core_signup_upsellStep_planSelection_total_v2.schema.d'; import { WebCoreSignupVerificationStepVerificationTotal } from './types/web_core_signup_verificationStep_verification_total_v2.schema.d'; import { WebCoreVpnSingleSignupFetchDependencies2Total } from './types/web_core_vpn_single_signup_fetchDependencies_2_total_v1.schema'; import { WebCoreVpnSingleSignupPageLoad2Total } from './types/web_core_vpn_single_signup_pageLoad_2_total_v1.schema'; import { WebCoreVpnSingleSignupPasswordSelectionStep2Total } from './types/web_core_vpn_single_signup_passwordSelection_step_2_total_v1.schema'; import { WebCoreVpnSingleSignupStep1AccountCreation2Total } from './types/web_core_vpn_single_signup_step1_accountCreation_2_total_v1.schema'; import { WebCoreVpnSingleSignupStep1CurrencyChange2Total } from './types/web_core_vpn_single_signup_step1_currencyChange_2_total_v1.schema'; import { WebCoreVpnSingleSignupStep1CycleChange2Total } from './types/web_core_vpn_single_signup_step1_cycleChange_2_total_v1.schema'; import { WebCoreVpnSingleSignupStep1Interaction2Total } from './types/web_core_vpn_single_signup_step1_interaction_2_total_v1.schema'; import { WebCoreVpnSingleSignupStep1Payment2Total } from './types/web_core_vpn_single_signup_step1_payment_2_total_v1.schema'; import { WebCoreVpnSingleSignupStep2Setup3Total } from './types/web_core_vpn_single_signup_step2_setup_3_total_v1.schema'; import { WebCoreVpnSingleSignupStep3Complete2Total } from './types/web_core_vpn_single_signup_step3_complete_2_total_v1.schema'; import { WebCoreVpnSingleSignupStep4OrgSetupTotal } from './types/web_core_vpn_single_signup_step4_orgSetup_total_v1.schema'; import { WebCoreVpnSingleSignupStep4Setup2Total } from './types/web_core_vpn_single_signup_step4_setup_2_total_v1.schema'; import { WebPaymentsSubscriptionStepsTotal } from './types/web_payments_subscription_steps_total_v1.schema'; import { WebPaymentsSubscriptionTotal } from './types/web_payments_subscription_total_v1.schema'; export * from './lib/observeApiError'; export { default as observeApiError } from './lib/observeApiError'; class Metrics extends MetricsBase { public core_signup_pageLoad_total: Counter<WebCoreSignupPageLoadTotal>; public core_signup_accountStep_accountCreation_total: Counter<WebCoreSignupAccountStepAccountCreationTotal>; public core_signup_verificationStep_verification_total: Counter<WebCoreSignupVerificationStepVerificationTotal>; public core_signup_upsellStep_planSelection_total: Counter<WebCoreSignupUpsellStepPlanSelectionTotal>; public core_signup_paymentStep_payment_total: Counter<WebCoreSignupPaymentStepPaymentTotal>; public core_signup_loadingStep_accountSetup_total: Counter<WebCoreSignupLoadingStepAccountSetupTotal>; public core_signup_congratulationsStep_displayNameChoice_total: Counter<WebCoreSignupCongratulationsStepDisplayNameChoiceTotal>; public core_signup_exploreStep_login_total: Counter<WebCoreSignupExploreStepLoginTotal>; public core_signup_recoveryStep_setRecoveryMethod_total: Counter<WebCoreSignupRecoveryStepSetRecoveryMethodTotal>; public core_signup_referralStep_planSelection_total: Counter<WebCoreSignupReferralStepPlanSelectionTotal>; public core_signup_backButton_total: Counter<WebCoreSignupBackButtonTotal>; public core_vpn_single_signup_pageLoad_2_total: Counter<WebCoreVpnSingleSignupPageLoad2Total>; public core_vpn_single_signup_fetchDependencies_2_total: Counter<WebCoreVpnSingleSignupFetchDependencies2Total>; public core_vpn_single_signup_step1_accountCreation_2_total: Counter<WebCoreVpnSingleSignupStep1AccountCreation2Total>; public core_vpn_single_signup_step1_interaction_2_total: Counter<WebCoreVpnSingleSignupStep1Interaction2Total>; public core_vpn_single_signup_step1_currencyChange_2_total: Counter<WebCoreVpnSingleSignupStep1CurrencyChange2Total>; public core_vpn_single_signup_step1_cycleChange_2_total: Counter<WebCoreVpnSingleSignupStep1CycleChange2Total>; public core_vpn_single_signup_step1_payment_2_total: Counter<WebCoreVpnSingleSignupStep1Payment2Total>; public core_vpn_single_signup_step2_setup_3_total: Counter<WebCoreVpnSingleSignupStep2Setup3Total>; public core_vpn_single_signup_passwordSelection_step_2_total: Counter<WebCoreVpnSingleSignupPasswordSelectionStep2Total>; public core_vpn_single_signup_step3_complete_2_total: Counter<WebCoreVpnSingleSignupStep3Complete2Total>; public core_vpn_single_signup_step4_setup_2_total: Counter<WebCoreVpnSingleSignupStep4Setup2Total>; public core_vpn_single_signup_step4_orgSetup_total: Counter<WebCoreVpnSingleSignupStep4OrgSetupTotal>; public payments_subscription_steps_total: Counter<WebPaymentsSubscriptionStepsTotal>; public payments_subscription_total: Counter<WebPaymentsSubscriptionTotal>; public core_session_recovery_initiation_modal_load_total: Counter<WebCoreSessionRecoveryInitiationModalLoadTotal>; public core_session_recovery_initiation_total: Counter<WebCoreSessionRecoveryInitiationTotal>; public core_session_recovery_abort_total: Counter<WebCoreSessionRecoveryAbortTotal>; public core_session_recovery_cancellation_modal_load_total: Counter<WebCoreSessionRecoveryCancellationModalLoadTotal>; public core_session_recovery_consume_total: Counter<WebCoreSessionRecoveryConsumeTotal>; public core_session_recovery_password_reset_available_account_modal_load_total: Counter<WebCoreSessionRecoveryPasswordResetAvailableAccountModalLoadTotal>; public core_session_recovery_settings_update_total: Counter<WebCoreSessionRecoverySettingsUpdateTotal>; constructor(requestService: IMetricsRequestService) { super(requestService); this.core_signup_pageLoad_total = new Counter<WebCoreSignupPageLoadTotal>( { name: 'web_core_signup_pageLoad_total', version: 1 }, this.requestService ); this.core_signup_accountStep_accountCreation_total = new Counter<WebCoreSignupAccountStepAccountCreationTotal>( { name: 'web_core_signup_accountStep_accountCreation_total', version: 2 }, this.requestService ); this.core_signup_verificationStep_verification_total = new Counter<WebCoreSignupVerificationStepVerificationTotal>( { name: 'web_core_signup_verificationStep_verification_total', version: 2 }, this.requestService ); this.core_signup_upsellStep_planSelection_total = new Counter<WebCoreSignupUpsellStepPlanSelectionTotal>( { name: 'web_core_signup_upsellStep_planSelection_total', version: 2 }, this.requestService ); this.core_signup_paymentStep_payment_total = new Counter<WebCoreSignupPaymentStepPaymentTotal>( { name: 'web_core_signup_paymentStep_payment_total', version: 2 }, this.requestService ); this.core_signup_loadingStep_accountSetup_total = new Counter<WebCoreSignupLoadingStepAccountSetupTotal>( { name: 'web_core_signup_loadingStep_accountSetup_total', version: 2 }, this.requestService ); this.core_signup_congratulationsStep_displayNameChoice_total = new Counter<WebCoreSignupCongratulationsStepDisplayNameChoiceTotal>( { name: 'web_core_signup_congratulationsStep_displayNameChoice_total', version: 2 }, this.requestService ); this.core_signup_exploreStep_login_total = new Counter<WebCoreSignupExploreStepLoginTotal>( { name: 'web_core_signup_exploreStep_login_total', version: 2 }, this.requestService ); this.core_signup_recoveryStep_setRecoveryMethod_total = new Counter<WebCoreSignupRecoveryStepSetRecoveryMethodTotal>( { name: 'web_core_signup_recoveryStep_setRecoveryMethod_total', version: 2 }, this.requestService ); this.core_signup_referralStep_planSelection_total = new Counter<WebCoreSignupReferralStepPlanSelectionTotal>( { name: 'web_core_signup_referralStep_planSelection_total', version: 2 }, this.requestService ); this.core_signup_backButton_total = new Counter<WebCoreSignupBackButtonTotal>( { name: 'web_core_signup_backButton_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_pageLoad_2_total = new Counter<WebCoreVpnSingleSignupPageLoad2Total>( { name: 'web_core_vpn_single_signup_pageLoad_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_fetchDependencies_2_total = new Counter<WebCoreVpnSingleSignupFetchDependencies2Total>( { name: 'web_core_vpn_single_signup_fetchDependencies_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_step1_interaction_2_total = new Counter<WebCoreVpnSingleSignupStep1Interaction2Total>( { name: 'web_core_vpn_single_signup_step1_interaction_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_step1_currencyChange_2_total = new Counter<WebCoreVpnSingleSignupStep1CurrencyChange2Total>( { name: 'web_core_vpn_single_signup_step1_currencyChange_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_step1_cycleChange_2_total = new Counter<WebCoreVpnSingleSignupStep1CycleChange2Total>( { name: 'web_core_vpn_single_signup_step1_cycleChange_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_step1_payment_2_total = new Counter<WebCoreVpnSingleSignupStep1Payment2Total>( { name: 'web_core_vpn_single_signup_step1_payment_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_step1_accountCreation_2_total = new Counter<WebCoreVpnSingleSignupStep1AccountCreation2Total>( { name: 'web_core_vpn_single_signup_step1_accountCreation_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_step2_setup_3_total = new Counter<WebCoreVpnSingleSignupStep2Setup3Total>( { name: 'web_core_vpn_single_signup_step2_setup_3_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_passwordSelection_step_2_total = new Counter<WebCoreVpnSingleSignupPasswordSelectionStep2Total>( { name: 'web_core_vpn_single_signup_passwordSelection_step_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_step3_complete_2_total = new Counter<WebCoreVpnSingleSignupStep3Complete2Total>( { name: 'web_core_vpn_single_signup_step3_complete_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_step4_setup_2_total = new Counter<WebCoreVpnSingleSignupStep4Setup2Total>( { name: 'web_core_vpn_single_signup_step4_setup_2_total', version: 1 }, this.requestService ); this.core_vpn_single_signup_step4_orgSetup_total = new Counter<WebCoreVpnSingleSignupStep4OrgSetupTotal>( { name: 'web_core_vpn_single_signup_step4_orgSetup_total', version: 1 }, this.requestService ); this.payments_subscription_steps_total = new Counter<WebPaymentsSubscriptionStepsTotal>( { name: 'web_payments_subscription_steps_total', version: 1 }, this.requestService ); this.payments_subscription_total = new Counter<WebPaymentsSubscriptionTotal>( { name: 'web_payments_subscription_total', version: 1 }, this.requestService ); this.core_session_recovery_initiation_modal_load_total = new Counter<WebCoreSessionRecoveryInitiationModalLoadTotal>( { name: 'web_core_session_recovery_initiation_modal_load_total', version: 1 }, this.requestService ); this.core_session_recovery_initiation_total = new Counter<WebCoreSessionRecoveryInitiationTotal>( { name: 'web_core_session_recovery_initiation_total', version: 1 }, this.requestService ); this.core_session_recovery_abort_total = new Counter<WebCoreSessionRecoveryAbortTotal>( { name: 'web_core_session_recovery_abort_total', version: 1 }, this.requestService ); this.core_session_recovery_cancellation_modal_load_total = new Counter<WebCoreSessionRecoveryCancellationModalLoadTotal>( { name: 'web_core_session_recovery_cancellation_modal_load_total', version: 1 }, this.requestService ); this.core_session_recovery_consume_total = new Counter<WebCoreSessionRecoveryConsumeTotal>( { name: 'web_core_session_recovery_consume_total', version: 1 }, this.requestService ); this.core_session_recovery_password_reset_available_account_modal_load_total = new Counter<WebCoreSessionRecoveryPasswordResetAvailableAccountModalLoadTotal>( { name: 'web_core_session_recovery_password_reset_available_account_modal_load_total', version: 1 }, this.requestService ); this.core_session_recovery_settings_update_total = new Counter<WebCoreSessionRecoverySettingsUpdateTotal>( { name: 'web_core_session_recovery_settings_update_total', version: 1 }, this.requestService ); } } const metricsApi = new MetricsApi(); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: METRICS_REQUEST_FREQUENCY_SECONDS * SECOND, size: METRICS_BATCH_SIZE, }, }); const metrics = new Metrics(metricsRequestService); export default metrics;
7,414
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/jest.config.js
module.exports = { setupFilesAfterEnv: ['./jest.setup.js'], preset: 'ts-jest', testRegex: 'tests/.*\\.test\\.ts$', clearMocks: true, collectCoverage: true, coverageReporters: ['text', 'lcov', 'cobertura'], coverageThreshold: { global: { branches: 90, functions: 100, lines: 97, statements: 97, }, }, };
7,415
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/jest.setup.js
require('jest-fetch-mock').enableMocks();
7,416
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/package.json
{ "name": "@proton/metrics", "description": "Metrics library", "scripts": { "check-types": "tsc", "generate-schema-types": "json2ts -i 'json-schema-registry/observability/client/web*.schema.json' -o types/ --no-additionalProperties", "lint": "eslint . --ext ts --quiet --cache", "test": "jest --coverage --runInBand --ci", "test:dev": "jest --watch", "update-schema-types": "rimraf json-schema-registry types && git clone $SCHEMA_REPOSITORY && yarn generate-schema-types" }, "dependencies": { "@proton/shared": "workspace:packages/shared", "json-schema-to-typescript": "^13.1.1" }, "devDependencies": { "@proton/eslint-config-proton": "workspace:^", "eslint": "^8.54.0", "jest": "^29.7.0", "jest-fetch-mock": "^3.0.3", "rimraf": "^5.0.5", "ts-jest": "^29.1.1", "typescript": "^5.3.2" } }
7,417
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/metrics/tsconfig.json
{ "extends": "../../tsconfig.base.json" }
7,418
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/Counter.ts
import Metric from './Metric'; import MetricSchema from './types/MetricSchema'; class Counter<D extends MetricSchema> extends Metric<D> { public increment(labels: D['Labels']) { this.addToRequestQueue({ Value: 1, Labels: labels, } as D); } } export default Counter;
7,419
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/Histogram.ts
import Metric from './Metric'; import MetricSchema from './types/MetricSchema'; class Histogram<D extends MetricSchema> extends Metric<D> { public observe(data: D) { this.addToRequestQueue(data); } } export default Histogram;
7,420
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/Metric.ts
import IMetricsRequestService from './types/IMetricsRequestService'; import MetricSchema from './types/MetricSchema'; import MetricVersions from './types/MetricVersions'; /** * Custom regex based on the following * - https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels * - https://gitlab.protontech.ch/proton/be/json-schema-registry */ const metricRegexp = /^[a-zA-Z]+(?:_[a-zA-Z0-9]+)*$/; function validateMetricName(name: string) { return metricRegexp.test(name); } abstract class Metric<D extends MetricSchema> { private name: string; private version: MetricVersions; private requestService: IMetricsRequestService; constructor(config: { name: string; version: MetricVersions }, requestService: IMetricsRequestService) { this.name = config.name; this.version = config.version; this.requestService = requestService; if (!validateMetricName(this.name)) { throw new Error(`Invalid metric name ${this.name}`); } } protected addToRequestQueue(data: D) { this.requestService.report({ Name: this.name, Version: this.version, Timestamp: Math.round(Date.now() / 1000), Data: data, }); } } export default Metric;
7,421
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/MetricsApi.ts
import { HTTP_STATUS_CODE, SECOND } from '@proton/shared/lib/constants'; import { getAppVersionHeaders, getUIDHeaders } from '@proton/shared/lib/fetch/headers'; import { wait } from '@proton/shared/lib/helpers/promise'; import { METRICS_DEFAULT_RETRY_SECONDS, METRICS_MAX_ATTEMPTS, METRICS_REQUEST_TIMEOUT_SECONDS } from './../constants'; import IMetricsApi from './types/IMetricsApi'; class MetricsApi implements IMetricsApi { private _authHeaders: { [key: string]: string }; private _versionHeaders: { [key: string]: string }; constructor({ uid, clientID, appVersion }: { uid?: string; clientID?: string; appVersion?: string } = {}) { this._authHeaders = this.getAuthHeaders(uid); this._versionHeaders = this.getVersionHeaders(clientID, appVersion); } public setAuthHeaders(uid: string) { this._authHeaders = this.getAuthHeaders(uid); } public setVersionHeaders(clientID: string, appVersion: string) { this._versionHeaders = this.getVersionHeaders(clientID, appVersion); } private async _fetchWithTimeout(requestInfo: RequestInfo | URL, requestInit: RequestInit) { const abortController = new AbortController(); const timeoutId = setTimeout(() => { abortController.abort(); }, METRICS_REQUEST_TIMEOUT_SECONDS * SECOND); return fetch(requestInfo, { signal: abortController.signal, ...requestInit, }).finally(() => { clearTimeout(timeoutId); }); } public async fetch( requestInfo: RequestInfo | URL, requestInit: RequestInit = {}, attempt: number = 1 ): Promise<Response | undefined> { try { const response = await this._fetchWithTimeout(requestInfo, { ...requestInit, headers: { ...requestInit?.headers, 'content-type': 'application/json', priority: 'u=6', ...this._authHeaders, ...this._versionHeaders, }, }); if (attempt >= METRICS_MAX_ATTEMPTS) { return; } if (response.status === HTTP_STATUS_CODE.TOO_MANY_REQUESTS) { const retryAfterSeconds = (() => { const retryHeader = response?.headers?.get('retry-after') || ''; const parsedInt = parseInt(retryHeader, 10); if (parsedInt <= 0 || isNaN(parsedInt)) { return METRICS_DEFAULT_RETRY_SECONDS; } return parsedInt; })(); await wait(retryAfterSeconds * SECOND); return await this.fetch(requestInfo, requestInit, attempt + 1); } return response; } catch (error: any) { if (error.name !== 'AbortError') { throw error; } if (attempt >= METRICS_MAX_ATTEMPTS) { return; } await wait(METRICS_DEFAULT_RETRY_SECONDS * SECOND); return await this.fetch(requestInfo, requestInit, attempt + 1); } } private getAuthHeaders(uid?: string) { if (!uid) { return {}; } return getUIDHeaders(uid); } private getVersionHeaders(clientID?: string, appVersion?: string) { if (!clientID || !appVersion) { return {}; } return getAppVersionHeaders(clientID, appVersion); } } export default MetricsApi;
7,422
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/MetricsBase.ts
import IMetricsRequestService from './types/IMetricsRequestService'; export default class MetricsBase { protected requestService: IMetricsRequestService; constructor(requestService: IMetricsRequestService) { this.requestService = requestService; } public init({ uid, clientID, appVersion }: { uid: string; clientID: string; appVersion: string }) { this.setAuthHeaders(uid); this.setVersionHeaders(clientID, appVersion); } public setVersionHeaders(clientID: string, appVersion: string) { this.requestService.api.setVersionHeaders(clientID, appVersion); } public setAuthHeaders(uid: string) { this.requestService.api.setAuthHeaders(uid); } public clearAuthHeaders() { this.requestService.api.setAuthHeaders(''); } public setReportMetrics(reportMetrics: boolean) { this.requestService.setReportMetrics(reportMetrics); } public processAllRequests() { return this.requestService.processAllRequests(); } public stopBatchingProcess() { return this.requestService.stopBatchingProcess(); } public startBatchingProcess() { return this.requestService.startBatchingProcess(); } }
7,423
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/MetricsRequestService.ts
import IMetricsApi from './types/IMetricsApi'; import IMetricsRequestService from './types/IMetricsRequestService'; import MetricsRequest from './types/MetricsRequest'; interface BatchOptions { frequency: number; size: number; } class MetricsRequestService implements IMetricsRequestService { public api: IMetricsApi; private _reportMetrics: boolean; private _requestQueue: MetricsRequest[]; private _batch?: BatchOptions; private _intervalId: ReturnType<typeof setInterval> | null; constructor( api: IMetricsApi, { reportMetrics, batch, }: { reportMetrics: boolean; batch?: BatchOptions; } ) { this.api = api; this._reportMetrics = reportMetrics; this._batch = (() => { if (batch === undefined) { return; } if (batch.frequency <= 0 || batch.size <= 0) { return; } return batch; })(); this._requestQueue = []; this._intervalId = null; } public startBatchingProcess() { if (this._intervalId !== null || this._batch === undefined) { return; } this._intervalId = setInterval(this.processNextBatch.bind(this), this._batch.frequency); } public stopBatchingProcess() { if (this._intervalId === null) { return; } clearInterval(this._intervalId); this._intervalId = null; } public async processAllRequests() { if (this._requestQueue.length === 0) { return; } const itemsToProcess = this._requestQueue; this.clearQueue(); await this.makeRequest(itemsToProcess); } public clearQueue() { this._requestQueue = []; } public setReportMetrics(reportMetrics: boolean) { this._reportMetrics = reportMetrics; } public report(request: MetricsRequest) { if (!this._reportMetrics) { return; } if (this._batch === undefined) { void this.makeRequest([request]); return; } if (this._intervalId === null) { this.startBatchingProcess(); } this._requestQueue.push(request); } private processNextBatch() { if (this._batch === undefined) { return; } const itemsToProcess = this._requestQueue.splice(0, this._batch.size); if (itemsToProcess.length === 0) { return; } return this.makeRequest(itemsToProcess); } private makeRequest(metrics: MetricsRequest[]) { return this.api.fetch('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: metrics }), }); } } export default MetricsRequestService;
7,424
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/observeApiError.ts
import { getApiError, getIsConnectionIssue } from '@proton/shared/lib/api/helpers/apiErrorHelper'; import { API_CUSTOM_ERROR_CODES } from '@proton/shared/lib/errors'; export type MetricsApiStatusTypes = '4xx' | '5xx' | 'failure'; export default function observeApiError( error: any, metricObserver: (status: MetricsApiStatusTypes) => void, ignoreCodes = [API_CUSTOM_ERROR_CODES.CARD_DECLINED, API_CUSTOM_ERROR_CODES.HUMAN_VERIFICATION_REQUIRED] ) { if (!error) { return; } const { status, code } = getApiError(error); if ( !status || status === -1 || error?.name === 'AbortError' || getIsConnectionIssue(error) || ignoreCodes.includes(code) ) { return; } if (status >= 500) { return metricObserver('5xx'); } if (status >= 400) { return metricObserver('4xx'); } return metricObserver('failure'); }
7,425
0
petrpan-code/ProtonMail/WebClients/packages/metrics/lib
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/types/IMetricsApi.ts
export default interface IMetricsApi { setAuthHeaders: (uid: string) => void; setVersionHeaders: (clientID: string, appVersion: string) => void; fetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit, retries?: number) => Promise<Response | void>; }
7,426
0
petrpan-code/ProtonMail/WebClients/packages/metrics/lib
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/types/IMetricsRequestService.ts
import IMetricsApi from './IMetricsApi'; import MetricsRequest from './MetricsRequest'; export default interface IMetricsRequestService { api: IMetricsApi; report: (request: MetricsRequest) => void; startBatchingProcess: () => void; stopBatchingProcess: () => void; processAllRequests: () => Promise<void>; clearQueue: () => void; setReportMetrics: (reportMetrics: boolean) => void; }
7,427
0
petrpan-code/ProtonMail/WebClients/packages/metrics/lib
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/types/MetricSchema.ts
export default interface MetricSchema { Value: number; Labels: Object; }
7,428
0
petrpan-code/ProtonMail/WebClients/packages/metrics/lib
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/types/MetricVersions.ts
type MetricVersions = 1 | 2; export default MetricVersions;
7,429
0
petrpan-code/ProtonMail/WebClients/packages/metrics/lib
petrpan-code/ProtonMail/WebClients/packages/metrics/lib/types/MetricsRequest.ts
import MetricVersions from './MetricVersions'; export default interface MetricsRequest { Name: string; Version: MetricVersions; Timestamp: number; Data: object; }
7,430
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/Counter.test.ts
import Counter from '../lib/Counter'; import MetricsApi from '../lib/MetricsApi'; import MetricsRequestService from '../lib/MetricsRequestService'; import MetricSchema from '../lib/types/MetricSchema'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); jest.mock('../lib/MetricsRequestService'); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); interface DefaultMetricSchema extends MetricSchema { Labels: { foo: 'bar'; }; } const time = new Date('2020-01-01'); describe('Counter', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { jest.clearAllTimers(); jest.setSystemTime(time); }); afterAll(() => { jest.useRealTimers(); }); it('construct correct metric report', () => { const name = 'name'; const version = 1; const counter = new Counter<DefaultMetricSchema>({ name, version }, metricsRequestService); counter.increment({ foo: 'bar' }); expect(metricsRequestService.report).toHaveBeenCalledWith({ Name: name, Version: version, Timestamp: time.getTime() / 1000, Data: { Value: 1, Labels: { foo: 'bar' }, }, }); }); });
7,431
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/Histogram.test.ts
import Histogram from '../lib/Histogram'; import MetricsApi from '../lib/MetricsApi'; import MetricsRequestService from '../lib/MetricsRequestService'; import MetricSchema from '../lib/types/MetricSchema'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); jest.mock('../lib/MetricsRequestService'); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); interface DefaultMetricSchema extends MetricSchema { Labels: { foo: 'bar'; }; } const time = new Date('2020-01-01'); describe('Histogram', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { jest.clearAllTimers(); jest.setSystemTime(time); }); afterAll(() => { jest.useRealTimers(); }); it('construct correct metric report', () => { const name = 'name'; const version = 1; const counter = new Histogram<DefaultMetricSchema>({ name, version }, metricsRequestService); const value = 123.456; counter.observe({ Value: value, Labels: { foo: 'bar' } }); expect(metricsRequestService.report).toHaveBeenCalledWith({ Name: name, Version: version, Timestamp: time.getTime() / 1000, Data: { Value: value, Labels: { foo: 'bar' }, }, }); }); });
7,432
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/Metric.test.ts
import Metric from '../lib/Metric'; import MetricsApi from '../lib/MetricsApi'; import MetricsRequestService from '../lib/MetricsRequestService'; import MetricSchema from '../lib/types/MetricSchema'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); jest.mock('../lib/MetricsRequestService'); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); class MetricInstance<D extends MetricSchema> extends Metric<D> {} interface DefaultMetricSchema extends MetricSchema { Labels: { foo: 'bar'; }; } describe('Metric', () => { it('does not throw when creating a metric with a valid name', () => { const validNames = ['name', 'hello_there', 'aAAa_2bB']; const version = 1; for (let i = 0; i < validNames.length; i++) { const name = validNames[i]; expect(() => { new MetricInstance<DefaultMetricSchema>({ name, version }, metricsRequestService); }).not.toThrow(); } }); it('throws when creating a metric with an invalid name', () => { const invalidNames = [ 'ends_with_an_underscore_', '123_starts_with_a_number', 'contains_special_characters!@£$%^&*()', ]; const version = 1; for (let i = 0; i < invalidNames.length; i++) { const name = invalidNames[i]; expect(() => { new MetricInstance<DefaultMetricSchema>({ name, version }, metricsRequestService); }).toThrow(); } }); });
7,433
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/MetricsApi.test.ts
import { HTTP_STATUS_CODE, SECOND } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { METRICS_DEFAULT_RETRY_SECONDS, METRICS_MAX_ATTEMPTS, METRICS_REQUEST_TIMEOUT_SECONDS } from '../constants'; import MetricsApi from '../lib/MetricsApi'; jest.mock('@proton/shared/lib/helpers/promise'); function getHeader(headers: HeadersInit | undefined, headerName: string) { // @ts-ignore return headers[headerName]; } describe('MetricsApi', () => { beforeEach(() => { fetchMock.resetMocks(); }); describe('constructor', () => { describe('auth headers', () => { it('sets auth headers when uid is defined', async () => { const uid = 'uid'; const metricsApi = new MetricsApi({ uid }); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-uid')).toBe(uid); }); it('does not set auth headers when uid is not defined', async () => { const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-uid')).toBe(undefined); }); }); describe('app version headers', () => { it('sets app version headers when clientID and appVersion are defined', async () => { const clientID = 'clientID'; const appVersion = 'appVersion'; const metricsApi = new MetricsApi({ clientID, appVersion }); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(`${clientID}@${appVersion}-dev`); }); it('does not set app version headers when clientID is not defined', async () => { const appVersion = 'appVersion'; const metricsApi = new MetricsApi({ appVersion }); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(undefined); }); it('does not set app version headers when appVersion is not defined', async () => { const clientID = 'clientID'; const metricsApi = new MetricsApi({ clientID }); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(undefined); }); }); }); describe('setAuthHeaders', () => { it('sets auth headers when uid is defined', async () => { const uid = 'uid'; const metricsApi = new MetricsApi(); metricsApi.setAuthHeaders(uid); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-uid')).toBe(uid); }); it('does not set auth headers when uid is an empty string', async () => { const uid = ''; const metricsApi = new MetricsApi(); metricsApi.setAuthHeaders(uid); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-uid')).toBe(undefined); }); }); describe('setAuthHeaders', () => { it('sets app version headers when clientID and appVersion are defined', async () => { const clientID = 'clientID'; const appVersion = 'appVersion'; const metricsApi = new MetricsApi(); metricsApi.setVersionHeaders(clientID, appVersion); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(`${clientID}@${appVersion}-dev`); }); it('does not set app version headers when clientID is an empty string', async () => { const clientID = ''; const appVersion = 'appVersion'; const metricsApi = new MetricsApi(); metricsApi.setVersionHeaders(clientID, appVersion); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(undefined); }); it('does not set app version headers when appVersion is an empty string', async () => { const clientID = 'clientID'; const appVersion = ''; const metricsApi = new MetricsApi(); metricsApi.setVersionHeaders(clientID, appVersion); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(undefined); }); }); describe('fetch', () => { it('throws if fetch rejects', async () => { fetchMock.mockResponseOnce(() => Promise.reject(new Error('asd'))); const metricsApi = new MetricsApi(); await expect(async () => { await metricsApi.fetch('/route'); }).rejects.toThrow(); }); it('sets content-type header to application/json', async () => { const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'content-type')).toBe('application/json'); }); it('sets priority header to u=6', async () => { const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'priority')).toBe('u=6'); }); it('forwards request info', async () => { const route = '/route'; const metricsApi = new MetricsApi(); await metricsApi.fetch(route); const url = fetchMock.mock.lastCall?.[0]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(url).toBe(route); }); it('forwards request init params', async () => { const method = 'post'; const body = 'body'; const metricsApi = new MetricsApi(); await metricsApi.fetch('/route', { method, body, headers: { foo: 'bar', }, }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.method).toBe(method); expect(content?.body).toBe(body); expect(getHeader(content?.headers, 'foo')).toBe('bar'); }); describe('retry', () => { const getRetryImplementation = (url: string, retrySeconds?: string) => async (req: Request) => { if (req.url === url) { return retrySeconds === undefined ? { status: HTTP_STATUS_CODE.TOO_MANY_REQUESTS } : { status: HTTP_STATUS_CODE.TOO_MANY_REQUESTS, headers: { 'retry-after': retrySeconds, }, }; } return ''; }; it('retries request if response contains retry-after header', async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '1')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(fetchMock).toHaveBeenCalledTimes(2); }); it('respects the time the retry header contains', async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '1')); fetchMock.mockResponseOnce(getRetryImplementation('/retry', '2')); fetchMock.mockResponseOnce(getRetryImplementation('/retry', '3')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenNthCalledWith(1, 1 * SECOND); expect(wait).toHaveBeenNthCalledWith(2, 2 * SECOND); expect(wait).toHaveBeenNthCalledWith(3, 3 * SECOND); }); it(`retires a maximum of ${METRICS_MAX_ATTEMPTS} times`, async () => { fetchMock.mockResponse(getRetryImplementation('/retry', '1')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(fetchMock).toHaveBeenCalledTimes(METRICS_MAX_ATTEMPTS); }); it(`uses default retry of ${METRICS_DEFAULT_RETRY_SECONDS} if retry is 0`, async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '0')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it(`uses default retry of ${METRICS_DEFAULT_RETRY_SECONDS} if retry is NaN`, async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', 'hello')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it(`uses default retry of ${METRICS_DEFAULT_RETRY_SECONDS} if retry is negative`, async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '-1')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it(`uses default retry of ${METRICS_DEFAULT_RETRY_SECONDS} if retry is not defined`, async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it('floors non integer values', async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '2.5')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(2 * SECOND); }); }); describe('timeout', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { jest.clearAllTimers(); }); afterAll(() => { jest.useRealTimers(); }); const timeoutRequestMock = () => new Promise<{ body: string }>((resolve) => { setTimeout(() => resolve({ body: 'ok' }), METRICS_REQUEST_TIMEOUT_SECONDS * SECOND + 1); jest.advanceTimersByTime(METRICS_REQUEST_TIMEOUT_SECONDS * SECOND + 1); }); it('retries request if request aborts', async () => { fetchMock.mockAbort(); const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); expect(fetchMock).toHaveBeenCalledTimes(METRICS_MAX_ATTEMPTS); await expect(fetchMock).rejects.toThrow('The operation was aborted.'); }); it(`retries request if response takes longer than ${METRICS_REQUEST_TIMEOUT_SECONDS} seconds`, async () => { fetchMock.mockResponseOnce(timeoutRequestMock); const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); expect(fetchMock).toHaveBeenCalledTimes(2); }); it(`waits ${METRICS_DEFAULT_RETRY_SECONDS} seconds before retrying`, async () => { fetchMock.mockResponseOnce(timeoutRequestMock); const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); expect(wait).toHaveBeenNthCalledWith(1, METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it(`retires a maximum of ${METRICS_MAX_ATTEMPTS} times`, async () => { fetchMock.mockResponse(timeoutRequestMock); const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); expect(fetchMock).toHaveBeenCalledTimes(METRICS_MAX_ATTEMPTS); }); }); }); });
7,434
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/MetricsBase.test.ts
import MetricsApi from '../lib/MetricsApi'; import MetricsBase from '../lib/MetricsBase'; import MetricsRequestService from '../lib/MetricsRequestService'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); jest.mock('../lib/MetricsRequestService', () => { return jest.fn().mockImplementation(() => { return { api: metricsApi, setReportMetrics: jest.fn(), processAllRequests: jest.fn(), stopBatchingProcess: jest.fn(), startBatchingProcess: jest.fn(), }; }); }); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); describe('MetricsBase', () => { describe('init', () => { it('sets auth headers', () => { const uid = 'uid'; const clientID = 'clientID'; const appVersion = 'appVersion'; const metrics = new MetricsBase(metricsRequestService); metrics.init({ uid, clientID, appVersion }); expect(metricsRequestService.api.setAuthHeaders).toHaveBeenCalledWith(uid); }); it('sets version headers', () => { const uid = 'uid'; const clientID = 'clientID'; const appVersion = 'appVersion'; const metrics = new MetricsBase(metricsRequestService); metrics.init({ uid, clientID, appVersion }); expect(metricsRequestService.api.setVersionHeaders).toHaveBeenCalledWith(clientID, appVersion); }); }); describe('setVersionHeaders', () => { it('sets version headers', () => { const clientID = 'clientID'; const appVersion = 'appVersion'; const metrics = new MetricsBase(metricsRequestService); metrics.setVersionHeaders(clientID, appVersion); expect(metricsRequestService.api.setVersionHeaders).toHaveBeenCalledWith(clientID, appVersion); }); }); describe('setAuthHeaders', () => { it('sets auth headers', () => { const uid = 'uid'; const metrics = new MetricsBase(metricsRequestService); metrics.setAuthHeaders(uid); expect(metricsRequestService.api.setAuthHeaders).toHaveBeenCalledWith(uid); }); }); describe('clearAuthHeaders', () => { it(`sets auth headers with uid ''`, () => { const metrics = new MetricsBase(metricsRequestService); metrics.clearAuthHeaders(); expect(metricsRequestService.api.setAuthHeaders).toHaveBeenCalledWith(''); }); }); describe('setReportMetrics', () => { it('sets report metrics to false', () => { const metrics = new MetricsBase(metricsRequestService); metrics.setReportMetrics(false); expect(metricsRequestService.setReportMetrics).toHaveBeenCalledWith(false); }); it('sets report metrics to true', () => { const metrics = new MetricsBase(metricsRequestService); metrics.setReportMetrics(true); expect(metricsRequestService.setReportMetrics).toHaveBeenCalledWith(true); }); }); describe('processAllRequests', () => { it('calls processAllRequests', async () => { const metrics = new MetricsBase(metricsRequestService); await metrics.processAllRequests(); expect(metricsRequestService.processAllRequests).toHaveBeenCalledTimes(1); }); }); describe('stopBatchingProcess', () => { it('calls stopBatchingProcess', async () => { const metrics = new MetricsBase(metricsRequestService); await metrics.stopBatchingProcess(); expect(metricsRequestService.stopBatchingProcess).toHaveBeenCalledTimes(1); }); }); describe('startBatchingProcess', () => { it('calls startBatchingProcess', async () => { const metrics = new MetricsBase(metricsRequestService); await metrics.startBatchingProcess(); expect(metricsRequestService.startBatchingProcess).toHaveBeenCalledTimes(1); }); }); });
7,435
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/MetricsRequestService.test.ts
import MetricsApi from '../lib/MetricsApi'; import MetricsRequestService from '../lib/MetricsRequestService'; import MetricsRequest from '../lib/types/MetricsRequest'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); const getMetricsRequest = (name: string): MetricsRequest => ({ Name: name, Version: 1, Timestamp: 1, Data: {}, }); const defaultMetricsRequest = getMetricsRequest('Name'); describe('MetricsRequestService', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { jest.clearAllTimers(); }); afterAll(() => { jest.useRealTimers(); }); it('makes construct correct request', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [defaultMetricsRequest] }), }); }); describe('report metrics', () => { it('allows api calls if reportMetrics was set to true in constructor', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('disallows api calls if reportMetrics was set to false in constructor', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: false }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); }); describe('setter', () => { it('allows api calls if reportMetrics is set to true via setter', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: false }); requestService.setReportMetrics(true); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('disallows api calls if reportMetrics is set to false via setter', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); requestService.setReportMetrics(false); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); }); }); }); describe('batching', () => { describe('batch parameters', () => { it('does not batch if frequency is 0', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 0, size: 1, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not batch if frequency is negative', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: -1, size: 1, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not batch if size is 0', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: 0, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not batch if size is negative', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: -1, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('batches if frequency and size are positive', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: 1, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 1')] }), }); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 2')] }), }); }); }); it('delays api calls until frequency timeout has expired', () => { const batchFrequency = 100; const batchSize = 5; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: batchSize, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); // fast-forward time until 1 millisecond before it should be executed jest.advanceTimersByTime(batchFrequency - 1); expect(metricsApi.fetch).not.toHaveBeenCalled(); // fast-forward until 1st call should be executed jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not call api if there are no items to process', () => { const batchFrequency = 100; const batchSize = 5; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: batchSize, }, }); requestService.startBatchingProcess(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).not.toHaveBeenCalled(); }); it('batches calls in order they were reported', () => { const batchFrequency = 100; const batchSize = 2; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: batchSize, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); requestService.report(getMetricsRequest('Request 4')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 1'), getMetricsRequest('Request 2')] }), }); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 3'), getMetricsRequest('Request 4')] }), }); }); it('handles partial batches', () => { const batchFrequency = 100; const batchSize = 2; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: batchSize, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 1'), getMetricsRequest('Request 2')] }), }); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 3')] }), }); }); }); describe('startBatchingProcess', () => { it('starts batching interval on first report call if batch params are defined', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: 1, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not set batching interval if no batch params are set', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); /** * Advance timers to when call should have been * performed if batching was enabled and ensure * no extra calls have been made */ jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); }); describe('stopBatchingProcess', () => { it('stops any further batch requests from occurring until startBatchingProcess is called', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: 1, }, }); requestService.report(defaultMetricsRequest); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); requestService.stopBatchingProcess(); jest.advanceTimersByTime(4); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); requestService.startBatchingProcess(); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(2); }); }); describe('processAllRequests', () => { it('does not make a request if there is no queue', async () => { const batchFrequency = 10; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: 1, }, }); await requestService.processAllRequests(); expect(metricsApi.fetch).not.toHaveBeenCalled(); }); it('processes all requests in queue regardless of batch size', async () => { const batchFrequency = 10; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: 1, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 1')] }), }); jest.advanceTimersByTime(1); await requestService.processAllRequests(); expect(metricsApi.fetch).toHaveBeenCalledTimes(2); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 2'), getMetricsRequest('Request 3')] }), }); }); it('clears queue', async () => { const batchFrequency = 10; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: 1, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); expect(metricsApi.fetch).not.toHaveBeenCalled(); await requestService.processAllRequests(); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); }); describe('clearQueue', () => { it('removes all items from queue', () => { const batchFrequency = 10; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: 1, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); requestService.clearQueue(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); }); });
7,436
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/integration.test.ts
import Counter from '../lib/Counter'; import Histogram from '../lib/Histogram'; import MetricsApi from '../lib/MetricsApi'; import MetricsBase from '../lib/MetricsBase'; import MetricsRequestService from '../lib/MetricsRequestService'; import IMetricsRequestService from '../lib/types/IMetricsRequestService'; import MetricSchema from '../lib/types/MetricSchema'; export const counterName = 'counter_name'; export const counterVersion = 1; export const histogramName = 'histogram_name'; export const histogramVersion = 1; class MetricsTest extends MetricsBase { public counter: Counter<MetricSchema>; public histogram: Histogram<MetricSchema>; constructor(requestService: IMetricsRequestService) { super(requestService); this.counter = new Counter<MetricSchema>({ name: counterName, version: counterVersion }, this.requestService); this.histogram = new Histogram<MetricSchema>( { name: histogramName, version: histogramVersion }, this.requestService ); } } const metricsApi = new MetricsApi(); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); const metrics = new MetricsTest(metricsRequestService); const uid = 'uid'; const clientID = 'clientID'; const appVersion = 'appVersion'; metrics.init({ uid, clientID, appVersion, }); const time = new Date('2020-01-01'); describe('metrics', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { fetchMock.resetMocks(); jest.clearAllTimers(); jest.setSystemTime(time); }); afterAll(() => { jest.useRealTimers(); }); describe('counter requests', () => { it('uses the metrics v1 url', () => { metrics.counter.increment({ foo: 'bar', }); const url = fetchMock.mock.lastCall?.[0]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(url).toBe('api/data/v1/metrics'); }); it('makes a post request', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.method).toBe('post'); }); it('contains the correct headers', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.headers).toEqual({ 'content-type': 'application/json', priority: 'u=6', 'x-pm-appversion': `${clientID}@${appVersion}-dev`, 'x-pm-uid': uid, }); }); it('sends the metric name', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Name).toEqual(counterName); }); it('sends the metric version', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Version).toEqual(counterVersion); }); it('uses the current time for the timestamp', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Timestamp).toEqual(time.getTime() / 1000); }); it('sends Value as 1', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Data.Value).toBe(1); }); it('sends labels', async () => { const labels = { foo: 'bar', bar: 'foo', }; metrics.counter.increment(labels); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Data.Labels).toEqual(labels); }); }); describe('histogram requests', () => { it('uses the metrics v1 url', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const url = fetchMock.mock.lastCall?.[0]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(url).toBe('api/data/v1/metrics'); }); it('makes a post request', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.method).toBe('post'); }); it('contains the correct headers', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.headers).toEqual({ 'content-type': 'application/json', priority: 'u=6', 'x-pm-appversion': `${clientID}@${appVersion}-dev`, 'x-pm-uid': uid, }); }); it('sends the metric name', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Name).toEqual(histogramName); }); it('sends the metric version', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Version).toEqual(histogramVersion); }); it('uses the current time for the timestamp', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Timestamp).toEqual(time.getTime() / 1000); }); it('sends float Values', async () => { const Value = 1.234; metrics.histogram.observe({ Labels: { foo: 'bar', }, Value, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Data.Value).toBe(Value); }); it('sends Labels', async () => { const Labels = { foo: 'bar', bar: 'foo', }; metrics.histogram.observe({ Labels, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Data.Labels).toEqual(Labels); }); }); });
7,437
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/observeApiError.test.ts
import observeApiError from '../lib/observeApiError'; const metricObserver = jest.fn(); describe('observeApiError', () => { it('ignores reporting if error is undefined', () => { observeApiError(undefined, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if error is null', () => { observeApiError(null, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if error is not an object', () => { observeApiError('string', metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if status is -1 (offline)', () => { observeApiError({ status: -1 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if status is 0', () => { observeApiError({ status: 0 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if error does not contain a status property', () => { observeApiError('', metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if it is an abort error', () => { observeApiError({ name: 'AbortError ' }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if it is an HV error', () => { observeApiError({ status: 422, data: { Error: 'HV required', Code: 9001 } }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('returns 5xx if error.status is 500', () => { observeApiError({ status: 500 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('5xx'); }); it('returns 5xx if error.status is larger than 500', () => { observeApiError({ status: 501 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('5xx'); }); it('returns 4xx if error.status is 400', () => { observeApiError({ status: 400 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('4xx'); }); it('returns 4xx if error.status is larger than 400', () => { observeApiError({ status: 401 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('4xx'); }); it('returns failure if error.status is not in the correct range', () => { observeApiError({ status: 200 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('failure'); }); });
7,438
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_session_recovery_abort_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the session recovery abort api call successes and failures */ export interface WebCoreSessionRecoveryAbortTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,439
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_session_recovery_cancellation_modal_load_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the session recovery cancellation loads */ export interface WebCoreSessionRecoveryCancellationModalLoadTotal { Value: number; Labels: { step: "confirm"; }; }
7,440
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_session_recovery_consume_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the session recovery consume api call successes and failures */ export interface WebCoreSessionRecoveryConsumeTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,441
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_session_recovery_initiation_modal_load_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the session recovery initiation loads */ export interface WebCoreSessionRecoveryInitiationModalLoadTotal { Value: number; Labels: { step: "prompt" | "confirmed"; }; }
7,442
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_session_recovery_initiation_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the session recovery initiation api call successes and failures */ export interface WebCoreSessionRecoveryInitiationTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,443
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_session_recovery_password_reset_available_account_modal_load_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the session recovery password reset available account modal loads */ export interface WebCoreSessionRecoveryPasswordResetAvailableAccountModalLoadTotal { Value: number; Labels: { step: "info" | "password" | "confirm_cancellation"; }; }
7,444
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_session_recovery_settings_update_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the session recovery update api call successes and failures */ export interface WebCoreSessionRecoverySettingsUpdateTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,445
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_accountStep_accountCreation_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the create account step when signing up */ export interface WebCoreSignupAccountStepAccountCreationTotal { Value: number; Labels: { account_type: "proton_account" | "external_account"; status: "success" | "failure"; application: "proton-vpn-settings" | "proton-account"; }; }
7,446
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_accountStep_accountCreation_total_v2.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the create account step when signing up */ export interface WebCoreSignupAccountStepAccountCreationTotal { Value: number; Labels: { account_type: "proton_account" | "external_account"; status: "success" | "failure" | "4xx" | "5xx"; application: "proton-vpn-settings" | "proton-account"; }; }
7,447
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_backButton_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Metric for the total times the back button is used on a step when signing up */ export interface WebCoreSignupBackButtonTotal { Value: number; Labels: { step: "account" | "verification" | "referral" | "upsell" | "payment" | "recovery"; application: "proton-vpn-settings" | "proton-account"; }; }
7,448
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_congratulationsStep_displayNameChoice_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the display name selection step when signing up */ export interface WebCoreSignupCongratulationsStepDisplayNameChoiceTotal { Value: number; Labels: { status: "success" | "failure"; application: "proton-vpn-settings" | "proton-account"; }; }
7,449
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_congratulationsStep_displayNameChoice_total_v2.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the display name selection step when signing up */ export interface WebCoreSignupCongratulationsStepDisplayNameChoiceTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; application: "proton-vpn-settings" | "proton-account"; }; }
7,450
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_exploreStep_login_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the explore step when signing up */ export interface WebCoreSignupExploreStepLoginTotal { Value: number; Labels: { status: "success" | "failure"; application: "proton-vpn-settings" | "proton-account"; }; }
7,451
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_exploreStep_login_total_v2.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the explore step when signing up */ export interface WebCoreSignupExploreStepLoginTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; application: "proton-vpn-settings" | "proton-account"; }; }
7,452
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_loadingStep_accountSetup_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the loading step when signing up */ export interface WebCoreSignupLoadingStepAccountSetupTotal { Value: number; Labels: { status: "success" | "failure"; application: "proton-vpn-settings" | "proton-account"; }; }
7,453
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_loadingStep_accountSetup_total_v2.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the loading step when signing up */ export interface WebCoreSignupLoadingStepAccountSetupTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; application: "proton-vpn-settings" | "proton-account"; }; }
7,454
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_pageLoad_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total number of page loads for the web signup steps */ export interface WebCoreSignupPageLoadTotal { Value: number; Labels: { step: | "external_account_creation" | "proton_account_creation" | "verification" | "referral" | "upsell" | "payment" | "loading" | "congratulations" | "recovery" | "explore"; application: "proton-vpn-settings" | "proton-account"; }; }
7,455
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_paymentStep_payment_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the payment step when signing up */ export interface WebCoreSignupPaymentStepPaymentTotal { Value: number; Labels: { status: "success" | "failure"; application: "proton-vpn-settings" | "proton-account"; }; }
7,456
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_paymentStep_payment_total_v2.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the payment step when signing up */ export interface WebCoreSignupPaymentStepPaymentTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; application: "proton-vpn-settings" | "proton-account"; }; }
7,457
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_recoveryStep_setRecoveryMethod_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the recovery step when signing up */ export interface WebCoreSignupRecoveryStepSetRecoveryMethodTotal { Value: number; Labels: { status: "success" | "failure" | "skipped"; application: "proton-vpn-settings" | "proton-account"; }; }
7,458
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_recoveryStep_setRecoveryMethod_total_v2.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the recovery step when signing up */ export interface WebCoreSignupRecoveryStepSetRecoveryMethodTotal { Value: number; Labels: { status: "success" | "failure" | "skipped" | "4xx" | "5xx"; application: "proton-vpn-settings" | "proton-account"; }; }
7,459
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_referralStep_planSelection_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the referral step when signing up */ export interface WebCoreSignupReferralStepPlanSelectionTotal { Value: number; Labels: { status: "success" | "failure"; application: "proton-vpn-settings" | "proton-account"; }; }
7,460
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_referralStep_planSelection_total_v2.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the referral step when signing up */ export interface WebCoreSignupReferralStepPlanSelectionTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; application: "proton-vpn-settings" | "proton-account"; }; }
7,461
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_upsellStep_planSelection_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the upsell step when signing up */ export interface WebCoreSignupUpsellStepPlanSelectionTotal { Value: number; Labels: { status: "success" | "failure"; application: "proton-vpn-settings" | "proton-account"; }; }
7,462
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_upsellStep_planSelection_total_v2.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the upsell step when signing up */ export interface WebCoreSignupUpsellStepPlanSelectionTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; application: "proton-vpn-settings" | "proton-account"; }; }
7,463
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_verificationStep_verification_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the verification step when signing up */ export interface WebCoreSignupVerificationStepVerificationTotal { Value: number; Labels: { status: "successful" | "failed" | "cancelled"; application: "proton-vpn-settings" | "proton-account"; }; }
7,464
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_signup_verificationStep_verification_total_v2.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the verification step when signing up */ export interface WebCoreSignupVerificationStepVerificationTotal { Value: number; Labels: { status: "success" | "cancelled" | "failure" | "4xx" | "5xx"; application: "proton-vpn-settings" | "proton-account"; }; }
7,465
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_fetchDependencies_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total calls to fetchDependencies success and failures */ export interface WebCoreVpnSingleSignupFetchDependencies2Total { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; flow: "b2c" | "b2b"; }; }
7,466
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_fetchDependencies_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total calls to fetchDependencies success and failures */ export interface WebCoreVpnSingleSignupFetchDependenciesTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,467
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_pageLoad_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total number of page loads for the web vpn single signup steps. */ export interface WebCoreVpnSingleSignupPageLoad2Total { Value: number; Labels: { step: "plan_username_payment" | "account_setup" | "password_selection" | "saving_password" | "org_setup"; flow: "b2c" | "b2b"; }; }
7,468
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_pageLoad_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total number of page loads for the web vpn single signup steps. */ export interface WebCoreVpnSingleSignupPageLoadTotal { Value: number; Labels: { step: "plan_username_payment" | "account_setup" | "password_selection" | "saving_password"; }; }
7,469
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_passwordSelection_step_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total number of step loads for the web vpn single signup password selection step. */ export interface WebCoreVpnSingleSignupPasswordSelectionStep2Total { Value: number; Labels: { step: "given_password" | "own_password" | "copy_password_modal"; flow: "b2c" | "b2b"; }; }
7,470
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_passwordSelection_step_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total number of step loads for the web vpn single signup password selection step. */ export interface WebCoreVpnSingleSignupPasswordSelectionStepTotal { Value: number; Labels: { step: "given_password" | "own_password" | "copy_password_modal"; }; }
7,471
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_accountCreation_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the create account step when signing up */ export interface WebCoreVpnSingleSignupStep1AccountCreation2Total { Value: number; Labels: { account_type: "proton_account" | "external_account"; status: "success" | "failure" | "4xx" | "5xx"; flow: "b2c" | "b2b"; }; }
7,472
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_accountCreation_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total success or failures for the create account step when signing up */ export interface WebCoreVpnSingleSignupStep1AccountCreationTotal { Value: number; Labels: { account_type: "proton_account" | "external_account"; status: "success" | "failure" | "4xx" | "5xx"; }; }
7,473
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_currencyChange_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total currency change success and failures */ export interface WebCoreVpnSingleSignupStep1CurrencyChange2Total { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; flow: "b2c" | "b2b"; }; }
7,474
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_currencyChange_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total currency change success and failures */ export interface WebCoreVpnSingleSignupStep1CurrencyChangeTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,475
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_cycleChange_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total cycle change success and failures */ export interface WebCoreVpnSingleSignupStep1CycleChange2Total { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; flow: "b2c" | "b2b"; }; }
7,476
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_cycleChange_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total cycle change success and failures */ export interface WebCoreVpnSingleSignupStep1CycleChangeTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,477
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_interaction_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the number of first interactions with steps in Step 1 of the vpn single signup page. */ export interface WebCoreVpnSingleSignupStep1Interaction2Total { Value: number; Labels: { step: "plan" | "email" | "payment"; flow: "b2c" | "b2b"; }; }
7,478
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_interaction_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the number of first interactions with steps in Step 1 of the vpn single signup page. */ export interface WebCoreVpnSingleSignupStep1InteractionTotal { Value: number; Labels: { step: "plan" | "email" | "payment"; }; }
7,479
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_payment_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total payment success and failures */ export interface WebCoreVpnSingleSignupStep1Payment2Total { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; flow: "b2c" | "b2b"; }; }
7,480
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step1_payment_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total payment success and failures */ export interface WebCoreVpnSingleSignupStep1PaymentTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,481
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step2_setup_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total step 2 setup success and failures */ export interface WebCoreVpnSingleSignupStep2Setup2Total { Value: number; Labels: { type: "free" | "cc" | "pp" | "btc"; status: "success" | "failure" | "4xx" | "5xx"; }; }
7,482
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step2_setup_3_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total step 2 setup success and failures */ export interface WebCoreVpnSingleSignupStep2Setup3Total { Value: number; Labels: { type: "free" | "cc" | "pp" | "btc"; status: "success" | "failure" | "4xx" | "5xx"; flow: "b2c" | "b2b"; }; }
7,483
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step2_setup_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total step 2 setup success and failures */ export interface WebCoreVpnSingleSignupStep2SetupTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,484
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step3_complete_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total step 3 complete success and failures */ export interface WebCoreVpnSingleSignupStep3Complete2Total { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; flow: "b2c" | "b2b"; }; }
7,485
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step3_complete_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total step 3 complete success and failures */ export interface WebCoreVpnSingleSignupStep3CompleteTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,486
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step4_orgSetup_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total step 4 org setup success and failures */ export interface WebCoreVpnSingleSignupStep4OrgSetupTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; flow: "b2c" | "b2b"; }; }
7,487
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step4_setup_2_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total step 4 setup success and failures */ export interface WebCoreVpnSingleSignupStep4Setup2Total { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; flow: "b2c" | "b2b"; }; }
7,488
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_core_vpn_single_signup_step4_setup_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total step 4 setup success and failures */ export interface WebCoreVpnSingleSignupStep4SetupTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; }; }
7,489
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_payments_subscription_steps_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total number of subscription modal renders */ export interface WebPaymentsSubscriptionStepsTotal { Value: number; Labels: { source: | "dashboard" | "plans" | "lite-subscribe" | "subscription-section" | "upsells" | "vpn-get-more" | "vpn-um-get-more" | "automatic"; application: "proton-vpn-settings" | "proton-account" | "proton-account-lite"; fromPlan: "free" | "paid"; step: | "network-error" | "plan-selection" | "customization" | "checkout" | "checkout-with-customization" | "upgrade" | "thanks"; }; }
7,490
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/types/web_payments_subscription_total_v1.schema.d.ts
/* eslint-disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Measures the total number of subscriptions */ export interface WebPaymentsSubscriptionTotal { Value: number; Labels: { status: "success" | "failure" | "4xx" | "5xx"; source: | "dashboard" | "plans" | "lite-subscribe" | "subscription-section" | "upsells" | "vpn-get-more" | "vpn-um-get-more" | "automatic"; application: "proton-vpn-settings" | "proton-account" | "proton-account-lite"; fromPlan: "free" | "paid"; step: | "network-error" | "plan-selection" | "customization" | "checkout" | "checkout-with-customization" | "upgrade" | "thanks"; }; }
7,491
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/pack/.eslintignore
bin/protonPack
7,492
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/pack/.eslintrc.js
module.exports = { extends: ['@proton/eslint-config-proton'], parser: '@typescript-eslint/parser', parserOptions: { tsconfigRootDir: __dirname, project: './tsconfig.json', }, rules: { 'import/no-dynamic-require': 'off', 'global-require': 'off', 'no-console': 'off', }, ignorePatterns: ['.eslintrc.js'], };
7,493
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/pack/package.json
{ "name": "@proton/pack", "description": "Setup boilerplate for webpack", "license": "MIT", "author": "Proton AG", "main": "src/index.js", "module": "src/index.js", "bin": { "proton-pack": "./bin/protonPack.js" }, "scripts": { "lint": "eslint $(find cli bin -type f) --quiet --cache", "pretty": "prettier --write cli bin" }, "dependencies": { "@babel/cli": "^7.23.4", "@babel/core": "^7.23.3", "@babel/plugin-proposal-class-properties": "^7.18.6", "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6", "@babel/plugin-proposal-object-rest-spread": "^7.20.7", "@babel/plugin-proposal-optional-chaining": "^7.21.0", "@babel/plugin-proposal-private-methods": "^7.18.6", "@babel/plugin-syntax-dynamic-import": "^7.8.3", "@babel/plugin-transform-regenerator": "^7.23.3", "@babel/plugin-transform-runtime": "^7.23.4", "@babel/preset-env": "^7.23.3", "@babel/preset-react": "^7.23.3", "@babel/preset-typescript": "^7.23.3", "@babel/runtime": "^7.23.4", "@pmmmwh/react-refresh-webpack-plugin": "^0.5.11", "@sentry/webpack-plugin": "^1.21.0", "@types/webpack": "^5.28.5", "autoprefixer": "^10.4.16", "babel-loader": "^9.1.3", "babel-plugin-transform-react-remove-prop-types": "^0.4.24", "chalk": "4.1.2", "commander": "^11.1.0", "copy-webpack-plugin": "^11.0.0", "core-js": "^3.33.3", "cross-env": "^7.0.3", "css-loader": "^6.8.1", "css-minimizer-webpack-plugin": "^5.0.1", "dedent": "^1.5.1", "eslint-webpack-plugin": "^4.0.1", "execa": "^5.1.1", "favicons": "^7.1.4", "favicons-webpack-plugin": "^6.0.1", "fork-ts-checker-webpack-plugin": "^9.0.2", "html-webpack-plugin": "^5.5.3", "mini-css-extract-plugin": "^2.7.6", "po-gettext-loader": "^1.0.0", "portfinder": "^1.0.32", "postcss": "^8.4.31", "postcss-color-functional-notation": "^6.0.2", "postcss-loader": "^7.3.3", "postcss-logical": "^7.0.0", "react-refresh": "^0.14.0", "resolve-url-loader": "^5.0.0", "sass": "^1.69.5", "sass-loader": "^13.3.2", "terser-webpack-plugin": "^5.3.9", "ttag": "^1.7.29", "ttag-cli": "^1.10.9", "webpack": "^5.89.0", "webpack-cli": "^5.1.4", "webpack-dev-server": "^4.15.1", "webpack-retry-chunk-load-plugin": "^3.1.1", "webpack-subresource-integrity": "^5.1.0" }, "devDependencies": { "eslint": "^8.54.0", "prettier": "^3.1.0" }, "engines": { "node": ">= v20.9.0" } }
7,494
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/pack/tsconfig.json
{ "compilerOptions": { "noImplicitAny": true, "module": "commonjs", "target": "es5", "esModuleInterop": true } }
7,495
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/pack/webpack.config.ts
import path from 'path'; import { Configuration } from 'webpack'; import 'webpack-dev-server'; // @ts-ignore import { parseResource } from 'webpack/lib/util/identifier'; const { getJsLoaders } = require('./webpack/js.loader'); const getCssLoaders = require('./webpack/css.loader'); const getAssetsLoaders = require('./webpack/assets.loader'); const getPlugins = require('./webpack/plugins'); const getOptimizations = require('./webpack/optimization'); const getConfig = (env: any): Configuration => { const isProduction = process.env.NODE_ENV === 'production'; const isRelease = !!process.env.CI_COMMIT_TAG; const assetsFolder = 'assets'; const options = { isProduction, isRelease, publicPath: env.publicPath || '/', api: env.api, appMode: env.appMode || 'standalone', featureFlags: env.featureFlags || '', writeSRI: env.writeSri !== 'false', browserslist: isProduction ? `> 0.5%, not IE 11, Firefox ESR, Safari 11` : 'last 1 chrome version, last 1 firefox version, last 1 safari version', buildData: { version: env.version, commit: env.commit, branch: env.branch, date: env.date, mode: env.appMode, }, warningLogs: env.warningLogs || false, errorLogs: env.errorLogs || false, overlayWarnings: env.overlayWarnings || false, overlayErrors: env.overlayErrors || false, overlayRuntimeErrors: env.overlayRuntimeErrors || false, logical: env.logical || false, }; const version = options.buildData.version; return { target: `browserslist:${options.browserslist}`, mode: isProduction ? 'production' : 'development', bail: isProduction, devtool: isProduction ? 'source-map' : 'cheap-module-source-map', watchOptions: { ignored: /dist|node_modules|locales|\.(gif|jpeg|jpg|ico|png|svg)/, aggregateTimeout: 600, }, resolve: { extensions: ['.js', '.tsx', '.ts'], fallback: { crypto: false, buffer: false, stream: false, iconv: false, path: false, punycode: false, }, }, entry: { // The order is important. The pre.js listens to index.js, and supported.js file sets a global variable that is used by unsupported.js to detect if the main bundle could be parsed. pre: [require.resolve('@proton/shared/lib/supported/pre.ts')], index: [path.resolve('./src/app/index.tsx'), require.resolve('@proton/shared/lib/supported/supported.ts')], unsupported: [require.resolve('@proton/shared/lib/supported/unsupported.ts')], }, output: { filename: isProduction ? `${assetsFolder}/[name].[contenthash:8].js?v=${version}` : `${assetsFolder}/[name].js?v=${version}`, publicPath: options.publicPath, chunkFilename: (pathData) => { const result = isProduction ? `${assetsFolder}/[name].[contenthash:8].chunk.js?v=${version}` : `${assetsFolder}/[name].chunk.js?v=${version}`; const chunkName = pathData?.chunk?.name; if (chunkName && (chunkName.startsWith('date-fns/') || chunkName.startsWith('locales/'))) { // @ts-ignore const strippedChunkName = chunkName.replaceAll(/-index-js|-json/g, ''); return result.replace('[name]', strippedChunkName); } // Drive need static URL for transpiled SW if (chunkName && chunkName.startsWith('downloadSW')) { return `[name].js?v=${version}`; } return result; }, assetModuleFilename: (data) => { const { path: file } = parseResource(data?.filename || ''); const ext = path.extname(file); const base = path.basename(file); const name = base.slice(0, base.length - ext.length); if (name.includes('.var')) { const replacedNamed = name.replace('.var', '-var'); return `${assetsFolder}/${replacedNamed}.[hash][ext]?v=${version}`; } return `${assetsFolder}/[name].[hash][ext]?v=${version}`; }, crossOriginLoading: 'anonymous', }, cache: { type: 'filesystem', cacheDirectory: path.resolve('./node_modules/.cache/webpack'), buildDependencies: { defaultWebpack: ['webpack/lib/'], config: [__filename], }, }, module: { strictExportPresence: true, // Make missing exports an error instead of warning rules: [...getJsLoaders(options), ...getCssLoaders(options), ...getAssetsLoaders()], }, plugins: getPlugins({ ...options, cssName: isProduction ? `${assetsFolder}/[name].[contenthash:8].css?v=${version}` : `${assetsFolder}/[name].css?v=${version}`, }), optimization: getOptimizations(options), devServer: { hot: !isProduction, devMiddleware: { stats: 'minimal', publicPath: options.publicPath, }, allowedHosts: 'all', compress: true, historyApiFallback: { index: options.publicPath, }, client: { webSocketURL: 'auto://0.0.0.0:0/ws', overlay: { warnings: options.overlayWarnings, errors: options.overlayErrors, runtimeErrors: options.overlayRuntimeErrors, }, }, webSocketServer: 'ws', ...(options.api && { proxy: [ { context: ['/api', '/internal-api'], target: options.api, secure: false, changeOrigin: true, onProxyRes: (proxyRes) => { delete proxyRes.headers['content-security-policy']; delete proxyRes.headers['x-frame-options']; proxyRes.headers['set-cookie'] = proxyRes.headers['set-cookie']?.map((cookies) => cookies .split('; ') .filter((cookie) => { return !/(secure$|samesite=|domain=)/i.test(cookie); }) .join('; ') ); }, }, ], }), }, }; }; export default getConfig; export const mergeEntry = (originalEntry: any, entry: any) => { const { pre, ...rest } = originalEntry; return { pre, ...entry, ...rest, }; };
7,496
0
petrpan-code/ProtonMail/WebClients/packages/pack
petrpan-code/ProtonMail/WebClients/packages/pack/bin/protonPack.js
#!/usr/bin/env node const fs = require('fs').promises; const execa = require('execa'); const path = require('path'); const { Command } = require('commander'); const portfinder = require('portfinder'); const chalk = require('chalk'); const program = new Command(); const { getConfigData, getApi, getConfigFile } = require('../lib/config'); const getPort = (basePort) => { portfinder.basePort = basePort; return portfinder.getPortPromise(); }; const writeConfig = async (configFile) => { const configPath = path.resolve('./src/app/config.ts'); await fs.writeFile(configPath, configFile); }; const addGlobalOptions = (program) => { return program .option('--appMode <appMode>', '') .option('--featureFlags <featureFlags>', '') .option('--api <api>', '', (api) => getApi(api), getApi('')) .option('--sso <sso>', '') .option('--no-api-proxy', '') .option('--logical', '', false) .option( '--publicPath <publicPath>', '', (publicPath) => { if (publicPath && (!publicPath.startsWith('/') || !publicPath.endsWith('/'))) { throw new Error('--publicPath must start and end with a forward slash'); } return publicPath || '/'; }, '/' ); }; const getWebpackArgs = (options, env, { appData, buildData }) => { const envArgs = { api: appData.api === '/api' ? undefined : appData.api, sso: appData.sso, appMode: options.appMode, publicPath: options.publicPath === '/' ? undefined : options.publicPath, featureFlags: options.featureFlags, writeSri: options.sri ? undefined : options.sri, warningLogs: options.warningLogs, errorLogs: options.errorLogs, overlayWarnings: options.overlayWarnings, overlayErrors: options.overlayErrors, overlayRuntimeErrors: options.overlayRuntimeErrors, logical: Boolean(options.logical), ...buildData, }; const extraWebpackArgs = env.args.join(' '); const webpackEnvArgs = Object.entries(envArgs) .filter(([, value]) => value !== undefined && value !== '') .reduce((acc, [key, value]) => { if (typeof value === 'boolean') { if (value) { return `${acc} --env ${key}`; } else { return acc; } } return `${acc} --env ${key}=${value.replace(/ /g, '\\ ')}`; }, ''); return `${webpackEnvArgs} ${extraWebpackArgs}`; }; const commandWithLog = (...args) => { console.log(chalk.cyan(args[0]), `\n`); return execa.command(...args); }; addGlobalOptions(program.command('build').description('create an optimized production build')) .option('--no-sri', 'disable sri') .action(async (options, env) => { console.log(chalk.magenta('Creating a production build...\n')); const configData = getConfigData(options); await writeConfig(getConfigFile(configData)); const webpackArgs = getWebpackArgs(options, env, configData); const outputPath = path.resolve('./dist'); await commandWithLog(`rm -rf ${outputPath}`); await commandWithLog( `${require.resolve('webpack-cli/bin/cli.js')} --progress --output-path=${outputPath} ${webpackArgs}`, { stdio: 'inherit', } ); await commandWithLog(`${path.resolve(__dirname, `../scripts/validate.sh`)} ${outputPath}`, { stdio: 'inherit', }); }); addGlobalOptions(program.command('dev-server').description('run locally')) .option('--port <port>', '') .option('--warning-logs', 'emit typescript and eslint warnings') .option('--no-error-logs', 'do not emit typescript and eslint errors') .option('--overlay-warnings', 'show a full screen overlay when there are compiler warnings') .option('--overlay-runtime-errors', 'show a full screen overlay when there are runtime errors') .option('--overlay-errors', 'show a full screen overlay when there are compiler errors') .action(async (options, env) => { console.log(chalk.magenta('Starting development server...\n')); const configData = getConfigData(options); await writeConfig(getConfigFile(configData)); const port = await getPort(options.port || 8080); const webpackArgs = getWebpackArgs(options, env, configData); await commandWithLog( `${require.resolve('webpack-cli/bin/cli.js')} serve --progress --port=${port} ${webpackArgs}`, { stdio: 'inherit', } ); }); addGlobalOptions(program.command('config').description('write config')) .option('--version <version>', 'override the default (based on the tag) version number') .action(async (options) => { await writeConfig(getConfigFile(getConfigData(options))); }); program.parse(process.argv);
7,497
0
petrpan-code/ProtonMail/WebClients/packages/pack
petrpan-code/ProtonMail/WebClients/packages/pack/lib/config.js
const path = require('path'); const dedent = require('dedent'); const execa = require('execa'); const readJSON = (file) => { const fileName = `${file}.json`; try { return require(path.join(process.cwd(), fileName)); } catch { return undefined; } }; const getGitBranch = () => { try { const { stdout = '' } = execa.sync('git describe --all', { shell: true }); return stdout.trim(); } catch (e) { return ''; } }; const getGitCommitHash = () => { try { const { stdout = '' } = execa.sync('git rev-parse HEAD', { shell: true }); return stdout.trim(); } catch (e) { return ''; } }; const getGitTagVersion = (applicationName) => { try { const { stdout = '' } = execa.sync(`git describe --abbrev=0 --match=${applicationName}*`, { shell: true }); return stdout.trim(); } catch (e) { return ''; } }; /** * Clean ex. proton-mail@4.x.x to 4.x.x */ const getVersionNumberFromTag = (tag) => { return tag.replace(/[^@]*@/g, ''); }; const APP_CONFIG_JSON = readJSON('appConfig') || {}; const LOCALES = (() => { try { return require(path.join(process.cwd(), 'locales', 'config', 'locales.json')); } catch (e) { return {}; } })(); const ENV_CONFIG = Object.keys(APP_CONFIG_JSON).reduce( (acc, key) => { if (key === 'appConfig') { acc.app = APP_CONFIG_JSON[key]; return acc; } const { api, secure } = APP_CONFIG_JSON[key]; if (api) { acc.api[key] = api; } if (secure) { acc.secure[key] = secure; } return acc; }, { api: {}, secure: {}, app: {} } ); const API_TARGETS = { prod: 'https://mail.proton.me', localhost: 'https://localhost', proxy: '/api', ...ENV_CONFIG.api, }; const getApi = (value) => { // We can do --api=https://mail.proton.me/api and it's only for dev, so we can stop here if (value.startsWith('http') || value.startsWith('/api')) { return value; } return API_TARGETS[value] || API_TARGETS.prod; }; const getConfigData = ({ api, sso, apiProxy, publicPath, version }) => { const pkg = require(path.join(process.cwd(), 'package.json')); const appName = pkg.name; if (!appName) { throw new Error('Missing app name'); } const isProduction = process.env.NODE_ENV === 'production'; const appData = { appName, version: version || getVersionNumberFromTag(process.env.CI_COMMIT_TAG || getGitTagVersion(appName)) || '5.0.999.999', locales: LOCALES, api, sso, apiProxy, sentryDsn: isProduction ? ENV_CONFIG.app.sentry || '' : '', sentryDesktopDsn: isProduction ? ENV_CONFIG.app.sentryDesktop || '' : '', publicPath, }; const buildData = { version: appData.version, commit: process.env.CI_COMMIT_SHA || getGitCommitHash(), branch: process.env.CI_COMMIT_REF_NAME || getGitBranch(), date: new Date().toGMTString(), }; return { appData, buildData, }; }; const getConfigFile = ({ buildData, appData }) => { return dedent` export const CLIENT_TYPE = ${ENV_CONFIG.app.clientType || 1}; export const CLIENT_SECRET = '${ENV_CONFIG.app.clientSecret || ''}'; export const APP_VERSION = '${buildData.version}'; export const COMMIT = '${buildData.commit}'; export const BRANCH = '${buildData.branch}'; export const DATE_VERSION = '${buildData.date}'; export const APP_NAME = '${appData.appName}'; export const API_URL = '${(!appData.apiProxy && appData.api) || '/api'}'; export const SSO_URL = '${appData.sso || ''}'; export const LOCALES = ${JSON.stringify(LOCALES)}; export const VERSION_PATH = '${appData.publicPath}assets/version.json'; export const SENTRY_DSN = '${appData.sentryDsn}'; export const SENTRY_DESKTOP_DSN = '${appData?.sentryDesktopDsn ?? ''}'; `; }; module.exports = { getConfigData, getConfigFile, getApi, };
7,498
0
petrpan-code/ProtonMail/WebClients/packages/pack
petrpan-code/ProtonMail/WebClients/packages/pack/scripts/validate.sh
#!/usr/bin/env bash set -eo pipefail ## # This script should be useless but we found an issue with webpack. It was able to build everything # and gives you an exit code 0 even if there were 2 errors inside the process and it the dist dir # was empty... # # Ex: # ERROR in ./node_modules/react-components/hooks/useGetAddressKeys.ts # 433 Module build failed (from ./node_modules/babel-loader/lib/index.js): # 434 Error: /builds/web/mail/proton-mail/node_modules/react-components/hooks/useGetAddressKeys.ts: # Expected type "Expression" with option {}, but instead got "SpreadElement". # # Awesome isn't it ? # So this is why there is a script, to ensure even if webpack tells us "OK" it's really ok. # https://www.youtube.com/watch?v=t3otBjVZzT0&feature=youtu.be OUTPUT_DIR="$1"; OUTPUT_FILES="$(find "${OUTPUT_DIR}" -type f)"; function detect { echo "$OUTPUT_FILES" | grep -Ec "\.$1$"; } function detectEmpty { local total=0; for file in $(echo "$OUTPUT_FILES" | grep -E "\.$1$"); do if [ ! -s "$file" ]; then ((total++)) echo "[error] empty file: $file" >&2; fi; done; echo "$total"; } function main { local hasJS="$(detect 'js')"; local hasCSS="$(detect 'css')"; local hasHTML="$(detect 'html')"; local hasSourceMap="$(detect 'map')"; if [ "$hasJS" -eq 0 ]; then hasError=true; echo "[error] no JS found inside the directory: $OUTPUT_DIR"; fi; if [ "$hasCSS" -eq 0 ]; then hasError=true; echo "[error] no CSS found inside the directory: $OUTPUT_DIR"; fi; if [ "$hasHTML" -eq 0 ]; then hasError=true; echo "[error] no HTML found inside the directory: $OUTPUT_DIR"; fi; if [ "$hasSourceMap" -eq 0 ]; then hasError=true; echo "[error] no SourceMaps found inside the directory: $OUTPUT_DIR"; fi; local emptyJS="$(detectEmpty 'js')"; local emptyCSS="$(detectEmpty 'css')"; local emptyHTML="$(detectEmpty 'html')"; local emptySourceMap="$(detectEmpty 'map')"; if [ "$hasError" = true ] || [ "$emptyJS" -gt 0 ] || [ "$emptyCSS" -gt 0 ] || [ "$emptyHTML" -gt 0 ] || [ "$emptySourceMap" -gt 0 ]; then exit 1; fi } main
7,499