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
|
petrpan-code/ProtonMail/WebClients/packages/eslint-config-proton/index.js
|
const path = require('path');
module.exports = {
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: true,
},
extends: ['airbnb-typescript', 'prettier', 'plugin:monorepo-cop/recommended', 'plugin:jsx-a11y/recommended'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json',
},
plugins: [
'react',
'react-hooks',
'import',
'@typescript-eslint',
'es',
'monorepo-cop',
'deprecation',
'no-only-tests',
'jsx-a11y',
'custom-rules',
],
rules: {
'@typescript-eslint/array-type': [
'error',
{
default: 'array',
},
],
'@typescript-eslint/default-param-last': 'off',
'@typescript-eslint/no-shadow': 'off',
'@typescript-eslint/no-redeclare': ['error'],
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/indent': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-for-in-array': 'error',
'@typescript-eslint/no-misused-promises': ['error', { checksVoidReturn: false }],
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'variable',
format: ['camelCase', 'PascalCase', 'UPPER_CASE'],
},
{
selector: 'function',
format: ['camelCase', 'PascalCase'],
},
{
selector: 'typeLike',
format: ['PascalCase', 'UPPER_CASE'],
},
{
selector: 'enum',
format: ['PascalCase', 'UPPER_CASE'],
},
],
'arrow-body-style': 'off',
'consistent-return': 'off',
curly: ['error', 'all'],
'import/export': 2,
// Provided by TS
'import/named': 'off',
'import/default': 'off',
'import/namespace': 'off',
// Off since we use @trivago/prettier-plugin-sort-imports
'import/order': 'off',
'import/no-extraneous-dependencies': 'off',
'import/no-named-as-default': 'off',
'import/no-named-as-default-member': 'off',
'import/no-mutable-exports': 'off',
'import/no-unresolved': [
2,
{
amd: true,
commonjs: true,
},
],
'import/prefer-default-export': 'off',
'no-redeclare': 'off',
'no-await-in-loop': 'off',
'no-bitwise': 'off',
'no-console': 'warn',
'no-continue': 'off',
'no-nested-ternary': 'warn',
'no-param-reassign': 'off',
'no-plusplus': 'off',
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['pmcrypto/*'],
message:
'You should probably import from `@proton/crypto` instead: using `pmcrypto` directly is only needed for crypto-specific use cases.',
},
],
},
],
'no-restricted-syntax': [
'error',
{
selector:
'TaggedTemplateExpression > TemplateLiteral > TemplateElement.quasis[value.raw=/\\bProton\\b(?!\\s+(Account|Mail|Drive|Calendar|VPN|Verify))/i]',
message: 'Use `BRAND_NAME` instead to avoid possible translation.',
},
{
selector:
'TaggedTemplateExpression > TemplateLiteral > TemplateElement.quasis[value.raw=/\\bProton Account\\b/i]',
message: 'Use `${BRAND_NAME} Account` instead to allow translation of `Account`.',
},
{
selector:
'TaggedTemplateExpression > TemplateLiteral > TemplateElement.quasis[value.raw=/\\bProton Mail\\b/i]',
message: 'Use `MAIL_APP_NAME` instead to avoid possible translation.',
},
{
selector:
'TaggedTemplateExpression > TemplateLiteral > TemplateElement.quasis[value.raw=/\\bProton Drive\\b/i]',
message: 'Use `DRIVE_APP_NAME` instead to avoid possible translation.',
},
{
selector:
'TaggedTemplateExpression > TemplateLiteral > TemplateElement.quasis[value.raw=/\\bProton Calendar\\b/i]',
message: 'Use `CALENDAR_APP_NAME` instead to avoid possible translation.',
},
{
selector:
'TaggedTemplateExpression > TemplateLiteral > TemplateElement.quasis[value.raw=/\\bProton VPN\\b/i]',
message: 'Use `VPN_APP_NAME` instead to avoid possible translation.',
},
{
selector:
'TaggedTemplateExpression > TemplateLiteral > TemplateElement.quasis[value.raw=/\\bProton Verify\\b/i]',
message: 'Use `VERIFY_APP_NAME` instead to avoid possible translation.',
},
],
'no-shadow': 'off',
'no-void': [2, { allowAsStatement: true }],
'react-hooks/rules-of-hooks': 'error',
'react/display-name': 'warn',
'react/jsx-filename-extension': [
1,
{
extensions: ['.js', '.jsx', '.tsx'],
},
],
'react/jsx-props-no-spreading': 'off',
'react/prop-types': 'warn',
'react/require-default-props': 'off',
/*
* next two rules "off" because of the new JSX transform that
* came with React 17
*/
'react/jsx-uses-react': 'off',
'react/react-in-jsx-scope': 'off',
'react/forbid-component-props': [
'warn',
{
forbid: [
{
propName: 'data-test-id',
message: 'Please use `data-testid` instead',
},
],
},
],
'es/no-regexp-lookbehind-assertions': 'error',
'deprecation/deprecation': 'warn',
'no-only-tests/no-only-tests': 'error',
/*
* jsx-a11y
* set up some as warning only, while waiting real feedback
* disabled some
*/
'jsx-a11y/anchor-ambiguous-text': 'warn',
'jsx-a11y/anchor-is-valid': 'warn',
'jsx-a11y/click-events-have-key-events': 'warn',
'jsx-a11y/control-has-associated-label': 'warn',
'jsx-a11y/interactive-supports-focus': 'warn',
'jsx-a11y/label-has-associated-control': 'warn',
'jsx-a11y/media-has-caption': 'warn',
'jsx-a11y/mouse-events-have-key-events': 'warn',
'jsx-a11y/no-static-element-interactions': 'warn',
'jsx-a11y/no-interactive-element-to-noninteractive-role': 'warn',
'jsx-a11y/no-noninteractive-element-interactions': 'warn',
'jsx-a11y/no-noninteractive-tabindex': 'warn',
'jsx-a11y/no-aria-hidden-on-focusable': 'warn',
'jsx-a11y/prefer-tag-over-role': 'warn',
'jsx-a11y/img-redundant-alt': 'off',
'jsx-a11y/label-has-for': 'off',
'jsx-a11y/no-autofocus': 'off',
'jsx-a11y/no-onchange': 'off',
'custom-rules/deprecate-spacing-utility-classes': 'warn',
'custom-rules/deprecate-responsive-utility-classes': 'warn',
'custom-rules/deprecate-sizing-classes': 'warn',
'custom-rules/deprecate-classes': 'warn',
'custom-rules/no-template-in-translator-context': 'error',
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.ts', '.tsx'],
},
alias: {
map: [
['proton-mail', path.resolve(__dirname, '../../applications/mail/src/app')],
['tests', path.resolve(__dirname, '../../tests')],
['proton-pass-extension', path.resolve(__dirname, '../../applications/pass-extension/src')],
],
extensions: ['.ts', '.tsx'],
},
},
react: {
version: 'detect',
},
},
};
| 7,300
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/eslint-config-proton/package.json
|
{
"name": "@proton/eslint-config-proton",
"description": "Modern eslint config for a more civilized age",
"keywords": [
"eslint",
"eslintconfig",
"config",
"airbnb",
"javascript",
"styleguide",
"es2015",
"es2016",
"es2017",
"es2018"
],
"license": "GPL-3.0",
"author": "Proton AG",
"dependencies": {
"@typescript-eslint/eslint-plugin": "^6.12.0",
"@typescript-eslint/parser": "^6.12.0",
"eslint": "^8.54.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^17.1.0",
"eslint-config-prettier": "^9.0.0",
"eslint-import-resolver-alias": "^1.1.2",
"eslint-plugin-custom-rules": "workspace:packages/eslint-plugin-custom-rules",
"eslint-plugin-deprecation": "^2.0.0",
"eslint-plugin-es": "^4.1.0",
"eslint-plugin-import": "^2.29.0",
"eslint-plugin-monorepo-cop": "^1.0.2",
"eslint-plugin-no-only-tests": "^3.1.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0"
},
"peerDependencies": {
"prettier": "3.x",
"typescript": "*"
}
}
| 7,301
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/eslint-config-proton/tsconfig.json
|
{
"extends": "../../tsconfig.base.json"
}
| 7,302
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/eslint-plugin-custom-rules/deprecate-classes.js
|
/* eslint-env es6 */
// suggestedClassName is optional
const deprecatedClassNames = [
{
deprecatedClassName: 'mauto',
suggestedClassName: 'm-auto',
},
{
deprecatedClassName: 'center',
suggestedClassName: 'mx-auto',
},
{
deprecatedClassName: 'mxauto',
suggestedClassName: 'mx-auto',
},
{
deprecatedClassName: 'myauto',
suggestedClassName: 'my-auto',
},
{
deprecatedClassName: 'mtauto',
suggestedClassName: 'mt-auto',
},
{
deprecatedClassName: 'mrauto',
suggestedClassName: 'mr-auto',
},
{
deprecatedClassName: 'mbauto',
suggestedClassName: 'mb-auto',
},
{
deprecatedClassName: 'mlauto',
suggestedClassName: 'ml-auto',
},
{
deprecatedClassName: 'wauto',
suggestedClassName: 'w-auto',
},
{
deprecatedClassName: 'hauto',
suggestedClassName: 'h-auto',
},
{
deprecatedClassName: 'h0',
suggestedClassName: 'h-0',
},
{
deprecatedClassName: 'h100',
suggestedClassName: 'h-full',
},
{
deprecatedClassName: 'opacity-on-hover',
suggestedClassName: 'group-hover:opacity-100',
},
{
deprecatedClassName: 'opacity-on-hover-container',
suggestedClassName: 'group-hover-opacity-container',
},
{
deprecatedClassName: 'text-underline-on-hover',
suggestedClassName: 'hover:text-underline',
},
{
deprecatedClassName: 'opacity-on-focus',
suggestedClassName: 'opacity-0 focus:opacity-100',
},
{
deprecatedClassName: 'hide-on-hover',
suggestedClassName: 'group-hover:hidden',
},
{
deprecatedClassName: 'hide-on-hover-container',
suggestedClassName: 'group-hover-hide-container',
},
{
deprecatedClassName: 'on-hover-opacity-100',
suggestedClassName: '',
},
];
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: '',
url: 'https://design-system.protontech.ch',
},
},
create: (context) => {
return {
Literal(node) {
const { value } = node;
if (!value || !value.split) {
return;
}
const classes = new Set(value.split(' '));
deprecatedClassNames.forEach(({ deprecatedClassName, suggestedClassName }) => {
if (!classes.has(deprecatedClassName)) {
return;
}
const messageDeprecated = `"${deprecatedClassName}" has been deprecated.`;
const messageSuggested = suggestedClassName && `Please use "${suggestedClassName}" instead.`;
const message = `${messageDeprecated} ${messageSuggested}`;
context.report({
node,
message,
});
});
},
};
},
};
| 7,303
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/eslint-plugin-custom-rules/deprecate-responsive-utility-classes.js
|
/* eslint-env es6 */
const deprecatedClasses = [
{
pattern: /\b(on|no|auto)-(tiny-mobile|mobile|tablet|desktop)(-)?\b/,
getMessage: (match) =>
`"${match}" is deprecated. Please migrate to the new responsive utilities https://design-system.protontech.ch/?path=/docs/css-utilities-responsive--responsive`,
},
];
module.exports = {
meta: {
type: 'suggestion',
docs: {
description:
'The old responsive system classes are deprecated, please use the new mobile-first responsive system.',
url: 'https://design-system.protontech.ch/?path=/docs/css-utilities-responsive--responsive',
},
},
create: (context) => {
return {
Literal(node) {
const { value } = node;
if (!value || !value.split) {
return;
}
const classes = new Set(value.split(' '));
classes.forEach((className) => {
deprecatedClasses.forEach(({ pattern, getMessage }) => {
const match = pattern.exec(className);
if (match) {
const message = getMessage(match[0]);
context.report({
node,
message,
});
}
});
});
},
};
},
};
| 7,304
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/eslint-plugin-custom-rules/deprecate-sizing-classes.js
|
/* eslint-env es6 */
const deprecatedClasses = [
{
pattern: /\b((min|max)-)?w\d+(p|e|r|ch)?\b/,
getMessage: (match) =>
`"${match}" is deprecated. Please migrate to the new sizing utilities https://design-system.protontech.ch/?path=/docs/css-utilities-sizing--fractions`,
},
{
pattern: /\bmin-h\d+e\b/,
getMessage: (match) =>
`"${match}" is deprecated. Please migrate to the new sizing utilities https://design-system.protontech.ch/?path=/docs/css-utilities-sizing--fractions`,
},
];
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'The old sizing system classes are deprecated, please use the new mobile-first sizing system.',
url: 'https://design-system.protontech.ch/?path=/docs/css-utilities-sizing--fractions',
},
},
create: (context) => {
return {
Literal(node) {
const { value } = node;
if (!value || !value.split) {
return;
}
const classes = new Set(value.split(' '));
classes.forEach((className) => {
deprecatedClasses.forEach(({ pattern, getMessage }) => {
const match = pattern.exec(className);
if (match) {
const message = getMessage(match[0]);
context.report({
node,
message,
});
}
});
});
},
};
},
};
| 7,305
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/eslint-plugin-custom-rules/deprecate-spacing-utility-classes.js
|
/* eslint-env es6 */
const deprecatedClasses = [
{
pattern: /\b(on-(tiny-mobile|mobile|tablet|desktop)-)?[m][btlrxy]?\d+(-\d+)?\b/,
getMessage: (match) =>
`"${match}" is deprecated. Please migrate to the new margin utilities https://design-system.protontech.ch/?path=/docs/css-utilities-margin--margin`,
},
{
pattern: /\b(on-(tiny-mobile|mobile|tablet|desktop)-)?[p][btlrxy]?\d+(-\d+)?\b/,
getMessage: (match) =>
`"${match}" is deprecated. Please migrate to the new padding utilities https://design-system.protontech.ch/?path=/docs/css-utilities-padding--padding`,
},
{
pattern: /\b.*flex-gap.*\b/,
getMessage: (match) =>
`"${match}" is deprecated. Please migrate to the new gap utilities https://design-system.protontech.ch/?path=/docs/css-utilities-gap--gap`,
},
];
module.exports = {
meta: {
type: 'suggestion',
docs: {
description:
'The old spacing system classes are deprecated, please use the new mobile-first spacing system.',
url: 'https://design-system.protontech.ch/?path=/docs/css-utilities-margin--margin',
},
},
create: (context) => {
return {
Literal(node) {
const { value } = node;
if (!value || !value.split) {
return;
}
const classes = new Set(value.split(' '));
classes.forEach((className) => {
deprecatedClasses.forEach(({ pattern, getMessage }) => {
const match = pattern.exec(className);
if (match) {
const message = getMessage(match[0]);
context.report({
node,
message,
});
}
});
});
},
};
},
};
| 7,306
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/eslint-plugin-custom-rules/index.js
|
module.exports = {
rules: {
'deprecate-spacing-utility-classes': require('./deprecate-spacing-utility-classes'),
'deprecate-responsive-utility-classes': require('./deprecate-responsive-utility-classes'),
'deprecate-sizing-classes': require('./deprecate-sizing-classes'),
'deprecate-classes': require('./deprecate-classes'),
'no-template-in-translator-context': require('./no-template-in-translator-context'),
},
};
| 7,307
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/eslint-plugin-custom-rules/no-template-in-translator-context.js
|
/* eslint-env es6 */
const isValidTranslatorNode = (node) => {
return node.callee && node.callee.type === 'Identifier' && node.callee.name === 'c' && node.arguments.length === 1;
};
module.exports = {
meta: {
type: 'problem',
fixable: 'code',
docs: {
description: 'Forbid template literals in translator contexts.',
url: 'https://ttag.js.org/docs/context.html',
},
},
create: (context) => {
return {
CallExpression: function (node) {
if (!isValidTranslatorNode(node)) {
return;
}
const argument = node.arguments[0];
const argType = argument.type;
if (argType === 'TemplateLiteral') {
context.report({
node: node,
message: "Don't use template literals in translator contexts.",
fix(fixer) {
// 1. Check that we have no expressions in the template literal
const isFixable = argument.quasis.length === 1 && argument.expressions.length === 0;
if (!isFixable) {
return [];
}
// 2. Check that we can safely fix quotes
const text = context.sourceCode.getText(argument);
let quote = "'";
if (text.indexOf(quote) !== -1) {
quote = '"';
}
if (text.indexOf(quote) !== -1) {
return [];
}
// 3. Replace backticks with quotes
const innerText = text.slice(1, -1);
const result = `${quote}${innerText}${quote}`;
return [fixer.replaceText(argument, result)];
},
});
}
},
};
},
};
| 7,308
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/eslint-plugin-custom-rules/package.json
|
{
"name": "eslint-plugin-custom-rules",
"version": "1.0.0",
"main": "index.js"
}
| 7,309
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/.eslintrc.js
|
module.exports = {
extends: ['@proton/eslint-config-proton'],
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: __dirname,
project: './tsconfig.json',
},
ignorePatterns: ['.eslintrc.js'],
};
| 7,310
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/README.md
|
Generic business-agnostic utility react hooks.
1 module per hook. 1 test per hook.
| 7,311
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/index.ts
|
export { default as useCombinedRefs } from './useCombinedRefs';
export { default as useDateCountdown } from './useDateCountdown';
export { default as useInstance } from './useInstance';
export { default as useInterval } from './useInterval';
export { default as useLoading } from './useLoading';
export { default as useSynchronizingState } from './useSynchronizingState';
| 7,312
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/jest.config.js
|
module.exports = {
preset: 'ts-jest',
clearMocks: true,
testEnvironment: 'jsdom',
collectCoverageFrom: ['*.ts', '!index.ts'],
coverageReporters: ['text', 'lcov', 'cobertura'],
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
};
| 7,313
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/package.json
|
{
"name": "@proton/hooks",
"description": "Generic business use-case agnostic helper hooks",
"scripts": {
"check-types": "tsc",
"lint": "eslint . --ext ts --quiet --cache",
"test": "jest --coverage --runInBand --ci",
"test:dev": "jest --watch"
},
"dependencies": {
"@testing-library/react": "^12.1.5",
"@testing-library/react-hooks": "^8.0.1",
"react": "^17.0.2",
"react-test-renderer": "^17.0.2"
},
"devDependencies": {
"@proton/eslint-config-proton": "workspace:^",
"@types/jest": "^29.5.9",
"eslint": "^8.54.0",
"jest": "^29.7.0",
"ts-jest": "^29.1.1",
"typescript": "^5.3.2"
}
}
| 7,314
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/tsconfig.json
|
{
"extends": "../../tsconfig.base.json"
}
| 7,315
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useCombinedRefs.test.ts
|
import { createElement, useEffect, useRef } from 'react';
import { render } from '@testing-library/react';
import useCombinedRefs from './useCombinedRefs';
describe('useCombinedRefs', () => {
it('should correctly combine refs into one ref', async () => {
const cbRef = jest.fn();
const refs: { a: null | HTMLDivElement; b: null | HTMLDivElement } = { a: null, b: null };
const Test = () => {
const refA = useRef<HTMLDivElement>(null);
const refB = useRef<HTMLDivElement>(null);
const combinedRef = useCombinedRefs(refA, refB, cbRef, undefined);
useEffect(() => {
refs.a = refA.current;
refs.b = refB.current;
return () => {
refs.a = refA.current;
refs.b = refB.current;
};
});
return createElement('div', { ref: combinedRef, 'data-testid': 'div' });
};
const { getByTestId, rerender } = render(createElement(Test));
const div = getByTestId('div');
expect(refs.a).toBe(div);
expect(refs.b).toBe(div);
expect(cbRef).toHaveBeenCalledWith(div);
rerender(createElement('div'));
expect(cbRef).toHaveBeenCalledWith(null);
expect(refs.a).toBe(null);
expect(refs.b).toBe(null);
});
});
| 7,316
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useCombinedRefs.ts
|
import { Ref, useCallback } from 'react';
const useCombinedRefs = <T extends any>(...refs: (Ref<T> | undefined)[]): Ref<T> =>
useCallback(
(element: T) =>
refs.forEach((ref) => {
if (!ref) {
return;
}
// Ref can have two types - a function or an object. We treat each case.
if (typeof ref === 'function') {
return ref(element);
}
// As per https://github.com/facebook/react/issues/13029
// it should be fine to set current this way.
(ref as any).current = element;
}),
refs
);
export default useCombinedRefs;
| 7,317
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useControlled.test.ts
|
import { act, renderHook } from '@testing-library/react-hooks';
import useControlled from './useControlled';
describe('useControlled()', () => {
it('initializes with its passed value', () => {
const initial = 0;
const hook = renderHook(() => useControlled(initial));
const [state] = hook.result.current;
expect(state).toBe(initial);
});
it('ignores setState if a value from the outside is passed into it', () => {
const initial = 0;
const hook = renderHook(() => useControlled(initial));
act(() => {
const [, setState] = hook.result.current;
setState(1);
});
const [state] = hook.result.current;
expect(state).toBe(initial);
});
it('behaves like useState if no value is passed to it', () => {
const initial = undefined as undefined | number;
const hook = renderHook(() => useControlled(initial, 0));
const [stateOne] = hook.result.current;
expect(stateOne).toBe(0);
act(() => {
const [, setState] = hook.result.current;
setState(1);
});
const [stateTwo] = hook.result.current;
expect(stateTwo).toBe(1);
});
it('propagates values passed from the outside when they update', () => {
const hook = renderHook(({ initial }) => useControlled(initial), { initialProps: { initial: 0 } });
hook.rerender({ initial: 1 });
const [state] = hook.result.current;
expect(state).toBe(1);
});
it('switches from uncontrolled to controlled if initially no value is passed but later is', () => {
const hook = renderHook(({ initial }) => useControlled(initial), {
initialProps: { initial: undefined as undefined | number },
});
act(() => {
const [, setState] = hook.result.current;
setState(1);
});
hook.rerender({ initial: 2 });
const [stateTwo] = hook.result.current;
expect(stateTwo).toBe(2);
act(() => {
const [, setState] = hook.result.current;
setState(3);
});
const [stateThree] = hook.result.current;
expect(stateThree).toBe(2);
});
});
| 7,318
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useControlled.ts
|
import { useCallback, useState } from 'react';
export default function useControlled<V>(controlled: V, defaultValue?: V) {
const isControlled = controlled !== undefined;
const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);
const setValueIfUncontrolled = useCallback((v: V) => {
if (!isControlled) {
setUncontrolledValue(v);
}
}, []);
const value = isControlled ? controlled : uncontrolledValue;
/*
* type-cast here to ensure that this hook's return type is a tuple
* instead of an array as typescript seems to interpret it by default
*/
return [value, setValueIfUncontrolled] as const;
}
| 7,319
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useDateCountdown.test.ts
|
import { act, renderHook } from '@testing-library/react-hooks';
import { DAY, HOUR, MINUTE, SECOND } from '@proton/shared/lib/constants';
import useDateCountdown from './useDateCountdown';
describe('useDateCountdown', () => {
beforeAll(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
});
afterAll(() => {
jest.useRealTimers();
});
describe('interval', () => {
it('should default interval to update every second', () => {
const diff = 123456789;
const expiry = new Date(Date.now() + diff);
const { result } = renderHook(() => useDateCountdown(expiry));
const initialExpectedValue = {
days: 1,
diff,
expired: false,
hours: 10,
minutes: 17,
seconds: 36,
};
expect(result.current).toStrictEqual(initialExpectedValue);
// fast-forward time until 1 millisecond before it should be updated
act(() => {
jest.advanceTimersByTime(SECOND - 1);
});
expect(result.current).toStrictEqual(initialExpectedValue);
// fast-forward until 1st update should be
act(() => {
jest.advanceTimersByTime(1);
});
expect(result.current).toStrictEqual({ ...initialExpectedValue, diff: diff - SECOND, seconds: 35 });
});
it('should allow configuration of interval', () => {
const diff = 123456789;
const interval = 500;
const expiry = new Date(Date.now() + diff);
const { result } = renderHook(() => useDateCountdown(expiry, { interval }));
const initialExpectedValue = {
days: 1,
diff,
expired: false,
hours: 10,
minutes: 17,
seconds: 36,
};
expect(result.current).toStrictEqual(initialExpectedValue);
// fast-forward time until 1 millisecond before it should be updated
act(() => {
jest.advanceTimersByTime(interval - 1);
});
expect(result.current).toStrictEqual(initialExpectedValue);
// fast-forward until 1st update should be
act(() => {
jest.advanceTimersByTime(1);
});
expect(result.current).toStrictEqual({ ...initialExpectedValue, diff: diff - interval });
});
});
describe('expired', () => {
it('should be false when date is in the future', () => {
const expiry = new Date(Date.now() + 1000);
const { result } = renderHook(() => useDateCountdown(expiry));
const value = result.current;
expect(value.expired).toBeFalsy();
});
it('should be false when date now', () => {
const expiry = new Date(Date.now());
const { result } = renderHook(() => useDateCountdown(expiry));
const value = result.current;
expect(value.expired).toBeFalsy();
});
it('should be true when date is in the past', () => {
const expiry = new Date(Date.now() - 1000);
const { result } = renderHook(() => useDateCountdown(expiry));
const value = result.current;
expect(value.expired).toBeTruthy();
});
it('should return negative diff', () => {
const expiry = new Date(Date.now());
const { result } = renderHook(() => useDateCountdown(expiry));
const advanceBy = 1 * DAY + 2 * HOUR + 3 * MINUTE + 4 * SECOND;
act(() => {
jest.advanceTimersByTime(advanceBy);
});
expect(result.current).toStrictEqual({
diff: -advanceBy,
expired: true,
days: 1,
hours: 2,
minutes: 3,
seconds: 4,
});
});
});
it('should correctly countdown', () => {
let diff = 2 * DAY + 12 * HOUR + 3 * MINUTE + 32 * SECOND;
const expiry = new Date(Date.now() + diff);
const { result } = renderHook(() => useDateCountdown(expiry));
expect(result.current).toStrictEqual({
diff,
expired: false,
days: 2,
hours: 12,
minutes: 3,
seconds: 32,
});
// fast-forward time 1 Day
act(() => {
jest.advanceTimersByTime(DAY);
});
diff -= DAY;
expect(result.current).toStrictEqual({
diff,
expired: false,
days: 1,
hours: 12,
minutes: 3,
seconds: 32,
});
// fast-forward time 1 Hour
act(() => {
jest.advanceTimersByTime(HOUR);
});
diff -= HOUR;
expect(result.current).toStrictEqual({
diff,
expired: false,
days: 1,
hours: 11,
minutes: 3,
seconds: 32,
});
// fast-forward time 1 Minute
act(() => {
jest.advanceTimersByTime(MINUTE);
});
diff -= MINUTE;
expect(result.current).toStrictEqual({
diff,
expired: false,
days: 1,
hours: 11,
minutes: 2,
seconds: 32,
});
// fast-forward time 1 Second
act(() => {
jest.advanceTimersByTime(SECOND);
});
diff -= SECOND;
expect(result.current).toStrictEqual({
diff,
expired: false,
days: 1,
hours: 11,
minutes: 2,
seconds: 31,
});
// fast-forward rest
act(() => {
jest.advanceTimersByTime(1 * DAY + 11 * HOUR + 2 * MINUTE + 31 * SECOND);
});
expect(result.current).toStrictEqual({
diff: 0,
expired: false,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
});
// fast-forward to past expiry
act(() => {
jest.advanceTimersByTime(1 * DAY + 2 * HOUR + 3 * MINUTE + 4 * SECOND);
});
expect(result.current).toStrictEqual({
diff: -93784000,
expired: true,
days: 1,
hours: 2,
minutes: 3,
seconds: 4,
});
});
});
| 7,320
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useDateCountdown.ts
|
import { useState } from 'react';
import { differenceInMilliseconds } from 'date-fns';
import { DAY, HOUR, MINUTE, SECOND } from '@proton/shared/lib/constants';
import useInterval from './useInterval';
const EVERY_SECOND = SECOND;
export interface DateCountdown {
/**
* Difference between the two dates in milliseconds.
*/
diff: number;
/**
* Number of days remaining.
*/
days: number;
/**
* Number of hours remaining.
*/
hours: number;
/**
* Number of minutes remaining.
*/
minutes: number;
/**
* Number of seconds remaining.
*/
seconds: number;
/**
* Whether the countdown is expired.
* `true` if the `end` date is in the past.
*/
expired: boolean;
}
export interface DateCountdownOptions {
interval?: number;
}
const useDateCountdown = (
/**
* The date the countdown counts down to.
*/
expiry: Date,
{
/**
* Number of milliseconds between updates
*/
interval = EVERY_SECOND,
}: DateCountdownOptions = {}
): DateCountdown => {
const [now, setNow] = useState(() => new Date());
useInterval(() => setNow(new Date()), interval);
const diff = differenceInMilliseconds(expiry, now);
const expired = diff < 0;
const absoluteDiff = Math.abs(diff);
const days = Math.floor(absoluteDiff / DAY);
const hours = Math.floor((absoluteDiff % DAY) / HOUR);
const minutes = Math.floor((absoluteDiff % HOUR) / MINUTE);
const seconds = Math.floor((absoluteDiff % MINUTE) / SECOND);
return { expired, diff, days, hours, minutes, seconds };
};
export default useDateCountdown;
| 7,321
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useInstance.test.ts
|
import { act, renderHook } from '@testing-library/react-hooks';
import useInstance from './useInstance';
describe('useInstance()', () => {
it('initiates with the value returned from its callback argument', () => {
const hook = renderHook(() => useInstance(() => 'initial'));
expect(hook.result.current).toBe('initial');
});
it('keeps referential equality of the initial value between render cycles', () => {
const initial = {};
const hook = renderHook(() => useInstance(() => initial));
act(() => {});
expect(hook.result.current).toBe(initial);
});
it('only executes the passed callback once', () => {
const callback = jest.fn(() => 'initial');
renderHook(() => useInstance(callback));
act(() => {});
expect(callback).toHaveBeenCalledTimes(1);
});
});
| 7,322
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useInstance.ts
|
import { useRef } from 'react';
/**
* Use ref with callback support.
*/
const useInstance = <T>(fn: () => T): T => {
const ref = useRef<T>();
if (!ref.current) {
ref.current = fn();
}
return ref.current;
};
export default useInstance;
| 7,323
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useInterval.test.ts
|
import { renderHook } from '@testing-library/react-hooks';
import useInterval from './useInterval';
describe('useInterval', () => {
let callback: jest.Mock<any, any>;
let setInterval: jest.SpyInstance<any, any>;
let clearInterval: jest.SpyInstance<any, any>;
beforeEach(() => {
callback = jest.fn();
setInterval = jest.spyOn(window, 'setInterval');
clearInterval = jest.spyOn(window, 'clearInterval');
});
beforeAll(() => {
jest.useFakeTimers();
});
afterEach(() => {
callback.mockRestore();
jest.clearAllTimers();
});
afterAll(() => {
jest.useRealTimers();
});
it('should init hook with no delay', () => {
const { result } = renderHook(() => useInterval(callback, null));
const value = result.current;
expect(value).toBeUndefined();
// if null delay provided, it's assumed as no delay
expect(setInterval).not.toHaveBeenCalled();
});
it('should set pass delay to setInterval', () => {
const delay = 5000;
const { result } = renderHook(() => useInterval(callback, delay));
const value = result.current;
expect(value).toBeUndefined();
expect(setInterval).toHaveBeenCalledTimes(1);
expect(setInterval).toHaveBeenCalledWith(expect.any(Function), delay);
});
it('should repeatedly calls provided callback with a fixed time delay between each call', () => {
renderHook(() => useInterval(callback, 200));
expect(callback).not.toHaveBeenCalled();
// fast-forward time until 1 millisecond before it should be executed
jest.advanceTimersByTime(199);
expect(callback).not.toHaveBeenCalled();
// fast-forward until 1st call should be executed
jest.advanceTimersByTime(1);
expect(callback).toHaveBeenCalledTimes(1);
// fast-forward until next timer should be executed
jest.advanceTimersToNextTimer();
expect(callback).toHaveBeenCalledTimes(2);
// fast-forward until 3 more timers should be executed
jest.advanceTimersToNextTimer(3);
expect(callback).toHaveBeenCalledTimes(5);
});
it('should clear interval on unmount', () => {
const { unmount } = renderHook(() => useInterval(callback, 200));
const initialTimerCount = jest.getTimerCount();
expect(clearInterval).not.toHaveBeenCalled();
unmount();
expect(clearInterval).toHaveBeenCalledTimes(1);
expect(jest.getTimerCount()).toBe(initialTimerCount - 1);
});
it('should handle new interval when delay is updated', () => {
let delay = 200;
const { rerender } = renderHook(() => useInterval(callback, delay));
expect(callback).not.toHaveBeenCalled();
// fast-forward initial delay
jest.advanceTimersByTime(200);
expect(callback).toHaveBeenCalledTimes(1);
// update delay by increasing previous one
delay = 500;
rerender();
// fast-forward initial delay again but this time it should not execute the cb
jest.advanceTimersByTime(200);
expect(callback).toHaveBeenCalledTimes(1);
// fast-forward remaining time for new delay
jest.advanceTimersByTime(300);
expect(callback).toHaveBeenCalledTimes(2);
});
it('should clear pending interval when delay is updated', () => {
let delay = 200;
const { rerender } = renderHook(() => useInterval(callback, delay));
expect(clearInterval).not.toHaveBeenCalled();
const initialTimerCount = jest.getTimerCount();
// update delay while there is a pending interval
delay = 500;
rerender();
expect(clearInterval).toHaveBeenCalledTimes(1);
expect(jest.getTimerCount()).toBe(initialTimerCount);
});
});
| 7,324
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useInterval.ts
|
// https://usehooks-ts.com/react-hook/use-interval
// See also https://overreacted.io/making-setinterval-declarative-with-react-hooks/
import { useEffect, useRef } from 'react';
import noop from '@proton/utils/noop';
const useInterval = (callback: () => void, delay: number | null) => {
const savedCallback = useRef<() => void>(noop);
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
if (delay === null) {
return;
}
const id = setInterval(() => savedCallback.current(), delay);
return () => clearInterval(id);
}, [delay]);
};
export default useInterval;
| 7,325
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useIsMounted.test.ts
|
import { act, renderHook } from '@testing-library/react-hooks';
import useIsMounted from './useIsMounted';
describe('useIsMounted()', () => {
it('returns false initially', () => {
const hook = renderHook(() => useIsMounted());
const isMounted = hook.result.current();
/**
* TODO: expected this to return false if the callback
* returned from renderHook is called immediately, however
* this is true it seems.
*
* Tried removing the useCallback from inside useIsMounted,
* tried removing the callback entirely and just returning
* the ref directly, but it's true every time.
*
* This is probably an issue with @testing-library/react-hooks.
*
* The test below also doesn't really make sense given this
* as it's true both before and after the act() call.
*/
// expect(isMounted).toBe(false);
expect(isMounted).toBe(true);
});
it('returns true after mount', () => {
const hook = renderHook(() => useIsMounted());
act(() => {});
const isMounted = hook.result.current();
expect(isMounted).toBe(true);
});
});
| 7,326
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useIsMounted.ts
|
import { useCallback, useEffect, useRef } from 'react';
const useIsMounted = () => {
const ref = useRef(false);
useEffect(() => {
ref.current = true;
return () => {
ref.current = false;
};
}, []);
return useCallback(() => {
return ref.current;
}, []);
};
export default useIsMounted;
| 7,327
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useLoading.test.ts
|
import { act, renderHook } from '@testing-library/react-hooks';
import useLoading, { useLoadingByKey } from '@proton/hooks/useLoading';
import { createPromise } from '@proton/shared/lib/helpers/promise';
describe('useLoading', () => {
it('should return loading false by default', () => {
const { result } = renderHook(() => useLoading());
const [loading] = result.current;
expect(loading).toEqual(false);
});
it('should allow setting of initial loading state', () => {
const { result } = renderHook(() => useLoading(true));
const [loading] = result.current;
expect(loading).toEqual(true);
});
it('should resolve withLoading if there is no promise', async () => {
const { result } = renderHook(() => useLoading());
const [loading, withLoading] = result.current;
await act(async () => {
const resolved = await withLoading(undefined);
expect(resolved).toEqual(undefined);
});
expect(loading).toEqual(false);
});
it('should resolve promise and returns the result', async () => {
const { result } = renderHook(() => useLoading());
const [, withLoading] = result.current;
await act(async () => {
const resolved = await withLoading(Promise.resolve('resolved result'));
expect(resolved).toEqual('resolved result');
});
const [loading] = result.current;
expect(loading).toEqual(false);
});
it('should reject if promise rejects', async () => {
const { result } = renderHook(() => useLoading());
const [, withLoading] = result.current;
const error = new Error('some error');
expect.assertions(2);
await act(async () => {
try {
await withLoading(Promise.reject(error));
} catch (e) {
expect(e).toEqual(error);
}
});
const [loading] = result.current;
expect(loading).toEqual(false);
});
it('should render loading state', async () => {
const { result } = renderHook(() => useLoading());
const [, withLoading] = result.current;
const { promise, resolve } = createPromise<void>();
let wrappedPromise: Promise<unknown>;
act(() => {
wrappedPromise = withLoading(promise);
});
let [loading] = result.current;
expect(loading).toEqual(true);
await act(async () => {
resolve();
await wrappedPromise;
});
[loading] = result.current;
expect(loading).toEqual(false);
});
it('should ignore previous promises', async () => {
const { result } = renderHook(() => useLoading());
const [, withLoading] = result.current;
const { promise: promise1, resolve: resolve1 } = createPromise();
const { promise: promise2, resolve: resolve2 } = createPromise();
await act(async () => {
const wrappedPromise1 = withLoading(promise1);
const wrappedPromise2 = withLoading(promise2);
resolve1('First result');
resolve2('Second result');
expect(await wrappedPromise1).toEqual(undefined);
expect(await wrappedPromise2).toEqual('Second result');
});
});
it('should ignore previous errors', async () => {
const { result } = renderHook(() => useLoading());
const [, withLoading] = result.current;
const { promise: promise1, reject: reject1 } = createPromise();
const { promise: promise2, reject: reject2 } = createPromise();
await act(async () => {
const wrappedPromise1 = withLoading(promise1);
const wrappedPromise2 = withLoading(promise2);
let handledFirstReject = false;
wrappedPromise1.catch(() => {
handledFirstReject = true;
});
let handledSecondReject = false;
wrappedPromise2.catch(() => {
handledSecondReject = true;
});
reject1('First reject reason');
reject2('Second reject reason');
// Handle promises before doing the checks. Switching the control flow in the event loop.
expect.assertions(3);
await new Promise((resolve) => setTimeout(resolve));
expect(handledFirstReject).toEqual(false);
expect(handledSecondReject).toEqual(true);
expect(await wrappedPromise1).toEqual(undefined);
});
});
it('should support functions as an argument', async () => {
const { result } = renderHook(() => useLoading());
const [, withLoading] = result.current;
async function run(): Promise<string> {
return 'resolved result';
}
await act(async () => {
const resolvedResult = await withLoading(run);
expect(resolvedResult).toEqual('resolved result');
});
});
it('should expose setLoading', async () => {
const { result } = renderHook(() => useLoading());
const [, , setLoading] = result.current;
act(() => {
setLoading(true);
});
const [loading] = result.current;
expect(loading).toBe(true);
});
});
describe('useLoadingByKey', () => {
describe('when initial state is not provided', () => {
it('should return empty map', () => {
const { result } = renderHook(() => useLoadingByKey());
const [loading] = result.current;
expect(loading).toStrictEqual({});
});
});
describe('when initial state is provided', () => {
it('should return it at first', () => {
const { result } = renderHook(() => useLoadingByKey({ keyA: true }));
const [loading] = result.current;
expect(loading).toStrictEqual({ keyA: true });
});
});
describe('when promise is undefined', () => {
it('should resolve withLoading', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, withLoading] = result.current;
const resolved = await act(() => withLoading('keyA', undefined));
expect(resolved).toEqual(undefined);
const [loading] = result.current;
expect(loading).toEqual({ keyA: false });
});
});
describe('when promise is defined', () => {
it('should resolve promise and returns the result', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, withLoading] = result.current;
await act(async () => {
const resolved = await withLoading('keyA', Promise.resolve('resolved result'));
expect(resolved).toEqual('resolved result');
});
const [loading] = result.current;
expect(loading).toEqual({ keyA: false });
});
it('should reject if promise rejects', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, withLoading] = result.current;
const error = new Error('some error');
expect.assertions(2);
await act(async () => {
try {
await withLoading('keyA', Promise.reject(error));
} catch (e) {
expect(e).toEqual(error);
}
});
const [loading] = result.current;
expect(loading).toStrictEqual({ keyA: false });
});
it('should render loading state', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, withLoading] = result.current;
const { promise, resolve } = createPromise<void>();
let wrappedPromise: Promise<unknown>;
act(() => {
wrappedPromise = withLoading('keyA', promise);
});
let [loading] = result.current;
expect(loading).toStrictEqual({ keyA: true });
await act(async () => {
resolve();
await wrappedPromise;
});
[loading] = result.current;
expect(loading).toStrictEqual({ keyA: false });
});
it('should ignore previous promises', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, withLoading] = result.current;
const { promise: promise1, resolve: resolve1 } = createPromise();
const { promise: promise2, resolve: resolve2 } = createPromise();
await act(async () => {
const wrappedPromise1 = withLoading('keyA', promise1);
const wrappedPromise2 = withLoading('keyA', promise2);
resolve1('First result');
resolve2('Second result');
expect(await wrappedPromise1).toEqual(undefined);
expect(await wrappedPromise2).toEqual('Second result');
});
});
it('should ignore previous errors', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, withLoading] = result.current;
const { promise: promise1, reject: reject1 } = createPromise();
const { promise: promise2, reject: reject2 } = createPromise();
await act(async () => {
const wrappedPromise1 = withLoading('keyA', promise1);
const wrappedPromise2 = withLoading('keyA', promise2);
let handledFirstReject = false;
wrappedPromise1.catch(() => {
handledFirstReject = true;
});
let handledSecondReject = false;
wrappedPromise2.catch(() => {
handledSecondReject = true;
});
reject1('First reject reason');
reject2('Second reject reason');
// Handle promises before doing the checks. Switching the control flow in the event loop.
expect.assertions(3);
await new Promise((resolve) => setTimeout(resolve));
expect(handledFirstReject).toEqual(false);
expect(handledSecondReject).toEqual(true);
expect(await wrappedPromise1).toEqual(undefined);
});
});
it('should ignore previous errors', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, withLoading] = result.current;
const { promise: promise1, reject: reject1 } = createPromise();
const { promise: promise2, reject: reject2 } = createPromise();
await act(async () => {
const wrappedPromise1 = withLoading('keyA', promise1);
const wrappedPromise2 = withLoading('keyA', promise2);
let handledFirstReject = false;
wrappedPromise1.catch(() => {
handledFirstReject = true;
});
let handledSecondReject = false;
wrappedPromise2.catch(() => {
handledSecondReject = true;
});
reject1('First reject reason');
reject2('Second reject reason');
// Handle promises before doing the checks. Switching the control flow in the event loop.
expect.assertions(3);
await new Promise((resolve) => setTimeout(resolve));
expect(handledFirstReject).toEqual(false);
expect(handledSecondReject).toEqual(true);
expect(await wrappedPromise1).toEqual(undefined);
});
});
it('should support functions as an argument', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, withLoading] = result.current;
async function run(): Promise<string> {
return 'resolved result';
}
await act(async () => {
const resolvedResult = await withLoading('keyA', run);
expect(resolvedResult).toEqual('resolved result');
});
});
it('should expose setLoading', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, , setLoading] = result.current;
act(() => {
setLoading('keyA', true);
});
const [loading] = result.current;
expect(loading).toStrictEqual({ keyA: true });
});
});
describe('when several keys are used', () => {
it('should not conflict between each other', async () => {
const { result } = renderHook(() => useLoadingByKey());
const [, withLoading] = result.current;
const { promise: promise1, resolve: resolve1 } = createPromise();
const { promise: promise2, resolve: resolve2 } = createPromise();
let wrappedPromise1: Promise<unknown>;
let wrappedPromise2: Promise<unknown>;
await act(async () => {
wrappedPromise1 = withLoading('keyA', promise1);
});
let [loading] = result.current;
expect(loading).toStrictEqual({ keyA: true });
await act(async () => {
wrappedPromise2 = withLoading('keyB', promise2);
});
[loading] = result.current;
expect(loading).toStrictEqual({ keyA: true, keyB: true });
await act(async () => {
resolve2('Second result');
expect(await wrappedPromise2).toEqual('Second result');
});
[loading] = result.current;
expect(loading).toStrictEqual({ keyA: true, keyB: false });
await act(async () => {
resolve1('First result');
expect(await wrappedPromise1).toEqual('First result');
});
[loading] = result.current;
expect(loading).toStrictEqual({ keyA: false, keyB: false });
});
});
});
| 7,328
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useLoading.ts
|
import { useCallback, useEffect, useRef, useState } from 'react';
import { SimpleMap } from '@proton/shared/lib/interfaces';
import isFunction from '@proton/utils/isFunction';
export type WithLoading = <T>(promise: undefined | Promise<T | void> | (() => Promise<T | void>)) => Promise<T | void>;
export type WithLoadingByKey = <T>(
key: string,
promise: undefined | Promise<T | void> | (() => Promise<T | void>)
) => Promise<T | void>;
function unwrapPromise<T>(maybeWrappedPromise: Promise<T | void> | (() => Promise<T | void>)): Promise<T | void> {
if (isFunction(maybeWrappedPromise)) {
return maybeWrappedPromise();
}
return maybeWrappedPromise;
}
export type LoadingByKey = SimpleMap<boolean>;
export const useLoadingByKey = (
initialState: LoadingByKey = {}
): [LoadingByKey, WithLoadingByKey, (key: string, loading: boolean) => void] => {
const [loading, setLoading] = useState<LoadingByKey>(initialState);
const unmountedRef = useRef(false);
const counterRefByKey = useRef<SimpleMap<number>>({});
const getCurrentCounterRef = (key: string) => {
return counterRefByKey.current[key] ?? 0;
};
const withLoading = useCallback<WithLoadingByKey>((key: string, maybeWrappedPromise) => {
if (!maybeWrappedPromise) {
setLoading((prev) => ({ ...prev, [key]: false }));
return Promise.resolve();
}
const promise = unwrapPromise(maybeWrappedPromise);
const counterNext = getCurrentCounterRef(key) + 1;
counterRefByKey.current = { ...counterRefByKey.current, [key]: counterNext };
setLoading((prev) => ({ ...prev, [key]: true }));
return promise
.then((result) => {
// Ensure that the latest promise is setting the new state
if (getCurrentCounterRef(key) !== counterNext) {
return;
}
if (!unmountedRef.current) {
setLoading((prev) => ({ ...prev, [key]: false }));
}
return result;
})
.catch((e) => {
if (getCurrentCounterRef(key) !== counterNext) {
return;
}
if (!unmountedRef.current) {
setLoading((prev) => ({ ...prev, [key]: false }));
}
throw e;
});
}, []);
const setManualLoading = (key: string, value: boolean) => {
setLoading((prev) => ({ ...prev, [key]: value }));
};
useEffect(() => {
unmountedRef.current = false;
return () => {
unmountedRef.current = true;
};
}, []);
return [loading, withLoading, setManualLoading];
};
const SINGLE_LOADING_KEY = 'main';
const useLoading = (initialState = false): [boolean, WithLoading, (loading: boolean) => void] => {
const [loadingByKey, withLoadingByKey, setLoadingByKey] = useLoadingByKey({ [SINGLE_LOADING_KEY]: initialState });
const withLoading: WithLoading = (args) => {
return withLoadingByKey(SINGLE_LOADING_KEY, args);
};
const setLoading = (loading: boolean) => {
return setLoadingByKey(SINGLE_LOADING_KEY, loading);
};
return [loadingByKey[SINGLE_LOADING_KEY] as boolean, withLoading, setLoading];
};
export default useLoading;
| 7,329
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/usePrevious.test.ts
|
import { renderHook } from '@testing-library/react-hooks';
import usePrevious from './usePrevious';
describe('usePrevious()', () => {
it('remembers the value passed to it in the previous render cycle', () => {
const hook = renderHook(({ initial }) => usePrevious(initial), { initialProps: { initial: 0 } });
hook.rerender({ initial: 1 });
const previous = hook.result.current;
expect(previous).toBe(0);
});
});
| 7,330
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/usePrevious.ts
|
import { useEffect, useRef } from 'react';
const usePrevious = <T>(value: T) => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
export default usePrevious;
| 7,331
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useSynchronizingState.test.ts
|
import { act, renderHook } from '@testing-library/react-hooks';
import useSynchronizingState from './useSynchronizingState';
describe('useSynchronizingState()', () => {
it('initiates with the value passed to it', () => {
const hook = renderHook(() => useSynchronizingState('initial'));
const [value] = hook.result.current;
expect(value).toBe('initial');
});
it('sets the state just as useState would', () => {
const initial = 0;
const hook = renderHook(() => useSynchronizingState(initial));
act(() => {
const [, setState] = hook.result.current;
setState(1);
});
const [value] = hook.result.current;
expect(value).toBe(1);
});
it('synchronizes with the value passed to it on updates', () => {
const hook = renderHook(({ initial }) => useSynchronizingState(initial), { initialProps: { initial: 0 } });
hook.rerender({ initial: 1 });
const [value] = hook.result.current;
expect(value).toBe(1);
});
});
| 7,332
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/hooks/useSynchronizingState.ts
|
import { useEffect, useState } from 'react';
/*
* Same as setState with the difference being that the value
* passed in the argument of the hook is not only an initial
* value but will synchronize with the returned state should
* it change (pointer identity).
*/
const useSynchronizingState = <V>(value: V) => {
const [state, setState] = useState<V>(value);
useEffect(() => {
setState(value);
}, [value]);
return [state, setState] as const;
};
export default useSynchronizingState;
| 7,333
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/i18n/.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',
'@typescript-eslint/no-unused-expressions': 'off',
},
ignorePatterns: ['.eslintrc.js'],
};
| 7,334
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/i18n/.prettierignore
|
test
| 7,335
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/i18n/LICENSE
|
The MIT License (MIT)
Copyright (c) 2019 by Proton Technologies A.G. (Switzerland) Email: contact@protonmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
| 7,336
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/i18n/Readme.md
|
# Proton I18N
A CLI to manage translations - validation - extraction
We use [ttag](https://github.com/ttag-org/ttag) for our React projects and [angular-gettext](https://github.com/rubenv/angular-gettext) for our [WebClient](https://github.com/ProtonMail/WebClient).
## Commands
```sh
$ npx proton-i18n help
Usage: $ proton-i18n <command>
Available commands:
- validate <type>
To validate the translations, check if we have contexts
- type: default (default) validate we don't have missing context
- type: lint-functions check if we use the right format for ttag
- extract <type>
Extract all translations from the projet
- type: default (app) extract translations from the app and reactComponents + shared
- type: reactComponents extract only translations from react-components
- type: shared extract only translations from proton-shared
```
## How to setup ?
You need to have a file `.env` inside the directory `<project>/env/`.
```sh
I18N_TEMPLATE_FILE:<FILE SOURCE TO UPLOAD TO CROWDIN>
```
You don't need these key if you don't manage crowdin, for extraction and validation we won't need them.
- `I18N_TEMPLATE_FILE`: Default value -> `po/template.pot`
> We need this key to detect the project as we require some custom code for it.
## Tests
`$ npm test`
| 7,337
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/i18n/config.js
|
const path = require('path');
module.exports = {
TEMPLATE_FILE: process.env.I18N_TEMPLATE_FILE || path.join('po', 'template.pot'),
};
| 7,338
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/i18n/help
|
Usage: $ proton-i18n <command>
Available commands:
- [blue]validate[/blue] [yellow]<type>[/yellow]
To validate the translations, check if we have contexts
- type: default (default) validate we don't have missing context
- type: lint-functions check if we use the right format for ttag
- [blue]extract[/blue] [yellow]<type>[/yellow]
Extract all translations from the projet
- type: default (app) extract translations from the app and reactComponents + shared
- type: reactComponents extract only translations from @proton/components
- type: shared extract only translations from @proton/shared
| 7,339
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/i18n/index.js
|
#!/usr/bin/env node
const { error } = require('./lib/helpers/log')('proton-i18n');
const renderHelp = require('./lib/helpers/help');
const argv = process.argv.slice(2);
const is = (command) => argv.includes(command);
async function main() {
const [, ...options] = argv;
if (is('extract')) {
await require('./lib/extract')(options[0]);
}
if (is('validate')) {
const flags = { isVerbose: options.includes('--verbose') };
const args = options.filter((val) => !val.startsWith('--'));
await require('./lib/validate')(options[0], { dir: args[1], flags });
}
if (is('help')) {
renderHelp();
}
process.exit(0);
}
main().catch(error);
| 7,340
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/i18n/package.json
|
{
"name": "@proton/i18n",
"description": "CLI to extract/validate translations from the code",
"keywords": [],
"license": "ISC",
"author": "Proton AG",
"main": "index.js",
"bin": {
"proton-i18n": "index.js"
},
"scripts": {
"lint": "eslint lib index.js config.js --ext .js --quiet --cache",
"pretty": "prettier --write $(find lib/ index.js -type f -name '*.js')",
"test": "./test/test-linter.sh* && ./test/test-validator.sh"
},
"dependencies": {
"chalk": "^4.1.2",
"execa": "^5.1.1",
"gettext-parser": "^7.0.1",
"glob": "^10.3.10",
"ttag-cli": "^1.10.9"
},
"devDependencies": {
"cross-env": "^7.0.3",
"eslint": "^8.54.0",
"prettier": "^3.1.0"
},
"engines": {
"node": ">= v20.9.0"
}
}
| 7,341
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/i18n/tsconfig.json
|
{
"extends": "../../tsconfig.base.json"
}
| 7,342
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib/extract.js
|
const { TEMPLATE_FILE } = require('../config');
const { success, debug } = require('./helpers/log')('proton-i18n');
const { hasDirectory } = require('./helpers/file');
const { script, bash } = require('./helpers/cli');
const PATHS = {
reactComponents: ['{components,containers,helpers,hooks}'],
shared: ['lib'],
};
async function extractor(app = 'app') {
debug(app, 'type of extraction');
if (app !== 'app') {
const dest = PATHS[app].join(' ');
if (!dest) {
throw new Error('Unknown app target');
}
const cmd = `yarn dlx -p ttag-cli ttag extract $(find ${dest} -type f -name '*.js' -o -name '*.ts' -o -name '*.tsx' -o -name '*.jsx') -o ${TEMPLATE_FILE}`;
debug(cmd);
return bash(cmd);
}
return script('extract.sh', [TEMPLATE_FILE], 'inherit');
}
async function main(app) {
await hasDirectory(TEMPLATE_FILE);
const { stdout } = await extractor(app);
debug(stdout);
success(`Translations extracted to ${TEMPLATE_FILE}`);
}
module.exports = main;
| 7,343
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib/validate.js
|
const fs = require('fs');
const path = require('path');
const gettextParser = require('gettext-parser');
const { success, debug } = require('./helpers/log')('proton-i18n');
const { TEMPLATE_FILE } = require('../config');
const { scriptNode } = require('./helpers/cli');
const isLint = process.argv.includes('--lint');
/**
* Parse pot file and find translations without a context
* @param {object} translations po object
* @param {string} except
*/
const getNoContextsExcept = (translations, except) => {
const emptyContexts = translations[''];
const emptyContextsKeys = Object.keys(emptyContexts);
return emptyContextsKeys
.filter((translationKey) => {
const translation = emptyContexts[translationKey];
return !(Array.isArray(translation.msgstr) && translation.msgstr.some((str) => str.includes(except)));
})
.map((key) => JSON.stringify(emptyContexts[key], null, 2));
};
function validateWithoutContext(translations) {
const translationsWithoutContext = getNoContextsExcept(translations, 'Plural-Forms');
const total = translationsWithoutContext.length;
if (!total) {
!isLint && success('All translations have a context, good job !');
return;
}
!isLint && console.log(translationsWithoutContext.sort().join('\n'));
throw new Error(`${total} ${total > 1 ? 'translations' : 'translation'} without context !`);
}
function getVariables(msgid) {
const variableREG = /\$\{\s*([.\w+[\]])*\s*\}/g;
return msgid.match(variableREG) || [];
}
function getWithoutMatchingVariables(translations) {
return Object.keys(translations)
.map((contextKey) => {
const translationsInContext = translations[contextKey];
return Object.keys(translationsInContext).map((translationKey) => translationsInContext[translationKey]);
})
.flat()
.filter(({ msgid_plural: msgIdPlural, msgid }) => {
if (!msgIdPlural) {
return;
}
const variablesSingle = getVariables(msgid).sort().join('');
const variablesPlural = getVariables(msgIdPlural).sort().join('');
return variablesSingle !== variablesPlural;
})
.map((x) => JSON.stringify(x, null, 2));
}
function validateVariables(translations) {
const translationsWithoutMatching = getWithoutMatchingVariables(translations);
const total = translationsWithoutMatching.length;
if (!total) {
!isLint && success('All translations have matching variables');
return;
}
!isLint && console.log(translationsWithoutMatching.sort().join('\n'));
throw new Error(`${total} ${total > 1 ? 'translations' : 'translation'} without matching variables !`);
}
async function main(mode, { dir, flags = {} } = {}) {
/*
* Validate the code to check if we use the correct format when we write ttag translations.
*/
if (mode === 'lint-functions') {
debug(`[lint-functions] validation path: ${dir}`);
return scriptNode('linter.mjs', [dir || process.cwd(), flags.isVerbose ? '--verbose' : ''], 'inherit');
}
const doc = fs.readFileSync(path.resolve(process.cwd(), TEMPLATE_FILE));
const { translations } = gettextParser.po.parse(doc);
validateWithoutContext(translations);
validateVariables(translations);
}
module.exports = main;
| 7,344
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib/helpers/cli.js
|
const path = require('path');
const execa = require('execa');
const { debug } = require('./log')('proton-i18n');
const bash = (cli, args = [], stdio) => {
debug({ cli, args, stdio }, 'bash');
return execa(cli, args, { shell: '/bin/bash', stdio });
};
// 'inherit'
const script = (cli, args = [], stdio) => {
const cmd = path.resolve(__dirname, '..', '..', 'scripts', cli);
return bash(cmd, args, stdio);
};
const scriptNode = (cli, args = [], stdio) => {
const cmd = path.resolve(__dirname, '..', '..', 'scripts', cli);
return bash('node ' + cmd, args, stdio);
};
module.exports = { bash, script, scriptNode };
| 7,345
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib/helpers/file.js
|
const { promises: fs, constants: FS_CONSTANTS } = require('fs');
const path = require('path');
const { warn } = require('./log')('proton-i18n');
/**
* Check if a directory exists, else we create it
* @param {String} filePath Path to a file (or directory if isDir is true)
* @param {Boolean} isDir The path is not for a file but a hasDirectory
* @param {[type]} options.warningSpaces Remove spaces around the warning message
* @return {void}
*/
async function hasDirectory(filePath, isDir, { warningSpaces = true } = {}) {
const dir = isDir ? filePath : path.dirname(filePath);
try {
await fs.access(dir, FS_CONSTANTS.F_OK | FS_CONSTANTS.W_OK);
} catch (e) {
warn(`Cannot find/write the directory ${dir}, we're going to create it`, warningSpaces);
await fs.mkdir(dir);
}
}
module.exports = { hasDirectory };
| 7,346
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib/helpers/help.js
|
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
function render(name = 'help') {
const CLI_DIR = path.resolve(__dirname, '..', '..');
const file = fs.readFileSync(path.join(CLI_DIR, name), 'utf8');
const content = file.replace(/\[(\w+)\](<\w+>|\w+|--\w+\|-\w|\w+-\w+)\[\/\w+\]/g, (match, g1, g2) => {
return chalk[g1](g2);
});
console.log(content);
}
module.exports = render;
| 7,347
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib
|
petrpan-code/ProtonMail/WebClients/packages/i18n/lib/helpers/log.js
|
const chalk = require('chalk');
const { IS_VERBOSE } = process.env;
module.exports = (scope) => {
const warn = (msg, addSpaces = true) => {
addSpaces && console.log();
console.log(chalk.bgMagenta(chalk.white('[warning]')), msg);
addSpaces && console.log();
};
const info = (msg, addSpaces = true) => {
addSpaces && console.log();
console.log(chalk.bgGrey('[info]'), msg);
addSpaces && console.log();
};
const success = (msg, { time, space = false } = {}) => {
const txt = chalk.bold(' ✔ ');
const message = [chalk.bgGreen(chalk.black(`[${scope}]`)), txt, msg, time && ` (${time})`]
.filter(Boolean)
.join('');
space && console.log();
console.log(message);
};
const json = (data, output, noSpace) => {
// only output for a command
if (output) {
return console.log(JSON.stringify(data, null, 2));
}
!noSpace && console.log();
!noSpace && console.log(`[${scope}]`, JSON.stringify(data, null, 2));
noSpace && console.log(JSON.stringify(data, null, 2));
console.log();
};
const error = (e) => {
console.log(chalk.bgRed(chalk.bold(chalk.white('[error]'))), e.message);
// Better log for CLI commands, better than a JSON version of stdX
if (e.stdout || e.stderr) {
console.log();
console.log('------------------------ [Stdout + stderr] -----------------------');
console.log(e.stdout);
console.error(e.stderr);
process.exit(1);
}
if (IS_VERBOSE) {
console.error(e);
}
process.exit(1);
};
function debug(item, message = 'debug') {
if (!IS_VERBOSE) {
return;
}
if (item instanceof Error) {
console.log(`[${scope}]`, message);
error(item);
}
if (Array.isArray(item) || typeof item === 'object') {
console.log(`[${scope}]`, message);
return json(item, false, true);
}
console.log(`[${scope}] ${message} \n`, item);
}
return {
success,
json,
debug,
error,
info,
warn,
};
};
| 7,348
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n
|
petrpan-code/ProtonMail/WebClients/packages/i18n/scripts/extract.sh
|
#!/usr/bin/env bash
set -eo pipefail
##
# Extract all the files we need to parse to get the translations
# - react-components
# - proton-shared
# - app sources
#
# We remove as much files a possible so it's faster
getFileList() {
# Remove what we do not need to filter + it makes find more complex
rm -rf node_modules | true
rm -rf webpack:/*/webpack | true
rm -rf webpack:/*/locales | true
# can't use the iregex flag,
# it doesn't work on PopOS 20.04 (wtf) and on MacOS as the find utility
# is too old. -> can't even run find --version
find * \
-type f \
-name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx"
# -not -path does not work
}
getDistDirectory() {
# inside the CI we have the dist directory available
if [ -n "$CI_COMMIT_REF_NAME" ] && [ -s dist ]; then
return 0;
fi
if [ -s "dist" ]; then
echo "extract from dist bundle local"
return 0
fi
# Cache for the CI so we're faster
if [ -s 'webapp-bundle.tar.gz' ]; then
echo "we extract the bundle"
rm -rf dist || true
mkdir dist
tar xzf webapp-bundle.tar.gz -C dist
else
echo "we create the bundle"
yarn run build
fi
}
function main {
ls -lSha
pwd;
appName="$(jq -r .name package.json)"
if [ ! -d "/tmp/sourcemapper" ]; then
git clone \
--quiet \
--single-branch \
--depth 1 \
https://github.com/dhoko/sourcemapper.git "/tmp/sourcemapper";
else
echo "we have a cache for the sourcemapper"
fi;
getDistDirectory
# Extract all the code available inside the dist and only the one we built (post tree-shacking)
for file in $(find ./dist/ -type f -name "*.js.map"); do
echo "[Parsing] $file";
if [[ "$OSTYPE" = "darwin"* ]]; then
if [[ "$(uname -m)" == 'arm64' ]]; then
/tmp/sourcemapper/bin/isourcemapper-arm --input "$file" --output 'i18n-js' &
else
/tmp/sourcemapper/bin/isourcemapper --input "$file" --output 'i18n-js' &
fi
else
/tmp/sourcemapper/bin/sourcemapper --input "$file" --output 'i18n-js' &
fi
done;
wait;
# Extract on top of the extracted code from the bundle
# Use direct relative path instead of npx or dlx since it doesn't resolve to the installed dependencies
(
cd i18n-js;
echo "Running ttag extract"
# Output from ttag extract is full of babel errors, silence it
../../../node_modules/.bin/ttag extract $(getFileList) -o "../${1}" 2>&1;
echo "done"
)
# Remove useless path
if [[ "$OSTYPE" = "darwin"* ]]; then
if [[ "$(uname -m)" == 'arm64' ]]; then
sed -i 's|webpack:/||g;s| /src/app/| src/app/|g' "$1";
else
sed -i '' 's|webpack:/||g;s| /src/app/| src/app/|g' "$1";
fi
else
sed -i 's|webpack:/||g;s| /src/app/| src/app/|g' "$1";
fi
rm -rf "./i18n-js";
}
main "$1";
| 7,349
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n
|
petrpan-code/ProtonMail/WebClients/packages/i18n/scripts/linter.mjs
|
/*
* Usage node linter.mjs [arg]
* - arg can be a directory or a single file (default src)
*/
import { readFile } from 'fs/promises';
import { sync } from 'glob';
import path from 'path';
/**
* @typedef {string} FilePath
* @typedef {'format' | 'usage' | 'backticks' | 'plurals'} BrokenRuleType
* @typedef {{ file:FilePath, line:string, match:string, index:int, type: BrokenRuleType}} BrokenRule
* @typedef { Generator<FilePath, Any, BrokenRule>} BrokenRulesIterator
* @typedef { AsyncGenerator<FilePath, Any, BrokenRule>} AsyncBrokenRulesIterator
*/
/**
* Test a rule inside the code and see if we find lines matching it
* @param {RegExp} rule rule to test inside the whole content
* @param {string} content text file content
* @param {BrokenRuleType} type type of rule you filter
* @return {{ errors: BrokenRulesIterator, match: bool}}
*/
function testRule(rule, content, type) {
const matches = content.match(rule);
/**
* @param {FilePath}file to lint
* @yields {BrokenRule}
*/
function* errors(file) {
if (!matches?.length) {
return;
}
for (const [index, line] of content.split('\n').entries()) {
const done = new Set();
for (const match of matches) {
const hasNewLine = match.includes('\n');
// If multiline matches
const [, string] = match.split('\n');
const toMatch = hasNewLine ? string : match;
const id = `${line}:${index}${match}`;
if (!line.includes(toMatch) || done.has(id)) {
continue;
}
done.add(id);
yield {
file,
line,
match,
string,
index,
type,
};
}
}
}
return { match: matches?.length > 0, errors };
}
/**
* Iterate over all your source files and see if we can find broken translations
* @param {string} source source to iterate over (directory or a single file)
* @param {{isVerbose: bool}}
* @returns {AsyncBrokenRulesIterator}
*/
async function* errorIterator(source = 'src', options = { isVerbose: false }) {
const { ext } = path.parse(source);
const files = ext
? [source]
: sync(path.join(source, '**', '*.{js,jsx,ts,tsx}'), {
ignore: [path.join(source, 'node_modules', '**')],
});
for (const file of files) {
if (file.endsWith('.d.ts') || file.includes('tests')) {
continue;
}
if (file.includes('stories')) {
continue;
}
if (options.isVerbose) {
console.log('[lint]', file);
}
const content = await readFile(file, 'utf-8');
const errorsFormat = testRule(/c\(\x27.+\x27\)\.(t|c)\(/g, content, 'format');
if (errorsFormat.match) {
yield* errorsFormat.errors(file);
}
const errorsUsage = testRule(/c\(\x27.+\x27\)\.(c\x60|\x60)/g, content, 'usage');
if (errorsUsage.match) {
yield* errorsUsage.errors(file);
}
const errorsPlurals = testRule(
/c\(\x27.+\x27\)\.ngettext\(msgid(\x60|\().+(\x60|\)),\s(\x27|\x22)/g,
content,
'plurals'
);
if (errorsPlurals.match) {
yield* errorsPlurals.errors(file);
}
const errorsBackticks = testRule(/c\((\s+\x60|\x60).+(\x60|\x60\s+)\)/g, content, 'backticks');
if (errorsBackticks.match) {
yield* errorsBackticks.errors(file);
}
const errorsNewLines = testRule(/[\s|\)]\.jt\x60.+\w\s{2,}\w+/, content, 'newlines');
if (errorsNewLines.match) {
yield* errorsNewLines.errors(file);
}
const errorsNewLinesT = testRule(/[\s|\)]\.t\x60.+\w\s{2,}\w+/, content, 'newlines');
if (errorsNewLinesT.match) {
yield* errorsNewLinesT.errors(file);
}
const errorsNumbers = testRule(/[\s|\)]\.t\x60(\d+|\d+\s)*\x60/, content, 'numbers');
if (errorsNumbers.match) {
yield* errorsNumbers.errors(file);
}
}
}
/**
* @param {BrokenRule} error
* @returns {string} formatted error
*/
function formatErrors(error) {
if (error.type === 'format') {
return `🚨 [Error] ${error.file}:${error.index}
match: ${error.match}
line: ${error.line}
fix: You should not use - c(<context>).t(<string>) or c(<context>).c(<string>)
but c(<context>).t\`<string>\`
`;
}
if (error.type === 'usage') {
return `🚨 [Error] ${error.file}:${error.index}
match: ${error.match}
line: ${error.line}
fix: You should not use - c(<context>).c\`<string>\` or c(<context>).\`<string>\`
but c(<context>).t\`<string>\`
`;
}
if (error.type === 'backticks') {
return `🚨 [Error] ${error.file}:${error.index}
match: ${error.match}
line: ${error.line}
fix: You should not use backticks for the context definition. It is a static string
best to use c(\x27<context>\x27).t\`<string>\`
`;
}
if (error.type === 'plurals') {
return `🚨 [Error] ${error.file}:${error.index}
match: ${error.match}
line: ${error.line}
fix: Plural form is - ngettext(msgid\`<string single>\`, \`<string plural>\`, value)
`;
}
if (error.type === 'newlines') {
return `🚨 [Error] ${error.file}:${error.index}
match: ${error.match}
line: ${error.line}
fix: Unexpected newline inside the string.
`;
}
if (error.type === 'numbers') {
return `🚨 [Error] ${error.file}:${error.index}
match: ${error.match}
line: ${error.line}
fix: Do not translate a string without anything else than numbers and/or spaces.
`;
}
}
async function main() {
const [, , source] = process.argv;
const isVerbose = process.argv.includes('--verbose');
let total = 0;
for await (const error of errorIterator(source, { isVerbose })) {
total++;
console.log(formatErrors(error));
}
total && console.log(`Found ${total} error(s)`);
// If total => it means we have error, exit with code 1
process.exit(+!!total);
}
main();
| 7,350
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/.env
|
I18N_JSON_DIR="test/compile"
I18N_EXTRACT_DIR="test/po"
| 7,351
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/test-linter.sh
|
#!/usr/bin/env bash
set -eo pipefail
readonly TEST_FILES='test/input/js';
function main {
local hasError=false;
for file in "$TEST_FILES"/*; do
echo "[~] validate ${file}";
local expectedFile="$(sed 's/\.js$//; s/input/output/' <<< "$file")";
local output="$(node scripts/linter.mjs "$file")";
local expectedOutput="$(cat "$expectedFile")";
if [ "$expectedOutput" != "$output" ]; then
hasError=true;
echo -e " 💥 \e[1m\e[31mError\e[39m\e[0m wrong output for ${file}"
echo -e "\e[4m🤖 Output\e[0m:"
echo "$(echo "$output")";
echo
echo -e "\e[4m🤖 Expected\e[0m:"
echo "$expectedOutput";
echo
echo '-----------------[DIFF]-----------------------'
echo
diff -rupP <(echo "$output") <(echo "$expectedOutput")
echo
echo '-----------------[/DIFF]-----------------------'
exit
else
echo -e "\e[32m ✔ lint translations for ${file}\e[0m";
fi;
done
if "$hasError"; then
return 1
fi
}
main
| 7,352
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/test-validator.sh
|
#!/usr/bin/env bash
set -eo pipefail
readonly TEST_FILES='test/input/po';
function main {
# $ for file in test/po/*; do
#
# I18N_TEMPLATE_FILE="$file" node index validate > "test/output/po/$(basename "$file")";
#
# done;
local hasError=false;
for file in "$TEST_FILES"/*; do
echo "[~] validate ${file}";
local expectedFile="$(sed 's/input/output/' <<< "$file")";
local output="$(I18N_TEMPLATE_FILE="$file" node index validate)";
local expectedOutput="$(cat "$expectedFile")";
if [ "$expectedOutput" != "$output" ]; then
hasError=true;
echo -e " 💥 \e[1m\e[31mError\e[39m\e[0m wrong output for ${file}"
echo -e "\e[4m🤖 Output\e[0m:"
echo "$(echo "$output")";
echo
echo -e "\e[4m🤖 Expected\e[0m:"
echo "$expectedOutput";
echo
echo '-----------------[DIFF]-----------------------'
echo
diff -rupP <(echo "$output") <(echo "$expectedOutput")
echo
echo '-----------------[/DIFF]-----------------------'
exit
else
echo -e "\e[32m ✔ lint translations for ${file}\e[0m";
fi;
done
if "$hasError"; then
return 1
fi
}
main
| 7,353
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input/js/broken.js
|
c('Action').t('Salut')
c('Action').c('Robert')
c('Action').c('jeanne')
c('Action').t('Monique')
c('Action').`OUPS`
c('Action').`OUPS 2`
c('Action').c`Nope monique`
c('Action').c`Nope monique 2`
c('Action').ngettext(msgid`Day`, 'Days', modifiedValue)
c('Action').ngettext(msgid`Miinute`, "Miinutes", modifiedValue)
c('Action').ngettext(msgid('Miinute'), "Miinutes", modifiedValue)
mailpro2022: {
label: c('new_plans_mailpro2022_team_management_session_management_label')
.t`User session management`,
tooltip: c(
`new_plans_mailpro2022_team_management_session_management_tooltip`
).t`Force sign-out of user sessions when user credentials are believed to be compromised.`,
icon: <DynamicHeroIcon className="w-5 h-5" icon="CheckIcon" />,
},
| 7,354
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input/js/valid.js
|
c('Action').t`Ok monique`;
c('Action').t`Ok monique 2`;
c('Action').ngettext(msgid`Day`, `Days`, modifiedValue);
c('Action').ngettext(msgid`Minute`, `Minutes`, modifiedValue);
| 7,355
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input/po/es.po
|
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Generator: crowdin.com\n"
"X-Crowdin-Project: protonvpn\n"
"X-Crowdin-Language: es-ES\n"
"X-Crowdin-File: ProtonVPN Settings Application.pot\n"
"Project-Id-Version: protonvpn\n"
"Last-Translator: PMtranslator\n"
"Language-Team: Spanish\n"
"Language: es_ES\n"
"PO-Revision-Date: 2019-09-03 12:33\n"
#: src/app/components/layout/PrivateLayout.js:14
msgctxt "Link"
msgid "Dashboard"
msgstr "Panel de control"
| 7,356
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input/po/fr.po
|
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Generator: crowdin.com\n"
"X-Crowdin-Project: protonvpn\n"
"X-Crowdin-Language: fr-FR\n"
"X-Crowdin-File: ProtonVPN Settings Application.pot\n"
"Project-Id-Version: protonvpn\n"
"Last-Translator: PMtranslator\n"
"Language-Team: French\n"
"Language: fr_FR\n"
"PO-Revision-Date: 2019-09-03 12:33\n"
#: src/app/components/layout/PrivateLayout.js:14
msgctxt "Link"
msgid "Dashboard"
msgstr "Panel de control"
| 7,357
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input/po/template_empty_context.pot
|
msgid ""
msgstr ""
"Content-Type: text/plain; charset=utf-8\n"
"Plural-Forms: nplurals=2; plural=(n!=1);\n"
#: node_modules/proton-shared/lib/contacts/decrypt.ts:95
msgctxt "Error"
msgid "Missing signature"
msgstr ""
#: node_modules/proton-shared/lib/contacts/decrypt.ts:80
msgctxt ""
msgid "Contact signature not verified"
msgstr ""
#: node_modules/react-components/containers/contacts/modals/ContactGroupModal.tsx:187
msgctxt "Info"
msgid "1 Member"
msgid_plural "${ model.contactEmails.length } Members"
msgstr[0] ""
msgstr[1] ""
#: node_modules/react-components/containers/contacts/ContactGroupDropdown.tsx:149
msgctxt ""
msgid "Contact group apply"
msgid_plural "Contact groups apply"
msgstr[0] ""
msgstr[1] ""
| 7,358
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input/po/template_invalid_variables.pot
|
msgid ""
msgstr ""
"Content-Type: text/plain; charset=utf-8\n"
"Plural-Forms: nplurals=2; plural=(n!=1);\n"
#: node_modules/proton-shared/lib/contacts/decrypt.ts:67
#: node_modules/proton-shared/lib/contacts/decrypt.ts:95
msgctxt "Error"
msgid "Missing signature"
msgstr ""
#: node_modules/react-components/containers/contacts/modals/ContactGroupModal.tsx:187
msgctxt "Info"
msgid "1 Member"
msgid_plural "${ model.contactEmails.length } Members"
msgstr[0] ""
msgstr[1] ""
#: node_modules/react-components/containers/contacts/modals/ContactDeleteModal.tsx:51
#, javascript-format
msgctxt "Title"
msgid "Delete ${ name }"
msgid_plural "Delete ${ count } contacts"
msgstr[0] ""
msgstr[1] ""
#: src/app/components/ContactPlaceholder.js:159
msgctxt "Action"
msgid "Deselect"
msgid_plural "Deselect all"
msgstr[0] ""
msgstr[1] ""
| 7,359
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input/po/template_ok.pot
|
msgid ""
msgstr ""
"Content-Type: text/plain; charset=utf-8\n"
"Plural-Forms: nplurals=2; plural=(n!=1);\n"
#: node_modules/proton-shared/lib/contacts/decrypt.ts:80
msgctxt "Error"
msgid "Contact signature not verified"
msgstr ""
#: node_modules/react-components/containers/contacts/ContactGroupDropdown.tsx:149
msgctxt "Info"
msgid "Contact group apply"
msgid_plural "Contact groups apply"
msgstr[0] ""
msgstr[1] ""
#: src/app/components/ContactGroupsTable.js:109
#, javascript-format
msgctxt "Info"
msgid "${ countEmailAddresses } email address"
msgid_plural "${ countEmailAddresses } email addresses"
msgstr[0] ""
msgstr[1] ""
| 7,360
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input/po/ua.po
|
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Generator: crowdin.com\n"
"X-Crowdin-Project: protonvpn\n"
"X-Crowdin-Language: uk\n"
"X-Crowdin-File: ProtonVPN Settings Application.pot\n"
"Project-Id-Version: protonvpn\n"
"Last-Translator: PMtranslator\n"
"Language-Team: Ukrainian\n"
"Language: uk_UA\n"
"PO-Revision-Date: 2019-09-03 12:33\n"
#: src/app/components/layout/PrivateLayout.js:14
msgctxt "Link"
msgid "Dashboard"
msgstr "Panel de control"
| 7,361
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/input/po/zh-TW.po
|
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Generator: crowdin.com\n"
"X-Crowdin-Project: protonvpn\n"
"X-Crowdin-Language: zh-TW\n"
"X-Crowdin-File: ProtonVPN Settings Application.pot\n"
"Project-Id-Version: protonvpn\n"
"Last-Translator: PMtranslator\n"
"Language-Team: Chinese Traditional\n"
"Language: zh_TW\n"
"PO-Revision-Date: 2019-09-03 12:33\n"
#: src/app/components/layout/PrivateLayout.js:14
msgctxt "Link"
msgid "Dashboard"
msgstr "Panel de control"
| 7,362
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output/js/broken
|
🚨 [Error] test/input/js/broken.js:0
match: c('Action').t(
line: c('Action').t('Salut')
fix: You should not use - c(<context>).t(<string>) or c(<context>).c(<string>)
but c(<context>).t`<string>`
🚨 [Error] test/input/js/broken.js:1
match: c('Action').c(
line: c('Action').c('Robert')
fix: You should not use - c(<context>).t(<string>) or c(<context>).c(<string>)
but c(<context>).t`<string>`
🚨 [Error] test/input/js/broken.js:2
match: c('Action').c(
line: c('Action').c('jeanne')
fix: You should not use - c(<context>).t(<string>) or c(<context>).c(<string>)
but c(<context>).t`<string>`
🚨 [Error] test/input/js/broken.js:3
match: c('Action').t(
line: c('Action').t('Monique')
fix: You should not use - c(<context>).t(<string>) or c(<context>).c(<string>)
but c(<context>).t`<string>`
🚨 [Error] test/input/js/broken.js:4
match: c('Action').`
line: c('Action').`OUPS`
fix: You should not use - c(<context>).c`<string>` or c(<context>).`<string>`
but c(<context>).t`<string>`
🚨 [Error] test/input/js/broken.js:5
match: c('Action').`
line: c('Action').`OUPS 2`
fix: You should not use - c(<context>).c`<string>` or c(<context>).`<string>`
but c(<context>).t`<string>`
🚨 [Error] test/input/js/broken.js:6
match: c('Action').c`
line: c('Action').c`Nope monique`
fix: You should not use - c(<context>).c`<string>` or c(<context>).`<string>`
but c(<context>).t`<string>`
🚨 [Error] test/input/js/broken.js:7
match: c('Action').c`
line: c('Action').c`Nope monique 2`
fix: You should not use - c(<context>).c`<string>` or c(<context>).`<string>`
but c(<context>).t`<string>`
🚨 [Error] test/input/js/broken.js:8
match: c('Action').ngettext(msgid`Day`, '
line: c('Action').ngettext(msgid`Day`, 'Days', modifiedValue)
fix: Plural form is - ngettext(msgid`<string single>`, `<string plural>`, value)
🚨 [Error] test/input/js/broken.js:9
match: c('Action').ngettext(msgid`Miinute`, "
line: c('Action').ngettext(msgid`Miinute`, "Miinutes", modifiedValue)
fix: Plural form is - ngettext(msgid`<string single>`, `<string plural>`, value)
🚨 [Error] test/input/js/broken.js:10
match: c('Action').ngettext(msgid('Miinute'), "
line: c('Action').ngettext(msgid('Miinute'), "Miinutes", modifiedValue)
fix: Plural form is - ngettext(msgid`<string single>`, `<string plural>`, value)
🚨 [Error] test/input/js/broken.js:16
match: c(
`new_plans_mailpro2022_team_management_session_management_tooltip`
)
line: `new_plans_mailpro2022_team_management_session_management_tooltip`
fix: You should not use backticks for the context definition. It is a static string
best to use c('<context>').t`<string>`
Found 12 error(s)
| 7,363
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output/po/es.po
|
[proton-i18n] ✔ All translations have a context, good job !
[proton-i18n] ✔ All translations have matching variables
| 7,364
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output/po/fr.po
|
[proton-i18n] ✔ All translations have a context, good job !
[proton-i18n] ✔ All translations have matching variables
| 7,365
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output/po/template_empty_context.pot
|
{
"msgid": "Contact group apply",
"comments": {
"reference": "node_modules/react-components/containers/contacts/ContactGroupDropdown.tsx:149"
},
"msgid_plural": "Contact groups apply",
"msgstr": [
"",
""
]
}
{
"msgid": "Contact signature not verified",
"comments": {
"reference": "node_modules/proton-shared/lib/contacts/decrypt.ts:80"
},
"msgstr": [
""
]
}
[error] 2 translations without context !
| 7,366
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output/po/template_invalid_variables.pot
|
[proton-i18n] ✔ All translations have a context, good job !
{
"msgid": "1 Member",
"msgctxt": "Info",
"comments": {
"reference": "node_modules/react-components/containers/contacts/modals/ContactGroupModal.tsx:187"
},
"msgid_plural": "${ model.contactEmails.length } Members",
"msgstr": [
"",
""
]
}
{
"msgid": "Delete ${ name }",
"msgctxt": "Title",
"comments": {
"reference": "node_modules/react-components/containers/contacts/modals/ContactDeleteModal.tsx:51",
"flag": "javascript-format"
},
"msgid_plural": "Delete ${ count } contacts",
"msgstr": [
"",
""
]
}
[error] 2 translations without matching variables !
| 7,367
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output/po/template_ok.pot
|
[proton-i18n] ✔ All translations have a context, good job !
[proton-i18n] ✔ All translations have matching variables
| 7,368
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output/po/ua.po
|
[proton-i18n] ✔ All translations have a context, good job !
[proton-i18n] ✔ All translations have matching variables
| 7,369
|
0
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output
|
petrpan-code/ProtonMail/WebClients/packages/i18n/test/output/po/zh-TW.po
|
[proton-i18n] ✔ All translations have a context, good job !
[proton-i18n] ✔ All translations have matching variables
| 7,370
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/.eslintignore
|
test/**/*data.js
| 7,371
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/.eslintrc.js
|
module.exports = {
extends: ['@proton/eslint-config-proton'],
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: __dirname,
project: './tsconfig.json',
},
ignorePatterns: ['.eslintrc.js'],
};
| 7,372
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/.prettierignore
|
test
| 7,373
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/LICENSE
|
The MIT License (MIT)
Copyright (c) 2019 by Proton Technologies A.G. (Switzerland) Email: contact@protonmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
| 7,374
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/package.json
|
{
"name": "@proton/key-transparency",
"description": "ProtonMail Key Transparency Web Client",
"license": "MIT",
"author": "ProtonMail",
"main": "lib/index.ts",
"scripts": {
"check-types": "tsc",
"i18n:validate": "proton-i18n validate lint-functions",
"i18n:validate:context": "proton-i18n extract && proton-i18n validate",
"lint": "eslint lib test --ext .js,.ts,tsx --quiet --cache",
"pretty": "prettier --write $(find lib test -type f -name '*.js' -o -name '*.ts' -o -name '*.tsx')",
"test": "NODE_ENV=test karma start test/karma.conf.js"
},
"dependencies": {
"@noble/ed25519": "1.7.3",
"@proton/cross-storage": "workspace:packages/cross-storage",
"@proton/crypto": "workspace:packages/crypto",
"@proton/shared": "workspace:packages/shared",
"@types/pkijs": "0.0.14",
"pkijs": "^3.0.15"
},
"devDependencies": {
"@proton/eslint-config-proton": "workspace:packages/eslint-config-proton",
"@proton/i18n": "workspace:packages/i18n",
"@types/jasmine": "^5.1.3",
"eslint": "^8.54.0",
"jasmine": "^5.1.0",
"jasmine-core": "^5.1.1",
"karma": "^6.4.2",
"karma-chrome-launcher": "^3.2.0",
"karma-jasmine": "^5.1.0",
"karma-webpack": "^5.0.0",
"playwright": "^1.40.0",
"ts-loader": "^9.5.1",
"typescript": "^5.3.2",
"webpack": "^5.89.0"
}
}
| 7,375
|
0
|
petrpan-code/ProtonMail/WebClients/packages
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/tsconfig.json
|
{
"extends": "../../tsconfig.base.json"
}
| 7,376
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/index.ts
|
export * from './interfaces';
export * from './storage';
export * from './constants';
export * from './helpers';
export * from './verification';
| 7,377
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/interfaces.ts
|
import { FetchedSignedKeyList } from '@proton/shared/lib/interfaces';
import { KT_CERTIFICATE_ISSUER, KT_DOMAINS } from './constants';
import { KeyTransparencyError } from './helpers';
export enum KTPROOF_TYPE {
ABSENCE,
EXISTENCE,
OBSOLESCENCE,
}
export interface Proof {
Neighbors: (string | null)[];
Verifier: string;
Type: KTPROOF_TYPE;
ObsolescenceToken: string | null;
}
export interface KTBlobContent {
creationTimestamp: number;
expectedMinEpochID: number;
email: string;
data: string;
revision: number;
isCatchall?: boolean;
}
export interface KTBlobValuesWithInfo {
userID: string;
addressID: string;
ktBlobsContent: KTBlobContent[];
}
export interface VerifiedEpoch {
EpochID: number;
Revision: number;
SKLCreationTime: number;
}
export interface AuditData {
initialEpoch: VerifiedEpoch;
newSKLs: FetchedSignedKeyList[];
}
export enum KT_STATUS {
KT_FAILED,
KT_PASSED,
KT_MINEPOCHID_NULL,
}
export interface Epoch {
EpochID: number;
TreeHash: string;
ChainHash: string;
PrevChainHash: string;
Certificate: string;
CertificateIssuer: KT_CERTIFICATE_ISSUER;
ClaimedTime: number;
Domain: KT_DOMAINS;
CertificateTime: number;
}
export enum AddressAuditStatus {
Success,
Failure,
Warning,
}
export enum AddressAuditWarningReason {
UnverifiableHistory,
AddressWithNoKeys,
}
export interface AddressAuditWarningDetails {
reason: AddressAuditWarningReason;
addressWasDisabled?: boolean;
sklVerificationFailed?: boolean;
}
export interface AddressAuditResult {
email: string;
status: AddressAuditStatus;
warningDetails?: AddressAuditWarningDetails;
error?: KeyTransparencyError;
}
export interface LocalStorageAuditResult {
email: string;
success: boolean;
error?: KeyTransparencyError;
primaryKeyFingerprint?: string;
}
export interface SelfAuditResult {
auditTime: number;
nextAuditTime: number;
addressAuditResults: AddressAuditResult[];
localStorageAuditResultsOwnAddress: LocalStorageAuditResult[];
localStorageAuditResultsOtherAddress: LocalStorageAuditResult[];
error?: SelfAuditError;
}
export interface SelfAuditError {
failedTrials: number;
tooManyRetries: boolean;
}
| 7,378
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/constants/certificates.ts
|
import { KT_CERTIFICATE_ISSUER } from './constants';
const letsEncryptCerts: string[] = [
// ISRGRootX1:
'-----BEGIN CERTIFICATE-----\nMIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\nTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\ncmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\nWhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\nZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\nMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\nh77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\nA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\nT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\nB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\nB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\nKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\nOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\njh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\nqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\nrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\nHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\nhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\nubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\nNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\nORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\nTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\njNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\noyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\nmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\nemyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n-----END CERTIFICATE-----',
// ISRGRootX1_crossSigned:
'-----BEGIN CERTIFICATE-----\nMIIFYDCCBEigAwIBAgIQQAF3ITfU6UK47naqPGQKtzANBgkqhkiG9w0BAQsFADA/\nMSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\nDkRTVCBSb290IENBIFgzMB4XDTIxMDEyMDE5MTQwM1oXDTI0MDkzMDE4MTQwM1ow\nTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\ncmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwggIiMA0GCSqGSIb3DQEB\nAQUAA4ICDwAwggIKAoICAQCt6CRz9BQ385ueK1coHIe+3LffOJCMbjzmV6B493XC\nov71am72AE8o295ohmxEk7axY/0UEmu/H9LqMZshftEzPLpI9d1537O4/xLxIZpL\nwYqGcWlKZmZsj348cL+tKSIG8+TA5oCu4kuPt5l+lAOf00eXfJlII1PoOK5PCm+D\nLtFJV4yAdLbaL9A4jXsDcCEbdfIwPPqPrt3aY6vrFk/CjhFLfs8L6P+1dy70sntK\n4EwSJQxwjQMpoOFTJOwT2e4ZvxCzSow/iaNhUd6shweU9GNx7C7ib1uYgeGJXDR5\nbHbvO5BieebbpJovJsXQEOEO3tkQjhb7t/eo98flAgeYjzYIlefiN5YNNnWe+w5y\nsR2bvAP5SQXYgd0FtCrWQemsAXaVCg/Y39W9Eh81LygXbNKYwagJZHduRze6zqxZ\nXmidf3LWicUGQSk+WT7dJvUkyRGnWqNMQB9GoZm1pzpRboY7nn1ypxIFeFntPlF4\nFQsDj43QLwWyPntKHEtzBRL8xurgUBN8Q5N0s8p0544fAQjQMNRbcTa0B7rBMDBc\nSLeCO5imfWCKoqMpgsy6vYMEG6KDA0Gh1gXxG8K28Kh8hjtGqEgqiNx2mna/H2ql\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-----',
// ISRGRootX2:
'-----BEGIN CERTIFICATE-----\nMIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\nCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\nR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\nMDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\nZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\nEAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\nItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\nAQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\nzj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\ntL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n/q4AaOeMSQ+2b1tbFfLn\n-----END CERTIFICATE-----',
// ISRGRootX2_crossSigned
'-----BEGIN CERTIFICATE-----\nMIIEYDCCAkigAwIBAgIQB55JKIY3b9QISMI/xjHkYzANBgkqhkiG9w0BAQsFADBP\nMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFy\nY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTAeFw0yMDA5MDQwMDAwMDBa\nFw0yNTA5MTUxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5l\ndCBTZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgy\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0H\nttwW+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7\nAlF9ItgKbppbd9/w+kHsOdx1ymgHDB/qo4HlMIHiMA4GA1UdDwEB/wQEAwIBBjAP\nBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR8Qpau3ktIO/qS+J6Mz22LqXI3lTAf\nBgNVHSMEGDAWgBR5tFnme7bl5AFzgAiIyBpY9umbbjAyBggrBgEFBQcBAQQmMCQw\nIgYIKwYBBQUHMAKGFmh0dHA6Ly94MS5pLmxlbmNyLm9yZy8wJwYDVR0fBCAwHjAc\noBqgGIYWaHR0cDovL3gxLmMubGVuY3Iub3JnLzAiBgNVHSAEGzAZMAgGBmeBDAEC\nATANBgsrBgEEAYLfEwEBATANBgkqhkiG9w0BAQsFAAOCAgEAG38lK5B6CHYAdxjh\nwy6KNkxBfr8XS+Mw11sMfpyWmG97sGjAJETM4vL80erb0p8B+RdNDJ1V/aWtbdIv\nP0tywC6uc8clFlfCPhWt4DHRCoSEbGJ4QjEiRhrtekC/lxaBRHfKbHtdIVwH8hGR\nIb/hL8Lvbv0FIOS093nzLbs3KvDGsaysUfUfs1oeZs5YBxg4f3GpPIO617yCnpp2\nD56wKf3L84kHSBv+q5MuFCENX6+Ot1SrXQ7UW0xx0JLqPaM2m3wf4DtVudhTU8yD\nZrtK3IEGABiL9LPXSLETQbnEtp7PLHeOQiALgH6fxatI27xvBI1sRikCDXCKHfES\nc7ZGJEKeKhcY46zHmMJyzG0tdm3dLCsmlqXPIQgb5dovy++fc5Ou+DZfR4+XKM6r\n4pgmmIv97igyIintTJUJxCD6B+GGLET2gUfA5GIy7R3YPEiIlsNekbave1mk7uOG\nnMeIWMooKmZVm4WAuR3YQCvJHBM8qevemcIWQPb1pK4qJWxSuscETLQyu/w4XKAM\nYXtX7HdOUM+vBqIPN4zhDtLTLxq9nHE+zOH40aijvQT2GcD5hq/1DhqqlWvvykdx\nS2McTZbbVSMKnQ+BdaDmQPVkRgNuzvpqfQbspDQGdNpT2Lm4xiN9qfgqLaSCpi4t\nEcrmzTFYeYXmchynn9NM0GbQp7s=\n-----END CERTIFICATE-----',
];
const zeroSSLCerts: string[] = [
// USERTrust:
'-----BEGIN CERTIFICATE-----\nMIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB\niDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\ncnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\nBAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw\nMjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV\nBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU\naGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy\ndGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK\nAoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B\n3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY\ntJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/\nFp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2\nVN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT\n79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6\nc0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT\nYo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l\nc6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee\nUB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE\nHg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd\nBgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G\nA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF\nUp/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO\nVWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3\nATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs\n8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR\niQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze\nSf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ\nXHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/\nqS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB\nVXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB\nL6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG\njjxDah2nGN59PRbxYvnKkKj9\n-----END CERTIFICATE-----',
// USERTrust_crossSigned:
'-----BEGIN CERTIFICATE-----\nMIIFgTCCBGmgAwIBAgIQOXJEOvkit1HX02wQ3TE1lTANBgkqhkiG9w0BAQwFADB7\nMQswCQYDVQQGEwJHQjEbMBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYD\nVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UE\nAwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTE5MDMxMjAwMDAwMFoXDTI4\nMTIzMTIzNTk1OVowgYgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpOZXcgSmVyc2V5\nMRQwEgYDVQQHEwtKZXJzZXkgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBO\nZXR3b3JrMS4wLAYDVQQDEyVVU0VSVHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0\naG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAgBJlFzYOw9sI\ns9CsVw127c0n00ytUINh4qogTQktZAnczomfzD2p7PbPwdzx07HWezcoEStH2jnG\nvDoZtF+mvX2do2NCtnbyqTsrkfjib9DsFiCQCT7i6HTJGLSR1GJk23+jBvGIGGqQ\nIjy8/hPwhxR79uQfjtTkUcYRZ0YIUcuGFFQ/vDP+fmyc/xadGL1RjjWmp2bIcmfb\nIWax1Jt4A8BQOujM8Ny8nkz+rwWWNR9XWrf/zvk9tyy29lTdyOcSOk2uTIq3XJq0\ntyA9yn8iNK5+O2hmAUTnAU5GU5szYPeUvlM3kHND8zLDU+/bqv50TmnHa4xgk97E\nxwzf4TKuzJM7UXiVZ4vuPVb+DNBpDxsP8yUmazNt925H+nND5X4OpWaxKXwyhGNV\nicQNwZNUMBkTrNN9N6frXTpsNVzbQdcS2qlJC9/YgIoJk2KOtWbPJYjNhLixP6Q5\nD9kCnusSTJV882sFqV4Wg8y4Z+LoE53MW4LTTLPtW//e5XOsIzstAL81VXQJSdhJ\nWBp/kjbmUZIO8yZ9HE0XvMnsQybQv0FfQKlERPSZ51eHnlAfV1SoPv10Yy+xUGUJ\n5lhCLkMaTLTwJUdZ+gQek9QmRkpQgbLevni3/GcV4clXhB4PY9bpYrrWX1Uu6lzG\nKAgEJTm4Diup8kyXHAc/DVL17e8vgg8CAwEAAaOB8jCB7zAfBgNVHSMEGDAWgBSg\nEQojPpbxB+zirynvgqV/0DCktDAdBgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rID\nZsswDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wEQYDVR0gBAowCDAG\nBgRVHSAAMEMGA1UdHwQ8MDowOKA2oDSGMmh0dHA6Ly9jcmwuY29tb2RvY2EuY29t\nL0FBQUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDQGCCsGAQUFBwEBBCgwJjAkBggr\nBgEFBQcwAYYYaHR0cDovL29jc3AuY29tb2RvY2EuY29tMA0GCSqGSIb3DQEBDAUA\nA4IBAQAYh1HcdCE9nIrgJ7cz0C7M7PDmy14R3iJvm3WOnnL+5Nb+qh+cli3vA0p+\nrvSNb3I8QzvAP+u431yqqcau8vzY7qN7Q/aGNnwU4M309z/+3ri0ivCRlv79Q2R+\n/czSAaF9ffgZGclCKxO/WIu6pKJmBHaIkU4MiRTOok3JMrO66BQavHHxW/BBC5gA\nCiIDEOUMsfnNkjcZ7Tvx5Dq2+UUTJnWvu6rvP3t3O9LEApE9GQDTF1w52z97GA1F\nzZOFli9d31kWTz9RvdVFGD/tSo7oBmF0Ixa1DVBzJ0RHfxBdiSprhTEUxOipakyA\nvGp4z7h/jnZymQyd/teRCBaho1+V\n-----END CERTIFICATE-----',
];
export const rootCertificates: Map<KT_CERTIFICATE_ISSUER, string[]> = new Map([
[KT_CERTIFICATE_ISSUER.LETSENCRYPT, letsEncryptCerts],
[KT_CERTIFICATE_ISSUER.ZEROSSL, zeroSSLCerts],
]);
export const ctLogs = {
version: '19.5',
log_list_timestamp: '2023-02-08T12:56:23Z',
operators: [
{
name: 'Google',
email: ['google-ct-logs@googlegroups.com'],
logs: [
{
description: "Google 'Argon2023' log",
log_id: '6D7Q2j71BjUy51covIlryQPTy9ERa+zraeF3fW0GvW4=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0JCPZFJOQqyEti5M8j13ALN3CAVHqkVM4yyOcKWCu2yye5yYeqDpEXYoALIgtM3TmHtNlifmt+4iatGwLpF3eA==',
url: 'https://ct.googleapis.com/logs/argon2023/',
mmd: 86400,
state: {
usable: {
timestamp: '2019-12-17T18:38:01Z',
},
},
temporal_interval: {
start_inclusive: '2023-01-01T00:00:00Z',
end_exclusive: '2024-01-01T00:00:00Z',
},
},
{
description: "Google 'Argon2024' log",
log_id: '7s3QZNXbGs7FXLedtM0TojKHRny87N7DUUhZRnEftZs=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHblsqctplMVc5ramA7vSuNxUQxcomQwGAVAdnWTAWUYr3MgDHQW0LagJ95lB7QT75Ve6JgT2EVLOFGU7L3YrwA==',
url: 'https://ct.googleapis.com/logs/us1/argon2024/',
mmd: 86400,
state: {
usable: {
timestamp: '2022-11-01T18:54:00Z',
},
},
temporal_interval: {
start_inclusive: '2024-01-01T00:00:00Z',
end_exclusive: '2025-01-01T00:00:00Z',
},
},
{
description: "Google 'Xenon2023' log",
log_id: 'rfe++nz/EMiLnT2cHj4YarRnKV3PsQwkyoWGNOvcgoo=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEchY+C+/vzj5g3ZXLY3q5qY1Kb2zcYYCmRV4vg6yU84WI0KV00HuO/8XuQqLwLZPjwtCymeLhQunSxgAnaXSuzg==',
url: 'https://ct.googleapis.com/logs/xenon2023/',
mmd: 86400,
state: {
usable: {
timestamp: '2019-12-17T18:38:01Z',
},
},
temporal_interval: {
start_inclusive: '2023-01-01T00:00:00Z',
end_exclusive: '2024-01-01T00:00:00Z',
},
},
{
description: "Google 'Xenon2024' log",
log_id: 'dv+IPwq2+5VRwmHM9Ye6NLSkzbsp3GhCCp/mZ0xaOnQ=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuWDgNB415GUAk0+QCb1a7ETdjA/O7RE+KllGmjG2x5n33O89zY+GwjWlPtwpurvyVOKoDIMIUQbeIW02UI44TQ==',
url: 'https://ct.googleapis.com/logs/eu1/xenon2024/',
mmd: 86400,
state: {
usable: {
timestamp: '2022-11-01T18:54:00Z',
},
},
temporal_interval: {
start_inclusive: '2024-01-01T00:00:00Z',
end_exclusive: '2025-01-01T00:00:00Z',
},
},
{
description: "Google 'Icarus' log",
log_id: 'KTxRllTIOWW6qlD8WAfUt2+/WHopctykwwz05UVH9Hg=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAETtK8v7MICve56qTHHDhhBOuV4IlUaESxZryCfk9QbG9co/CqPvTsgPDbCpp6oFtyAHwlDhnvr7JijXRD9Cb2FA==',
url: 'https://ct.googleapis.com/icarus/',
mmd: 86400,
state: {
retired: {
timestamp: '2022-09-15T00:00:00Z',
},
},
},
{
description: "Google 'Pilot' log",
log_id: 'pLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BA=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfahLEimAoz2t01p3uMziiLOl/fHTDM0YDOhBRuiBARsV4UvxG2LdNgoIGLrtCzWE0J5APC2em4JlvR8EEEFMoA==',
url: 'https://ct.googleapis.com/pilot/',
mmd: 86400,
state: {
retired: {
timestamp: '2022-09-15T00:00:00Z',
},
},
},
{
description: "Google 'Rocketeer' log",
log_id: '7ku9t3XOYLrhQmkfq+GeZqMPfl+wctiDAMR7iXqo/cs=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIFsYyDzBi7MxCAC/oJBXK7dHjG+1aLCOkHjpoHPqTyghLpzA9BYbqvnV16mAw04vUjyYASVGJCUoI3ctBcJAeg==',
url: 'https://ct.googleapis.com/rocketeer/',
mmd: 86400,
state: {
retired: {
timestamp: '2022-09-15T00:00:00Z',
},
},
},
{
description: "Google 'Skydiver' log",
log_id: 'u9nfvB+KcbWTlCOXqpJ7RzhXlQqrUugakJZkNo4e0YU=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEmyGDvYXsRJsNyXSrYc9DjHsIa2xzb4UR7ZxVoV6mrc9iZB7xjI6+NrOiwH+P/xxkRmOFG6Jel20q37hTh58rA==',
url: 'https://ct.googleapis.com/skydiver/',
mmd: 86400,
state: {
retired: {
timestamp: '2022-09-15T00:00:00Z',
},
},
},
],
},
{
name: 'Cloudflare',
email: [
'ct-logs@cloudflare.com',
'brendan@cloudflare.com',
'nick@cloudflare.com',
'pat@cloudflare.com',
'zi@cloudflare.com',
'ivan@cloudflare.com',
],
logs: [
{
description: "Cloudflare 'Nimbus2023' Log",
log_id: 'ejKMVNi3LbYg6jjgUh7phBZwMhOFTTvSK8E6V6NS61I=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEi/8tkhjLRp0SXrlZdTzNkTd6HqmcmXiDJz3fAdWLgOhjmv4mohvRhwXul9bgW0ODgRwC9UGAgH/vpGHPvIS1qA==',
url: 'https://ct.cloudflare.com/logs/nimbus2023/',
mmd: 86400,
state: {
usable: {
timestamp: '2019-10-31T19:22:00Z',
},
},
temporal_interval: {
start_inclusive: '2023-01-01T00:00:00Z',
end_exclusive: '2024-01-01T00:00:00Z',
},
},
{
description: "Cloudflare 'Nimbus2024' Log",
log_id: '2ra/az+1tiKfm8K7XGvocJFxbLtRhIU0vaQ9MEjX+6s=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEd7Gbe4/mizX+OpIpLayKjVGKJfyTttegiyk3cR0zyswz6ii5H+Ksw6ld3Ze+9p6UJd02gdHrXSnDK0TxW8oVSA==',
url: 'https://ct.cloudflare.com/logs/nimbus2024/',
mmd: 86400,
state: {
usable: {
timestamp: '2022-11-30T17:00:00Z',
},
},
temporal_interval: {
start_inclusive: '2024-01-01T00:00:00Z',
end_exclusive: '2025-01-01T00:00:00Z',
},
},
],
},
{
name: 'DigiCert',
email: ['ctops@digicert.com'],
logs: [
{
description: 'DigiCert Log Server',
log_id: 'VhQGmi/XwuzT9eG9RLI+x0Z2ubyZEVzA75SYVdaJ0N0=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAkbFvhu7gkAW6MHSrBlpE1n4+HCFRkC5OLAjgqhkTH+/uzSfSl8ois8ZxAD2NgaTZe1M9akhYlrYkes4JECs6A==',
url: 'https://ct1.digicert-ct.com/log/',
mmd: 86400,
state: {
retired: {
timestamp: '2022-01-24T00:00:00Z',
},
},
},
{
description: 'DigiCert Yeti2023 Log',
log_id: 'Nc8ZG7+xbFe/D61MbULLu7YnICZR6j/hKu+oA8M71kw=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfQ0DsdWYitzwFTvG3F4Nbj8Nv5XIVYzQpkyWsU4nuSYlmcwrAp6m092fsdXEw6w1BAeHlzaqrSgNfyvZaJ9y0Q==',
url: 'https://yeti2023.ct.digicert.com/log/',
mmd: 86400,
state: {
retired: {
timestamp: '2022-09-29T00:00:00Z',
},
},
temporal_interval: {
start_inclusive: '2023-01-01T00:00:00Z',
end_exclusive: '2024-01-01T00:00:00Z',
},
},
{
description: 'DigiCert Yeti2024 Log',
log_id: 'SLDja9qmRzQP5WoC+p0w6xxSActW3SyB2bu/qznYhHM=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV7jBbzCkfy7k8NDZYGITleN6405Tw7O4c4XBGA0jDliE0njvm7MeLBrewY+BGxlEWLcAd2AgGnLYgt6unrHGSw==',
url: 'https://yeti2024.ct.digicert.com/log/',
mmd: 86400,
state: {
usable: {
timestamp: '2022-11-01T18:54:00Z',
},
},
temporal_interval: {
start_inclusive: '2024-01-01T00:00:00Z',
end_exclusive: '2025-01-01T00:00:00Z',
},
},
{
description: 'DigiCert Yeti2025 Log',
log_id: 'fVkeEuF4KnscYWd8Xv340IdcFKBOlZ65Ay/ZDowuebg=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE35UAXhDBAfc34xB00f+yypDtMplfDDn+odETEazRs3OTIMITPEy1elKGhj3jlSR82JGYSDvw8N8h8bCBWlklQw==',
url: 'https://yeti2025.ct.digicert.com/log/',
mmd: 86400,
state: {
usable: {
timestamp: '2022-11-01T18:54:00Z',
},
},
temporal_interval: {
start_inclusive: '2025-01-01T00:00:00Z',
end_exclusive: '2026-01-01T00:00:00Z',
},
},
{
description: 'DigiCert Nessie2023 Log',
log_id: 's3N3B+GEUPhjhtYFqdwRCUp5LbFnDAuH3PADDnk2pZo=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEXu8iQwSCRSf2CbITGpUpBtFVt8+I0IU0d1C36Lfe1+fbwdaI0Z5FktfM2fBoI1bXBd18k2ggKGYGgdZBgLKTg==',
url: 'https://nessie2023.ct.digicert.com/log/',
mmd: 86400,
state: {
usable: {
timestamp: '2019-10-31T19:22:00Z',
},
},
temporal_interval: {
start_inclusive: '2023-01-01T00:00:00Z',
end_exclusive: '2024-01-01T00:00:00Z',
},
},
{
description: 'DigiCert Nessie2024 Log',
log_id: 'c9meiRtMlnigIH1HneayxhzQUV5xGSqMa4AQesF3crU=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELfyieza/VpHp/j/oPfzDp+BhUuos6QWjnycXgQVwa4FhRIr4OxCAQu0DLwBQIfxBVISjVNUusnoWSyofK2YEKw==',
url: 'https://nessie2024.ct.digicert.com/log/',
mmd: 86400,
state: {
usable: {
timestamp: '2022-11-01T18:54:00Z',
},
},
temporal_interval: {
start_inclusive: '2024-01-01T00:00:00Z',
end_exclusive: '2025-01-01T00:00:00Z',
},
},
{
description: 'DigiCert Nessie2025 Log',
log_id: '5tIxY0B3jMEQQQbXcbnOwdJA9paEhvu6hzId/R43jlA=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8vDwp4uBLgk5O59C2jhEX7TM7Ta72EN/FklXhwR/pQE09+hoP7d4H2BmLWeadYC3U6eF1byrRwZV27XfiKFvOA==',
url: 'https://nessie2025.ct.digicert.com/log/',
mmd: 86400,
state: {
usable: {
timestamp: '2022-11-01T18:54:00Z',
},
},
temporal_interval: {
start_inclusive: '2025-01-01T00:00:00Z',
end_exclusive: '2026-01-01T00:00:00Z',
},
},
],
},
{
name: 'Sectigo',
email: ['ctops@sectigo.com'],
logs: [
{
description: "Sectigo 'Sabre' CT log",
log_id: 'VYHUwhaQNgFK6gubVzxT8MDkOHhwJQgXL6OqHQcT0ww=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8m/SiQ8/xfiHHqtls9m7FyOMBg4JVZY9CgiixXGz0akvKD6DEL8S0ERmFe9U4ZiA0M4kbT5nmuk3I85Sk4bagA==',
url: 'https://sabre.ct.comodo.com/',
mmd: 86400,
state: {
usable: {
timestamp: '2017-10-10T00:38:10Z',
},
},
},
{
description: "Sectigo 'Mammoth' CT log",
log_id: 'b1N2rDHwMRnYmQCkURX/dxUcEdkCwQApBo2yCJo32RM=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7+R9dC4VFbbpuyOL+yy14ceAmEf7QGlo/EmtYU6DRzwat43f/3swtLr/L8ugFOOt1YU/RFmMjGCL17ixv66MZw==',
url: 'https://mammoth.ct.comodo.com/',
mmd: 86400,
state: {
retired: {
timestamp: '2023-01-15T00:00:00Z',
},
},
},
],
},
{
name: "Let's Encrypt",
email: ['sre@letsencrypt.org'],
logs: [
{
description: "Let's Encrypt 'Oak2023' log",
log_id: 'tz77JN+cTbp18jnFulj0bF38Qs96nzXEnh0JgSXttJk=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEsz0OeL7jrVxEXJu+o4QWQYLKyokXHiPOOKVUL3/TNFFquVzDSer7kZ3gijxzBp98ZTgRgMSaWgCmZ8OD74mFUQ==',
url: 'https://oak.ct.letsencrypt.org/2023/',
mmd: 86400,
state: {
usable: {
timestamp: '2021-03-01T19:24:00Z',
},
},
temporal_interval: {
start_inclusive: '2023-01-01T00:00:00Z',
end_exclusive: '2024-01-07T00:00:00Z',
},
},
{
description: "Let's Encrypt 'Oak2024H1' log",
log_id: 'O1N3dT4tuYBOizBbBv5AO2fYT8P0x70ADS1yb+H61Bc=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEVkPXfnvUcre6qVG9NpO36bWSD+pet0Wjkv3JpTyArBog7yUvuOEg96g6LgeN5uuk4n0kY59Gv5RzUo2Wrqkm/Q==',
url: 'https://oak.ct.letsencrypt.org/2024h1/',
mmd: 86400,
state: {
usable: {
timestamp: '2022-11-30T17:00:00Z',
},
},
temporal_interval: {
start_inclusive: '2023-12-20T00:00:00Z',
end_exclusive: '2024-07-20T00:00:00Z',
},
},
{
description: "Let's Encrypt 'Oak2024H2' log",
log_id: 'PxdLT9ciR1iUHWUchL4NEu2QN38fhWrrwb8ohez4ZG4=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE13PWU0fp88nVfBbC1o9wZfryUTapE4Av7fmU01qL6E8zz8PTidRfWmaJuiAfccvKu5+f81wtHqOBWa+Ss20waA==',
url: 'https://oak.ct.letsencrypt.org/2024h2/',
mmd: 86400,
state: {
usable: {
timestamp: '2022-11-30T17:00:00Z',
},
},
temporal_interval: {
start_inclusive: '2024-06-20T00:00:00Z',
end_exclusive: '2025-01-20T00:00:00Z',
},
},
],
},
{
name: 'TrustAsia',
email: ['trustasia-ct-logs@trustasia.com'],
logs: [
{
description: 'Trust Asia Log2023',
log_id: '6H6nZgvCbPYALvVyXT/g4zG5OTu5L79Y6zuQSdr1Q1o=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEpBFS2xdBTpDUVlESMFL4mwPPTJ/4Lji18Vq6+ji50o8agdqVzDPsIShmxlY+YDYhINnUrF36XBmhBX3+ICP89Q==',
url: 'https://ct.trustasia.com/log2023/',
mmd: 86400,
state: {
usable: {
timestamp: '2021-03-01T19:24:00Z',
},
},
temporal_interval: {
start_inclusive: '2023-01-01T00:00:00Z',
end_exclusive: '2024-01-01T00:00:00Z',
},
},
{
description: 'Trust Asia Log2024-2',
log_id: 'h0+1DcAp2ZMd5XPp8omejkUzs5LTiwpGJXS/D+6y/B4=',
key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEp2TieYE/YdfsxvhlKB2gtGYzwyXVCpV4nI/+pCrYj35y4P6of/ixLYXAjhJ0DS+Mq9d/eh7ZhDM56P2JX5ZICA==',
url: 'https://ct2024.trustasia.com/log2024/',
mmd: 86400,
state: {
usable: {
timestamp: '2023-02-03T08:00:00Z',
},
},
temporal_interval: {
start_inclusive: '2024-01-01T00:00:00Z',
end_exclusive: '2025-01-01T00:00:00Z',
},
},
],
},
],
};
| 7,379
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/constants/constants.ts
|
import { HOUR } from '@proton/shared/lib/constants';
export const MAX_EPOCH_INTERVAL = 72 * HOUR;
export const EXPECTED_EPOCH_INTERVAL = 4 * HOUR;
// VRF constants
export const vrfHexKeyDev = '2d7688feb429f714f102f758412cd4b81337b307122770f620ad9e4ac898a2eb';
export const vrfHexKeyProd = '90a74b3d3ad9cb92e62c4e9c32acc3cc3eff199a32a0ab47a05872c2f15a99c6';
export const N = 16;
export const ptLen = 2 * N; // = qLen
export const CO_FACTOR = 8;
export const LEFT_N = 1; // left neighbour
export const KT_LEN = 32;
export const epochChainVersion = 1;
export enum KT_DOMAINS {
PROD = 'keytransparency.ch',
ATLAS_DEV = 'dev.proton.wtf',
DEV_POSTFIX = '.proton.wtf',
UNKNOWN = 'unknown',
}
export enum KT_CERTIFICATE_ISSUER {
LETSENCRYPT,
ZEROSSL,
}
// Number of independent CT operators from which
// we expect SCTs on epoch certificates
export const SCT_THRESHOLD = 2;
export const KT_VE_SIGNING_CONTEXT = {
value: `key-transparency.verified-epoch.${epochChainVersion}`,
critical: true,
};
export const KT_VE_VERIFICATION_CONTEXT = {
value: `key-transparency.verified-epoch.${epochChainVersion}`,
required: true,
};
export const KT_SKL_SIGNING_CONTEXT = {
value: 'key-transparency.key-list',
critical: false,
};
export const KT_SKL_VERIFICATION_CONTEXT = {
value: 'key-transparency.key-list',
required: false,
};
| 7,380
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/constants/domains.ts
|
export const NO_KT_DOMAINS = [
// Google
'@gmail.com',
'@googlemail.com',
'@google.com',
'@googlegroups.com',
// Microsoft
'@charter.com',
'@compaq.net',
'@hotmail.be',
'@hotmail.ca',
'@hotmail.ch',
'@hotmail.cl',
'@hotmail.co.id',
'@hotmail.co.il',
'@hotmail.co.in',
'@hotmail.co.jp',
'@hotmail.co.kr',
'@hotmail.co.nz',
'@hotmail.co.th',
'@hotmail.co.uk',
'@hotmail.co.za',
'@hotmail.com',
'@hotmail.com.ar',
'@hotmail.com.au',
'@hotmail.com.br',
'@hotmail.com.hk',
'@hotmail.com.tr',
'@hotmail.com.tw',
'@hotmail.com.vn',
'@hotmail.cz',
'@hotmail.de',
'@hotmail.dk',
'@hotmail.es',
'@hotmail.fi',
'@hotmail.fr',
'@hotmail.gr',
'@hotmail.hu',
'@hotmail.it',
'@hotmail.lv',
'@hotmail.my',
'@hotmail.nl',
'@hotmail.no',
'@hotmail.ph',
'@hotmail.rs',
'@hotmail.se',
'@hotmail.sg',
'@hotmail.sk',
'@live.at',
'@live.be',
'@live.ca',
'@live.cl',
'@live.cn',
'@live.co.in',
'@live.co.kr',
'@live.co.uk',
'@live.co.za',
'@live.com',
'@live.com.ar',
'@live.com.au',
'@live.com.co',
'@live.com.mx',
'@live.com.my',
'@live.com.pe',
'@live.com.ph',
'@live.com.pk',
'@live.com.pt',
'@live.com.sg',
'@live.com.ve',
'@live.de',
'@live.dk',
'@live.fi',
'@live.fr',
'@live.hk',
'@live.ie',
'@live.in',
'@live.it',
'@live.jp',
'@live.ma',
'@live.nl',
'@live.no',
'@live.ph',
'@live.ru',
'@live.se',
'@livemail.com.br',
'@livemail.tw',
'@messengeruser.com',
'@msn.com',
'@outlook.at',
'@outlook.be',
'@outlook.cl',
'@outlook.co.id',
'@outlook.co.il',
'@outlook.co.nz',
'@outlook.co.th',
'@outlook.com',
'@outlook.com.ar',
'@outlook.com.au',
'@outlook.com.br',
'@outlook.com.gr',
'@outlook.com.pe',
'@outlook.com.tr',
'@outlook.com.vn',
'@outlook.cz',
'@outlook.de',
'@outlook.dk',
'@outlook.es',
'@outlook.fr',
'@outlook.hu',
'@outlook.ie',
'@outlook.in',
'@outlook.it',
'@outlook.jp',
'@outlook.kr',
'@outlook.lv',
'@outlook.my',
'@outlook.ph',
'@outlook.pt',
'@outlook.sa',
'@outlook.sg',
'@outlook.sk',
'@passport.com',
'@passport.net',
'@windowslive.com',
'@windowslive.es',
// Yahoo
'@yahoo.at',
'@yahoo.be',
'@yahoo.ca',
'@yahoo.co.id',
'@yahoo.co.il',
'@yahoo.co.in',
'@yahoo.co.jp',
'@yahoo.co.nz',
'@yahoo.co.th',
'@yahoo.co.uk',
'@yahoo.co.za',
'@yahoo.com',
'@yahoo.com.ar',
'@yahoo.com.br',
'@yahoo.com.co',
'@yahoo.com.hk',
'@yahoo.com.my',
'@yahoo.com.ph',
'@yahoo.com.sg',
'@yahoo.com.tr',
'@yahoo.com.tw',
'@yahoo.com.vn',
'@yahoo.cz',
'@yahoo.de',
'@yahoo.dk',
'@yahoo.es',
'@yahoo.fi',
'@yahoo.fr',
'@yahoo.gr',
'@yahoo.hu',
'@yahoo.ie',
'@yahoo.in',
'@yahoo.it',
'@yahoo.nl',
'@yahoo.no',
'@yahoo.pl',
'@yahoo.pt',
'@yahoo.ro',
'@yahoo.se',
'@ymail.com',
'@rocketmail.com',
// AOL
'@aol.asia',
'@aol.at',
'@aol.be',
'@aol.ch',
'@aol.cl',
'@aol.co.nz',
'@aol.co.uk',
'@aol.com',
'@aol.com.ar',
'@aol.com.au',
'@aol.com.br',
'@aol.com.co',
'@aol.com.mx',
'@aol.com.tr',
'@aol.com.ve',
'@aol.cz',
'@aol.de',
'@aol.dk',
'@aol.es',
'@aol.fi',
'@aol.fr',
'@aol.in',
'@aol.it',
'@aol.jp',
'@aol.nl',
'@aol.pl',
'@aol.se',
'@aol.tw',
'@wow.com',
'@games.com',
'@love.com',
'@ygm.com',
// Mail.com
'@email.com',
'@groupmail.com',
'@post.com',
'@homemail.com',
'@housemail.com',
'@writeme.com',
'@mail.com',
'@mail-me.com',
'@workmail.com',
'@accountant.com',
'@activist.com',
'@adexec.com',
'@allergist.com',
'@alumni.com',
'@alumnidirector.com',
'@alumnidirector.com',
'@archaeologist.com',
'@auctioneer.net',
'@bartender.net',
'@brew-master.com',
'@chef.net',
'@chemist.com',
'@clerk.com',
'@collector.org',
'@columnist.com',
'@comic.com',
'@consultant.com',
'@contractor.net',
'@counsellor.com',
'@deliveryman.com',
'@diplomats.com',
'@dr.com',
'@engineer.com',
'@financier.com',
'@fireman.net',
'@gardener.com',
'@geologist.com',
'@graphic-designer.com',
'@graduate.org',
'@hairdresser.net',
'@instructor.net',
'@insurer.com',
'@journalist.com',
'@legislator.com',
'@lobbyist.com',
'@minister.com',
'@musician.org',
'@optician.com',
'@orthodontist.net',
'@pediatrician.com',
'@photographer.net',
'@physicist.net',
'@politician.com',
'@presidency.com',
'@priest.com',
'@programmer.net',
'@publicist.com',
'@radiologist.net',
'@realtyagent.com',
'@registerednurses.com',
'@repairman.com',
'@representative.com',
'@salesperson.net',
'@secretary.net',
'@socialworker.net',
'@sociologist.com',
'@songwriter.net',
'@teachers.org',
'@techie.com',
'@technologist.com',
'@therapist.net',
'@umpire.com',
'@worker.com',
'@activist.com',
'@artlover.com',
'@bikerider.com',
'@birdlover.com',
'@blader.com',
'@kittymail.com',
'@lovecat.com',
'@marchmail.com',
'@musician.org',
'@boardermail.com',
'@brew-master.com',
'@catlover.com',
'@chef.net',
'@clubmember.org',
'@nonpartisan.com',
'@petlover.com',
'@photographer.net',
'@songwriter.net',
'@collector.org',
'@doglover.com',
'@gardener.com',
'@greenmail.net',
'@hackermail.com',
'@techie.com',
'@theplate.com',
'@bsdmail.com',
'@computer4u.com',
'@consultant.com',
'@contractor.net',
'@coolsite.net',
'@cyberdude.com',
'@cybergal.com',
'@cyberservices.com',
'@cyber-wizard.com',
'@engineer.com',
'@graphic-designer.com',
'@hackermail.com',
'@linuxmail.org',
'@null.net',
'@physicist.net',
'@post.com',
'@programmer.net',
'@solution4u.com',
'@tech-center.com',
'@techie.com',
'@technologist.com',
'@webname.com',
'@workmail.com',
'@writeme.com',
'@acdcfan.com',
'@angelic.com',
'@discofan.com',
'@elvisfan.com',
'@hiphopfan.com',
'@housemail.com',
'@kissfans.com',
'@madonnafan.com',
'@metalfan.com',
'@musician.org',
'@ninfan.com',
'@ravemail.com',
'@reggaefan.com',
'@snakebite.com',
'@songwriter.net',
'@bellair.net',
'@californiamail.com',
'@dallasmail.com',
'@nycmail.com',
'@pacific-ocean.com',
'@pacificwest.com',
'@sanfranmail.com',
'@usa.com',
'@africamail.com',
'@asia-mail.com',
'@australiamail.com',
'@berlin.com',
'@brazilmail.com',
'@chinamail.com',
'@dublin.com',
'@dutchmail.com',
'@englandmail.com',
'@europe.com',
'@arcticmail.com',
'@europemail.com',
'@germanymail.com',
'@irelandmail.com',
'@israelmail.com',
'@italymail.com',
'@koreamail.com',
'@mexicomail.com',
'@moscowmail.com',
'@munich.com',
'@asia.com',
'@polandmail.com',
'@safrica.com',
'@samerica.com',
'@scotlandmail.com',
'@spainmail.com',
'@swedenmail.com',
'@swissmail.com',
'@torontomail.com',
'@aircraftmail.com',
'@cash4u.com',
'@computer4u.com',
'@comic.com',
'@consultant.com',
'@contractor.net',
'@coolsite.net',
'@cyberservices.com',
'@disposable.com',
'@email.com',
'@execs.com',
'@fastservice.com',
'@greenmail.net',
'@groupmail.com',
'@instruction.com',
'@insurer.com',
'@job4u.com',
'@mail-me.com',
'@net-shopping.com',
'@post.com',
'@planetmail.com',
'@planetmail.net',
'@qualityservice.com',
'@rescueteam.com',
'@solution4u.com',
'@surgical.net',
'@tech-center.com',
'@theplate.com',
'@workmail.com',
'@webname.com',
'@writeme.com',
'@angelic.com',
'@atheist.com',
'@disciples.com',
'@minister.com',
'@muslim.com',
'@priest.com',
'@protestant.com',
'@reborn.com',
'@reincarnate.com',
'@religious.com',
'@saintly.com',
'@brew-meister.com',
'@cutey.com',
'@dbzmail.com',
'@doramail.com',
'@elvisfan.com',
'@galaxyhit.com',
// Mail.ru
'@mail.ru',
'@internet.ru',
'@inbox.ru',
'@list.ru',
'@bk.ru',
// Zoho
'@zohomail.eu',
// iCloud
'@icloud.com',
'@me.com',
'@mac.com',
// Tutanota
'@tutanota.com',
'@tutanota.de',
'@tutamail.com',
'@tuta.io',
'@keemail.me',
'@tutao.de',
// Yandex
'@yandex.ru',
'@yandex.ua',
];
| 7,381
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/constants/index.ts
|
export * from './certificates';
export * from './constants';
export * from './domains';
| 7,382
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/helpers/api.ts
|
export interface GetEpochsParams {
SinceEpochID?: number;
Page?: number;
PageSize?: number;
}
export const getEpochsRoute = (params: GetEpochsParams) => ({
url: 'kt/epochs',
method: 'get',
params,
});
export interface GetCertificateParams {
EpochID: number;
}
export const getCertificateRoute = ({ EpochID }: GetCertificateParams) => ({
url: `kt/v1/epochs/${EpochID}`,
method: 'get',
});
export interface GetProofParams {
EpochID: number;
Identifier: string;
Revision: number;
}
export const getProofRoute = ({ EpochID, Identifier, Revision }: GetProofParams) => ({
url: `kt/v1/epochs/${EpochID}/proof?Identifier=${encodeURIComponent(Identifier)}&Revision=${Revision}`,
method: 'get',
});
export interface GetLatestVerifiedEpochParams {
AddressID: string;
}
export const getLatestVerifiedEpochRoute = ({ AddressID }: GetLatestVerifiedEpochParams) => ({
url: `kt/v1/verifiedepoch/${AddressID}`,
method: 'get',
});
export interface UploadVerifiedEpochPayload {
AddressID: string;
Data: string;
Signature: string;
}
export const uploadVerifiedEpochRoute = ({ AddressID, ...data }: UploadVerifiedEpochPayload) => ({
url: `kt/v1/verifiedepoch/${AddressID}`,
method: 'put',
data,
});
| 7,383
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/helpers/apiHelpers.ts
|
import { CryptoProxy, PrivateKeyReference, PublicKeyReference, VERIFICATION_STATUS } from '@proton/crypto';
import {
getSignedKeyListRoute,
getSignedKeyListsRoute,
updateSignedKeyListRoute,
updateSignedKeyListSignatureRoute,
} from '@proton/shared/lib/api/keys';
import { HTTP_STATUS_CODE } from '@proton/shared/lib/constants';
import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email';
import { Address, Api, FetchedSignedKeyList, SignedKeyList } from '@proton/shared/lib/interfaces';
import { KT_VE_SIGNING_CONTEXT, KT_VE_VERIFICATION_CONTEXT } from '../constants';
import { Epoch, Proof, VerifiedEpoch } from '../interfaces';
import { verifyEpoch } from '../verification';
import { getEpochsRoute, getLatestVerifiedEpochRoute, getProofRoute, uploadVerifiedEpochRoute } from './api';
import { StaleEpochError, isTimestampTooOld, throwKTError } from './utils';
/**
* Fetch the latest issued epoch. Note that there is no guarantee that the
* server will return the actual latest epoch. We can only check that what
* is returned is no older than MAX_EPOCH_INTERVAL
*/
export const fetchLatestEpoch = async (api: Api, verify: boolean = true): Promise<Epoch> => {
const { Epochs } = await api<{ Epochs: Epoch[] }>(getEpochsRoute({}));
const [lastEpoch] = Epochs;
if (verify) {
const certificateTimestamp = await verifyEpoch(lastEpoch);
if (isTimestampTooOld(certificateTimestamp)) {
return throwKTError('Certificate timestamp of alleged latest epoch is older than MAX_EPOCH_INTERVAL', {
lastEpoch: JSON.stringify(lastEpoch),
certificateTimestamp,
});
}
}
return lastEpoch;
};
/**
* Fetch the KT proof of a given email address in a given epoch
*/
export const fetchProof = async (EpochID: number, Identifier: string, Revision: number, api: Api) => {
try {
const cleanIdentifier = canonicalizeInternalEmail(Identifier);
const { Proof } = await api<{ Proof: Proof }>(
getProofRoute({ EpochID, Identifier: cleanIdentifier, Revision })
);
return Proof;
} catch (error: any) {
// If the returned error is 422, it means that the epoch is stale, self audit should start over
if (error?.status === HTTP_STATUS_CODE.UNPROCESSABLE_ENTITY) {
throw new StaleEpochError('Fetching proof with stale epoch');
}
throw error;
}
};
/**
* Fetch all Signed Key Lists that have a revision > AfterRevision, for given email
*/
export const fetchSignedKeyLists = async (
api: Api,
AfterRevision: number,
Identifier: string
): Promise<FetchedSignedKeyList[]> => {
const cleanIdentifier = canonicalizeInternalEmail(Identifier);
const { SignedKeyLists } = await api<{ SignedKeyLists: FetchedSignedKeyList[] }>(
getSignedKeyListsRoute({ AfterRevision, Identifier: cleanIdentifier })
);
return SignedKeyLists;
};
export const updateSignedKeyList = async (
api: Api,
addressID: string,
signedKeyList: SignedKeyList
): Promise<FetchedSignedKeyList> => {
const { SignedKeyList } = await api<{ SignedKeyList: FetchedSignedKeyList }>(
updateSignedKeyListRoute({ AddressID: addressID, SignedKeyList: signedKeyList })
);
return SignedKeyList;
};
/**
* Fetch the Signed key list, for given email and revision
*/
export const fetchSignedKeyList = async (
api: Api,
Revision: number,
Identifier: string
): Promise<FetchedSignedKeyList | null> => {
try {
const cleanIdentifier = canonicalizeInternalEmail(Identifier);
const { SignedKeyList } = await api<{ SignedKeyList: FetchedSignedKeyList }>(
getSignedKeyListRoute({ Revision, Identifier: cleanIdentifier })
);
return SignedKeyList;
} catch (error: any) {
// If the returned error is 422, it means that the revision doesn't exist
if (error?.status === HTTP_STATUS_CODE.UNPROCESSABLE_ENTITY) {
return null;
}
throw error;
}
};
/**
* Fetch the latest verified epoch
*/
export const fetchVerifiedEpoch = async (
address: Address,
api: Api,
userVerificationKeys?: PublicKeyReference[]
): Promise<VerifiedEpoch | null> => {
try {
const { Data, Signature } = await api<{ Data: string; Signature: string }>(
getLatestVerifiedEpochRoute({ AddressID: address.ID })
);
if (userVerificationKeys?.length) {
const { verified } = await CryptoProxy.verifyMessage({
armoredSignature: Signature,
verificationKeys: userVerificationKeys,
textData: Data,
context: KT_VE_VERIFICATION_CONTEXT,
});
if (verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) {
console.warn(
"Verified epoch's signature could not be verified",
'This is expected after a password reset'
);
return null;
}
}
const verifiedEpochData: VerifiedEpoch = JSON.parse(Data);
return verifiedEpochData;
} catch (error: any) {
// If the returned error is 422, it means that the verified
// epoch was never uploaded, e.g. because the address has just been created
if (error?.status === HTTP_STATUS_CODE.UNPROCESSABLE_ENTITY) {
return null;
}
throw error;
}
};
/**
* Upload a verified epoch
*/
export const uploadVerifiedEpoch = async (
verifiedEpoch: VerifiedEpoch,
AddressID: string,
signingKeys: PrivateKeyReference,
api: Api
) => {
const bodyData = JSON.stringify(verifiedEpoch);
await api(
uploadVerifiedEpochRoute({
AddressID,
Data: bodyData,
Signature: await CryptoProxy.signMessage({
textData: bodyData,
signingKeys,
detached: true,
context: KT_VE_SIGNING_CONTEXT,
}),
})
);
};
/**
* Update the signature for an existing SKL
*/
export const updateSignedKeyListSignature = async (
addressID: string,
revision: number,
newSignature: string,
api: Api
) => {
await api(
updateSignedKeyListSignatureRoute({
AddressID: addressID,
Revision: revision,
Signature: newSignature,
})
);
};
| 7,384
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/helpers/index.ts
|
export * from './api';
export * from './apiHelpers';
export * from './utils';
| 7,385
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/helpers/utils.ts
|
import { sub } from 'date-fns';
import { serverTime } from '@proton/crypto';
import { TelemetryKeyTransparencyErrorEvents, TelemetryMeasurementGroups } from '@proton/shared/lib/api/telemetry';
import { PROTON_DOMAINS } from '@proton/shared/lib/constants';
import { sendTelemetryReport } from '@proton/shared/lib/helpers/metrics';
import { captureMessage } from '@proton/shared/lib/helpers/sentry';
import { Api, SimpleMap } from '@proton/shared/lib/interfaces';
import { EXPECTED_EPOCH_INTERVAL, KT_DOMAINS, MAX_EPOCH_INTERVAL } from '../constants/constants';
/**
* Retrieve when an obsolescence token was generated by parsing
* from the token itself
*/
export const getTimeFromObsolescenceToken = (ObsolescenceToken: string) => parseInt(ObsolescenceToken.slice(0, 16), 16);
/**
* Extract the domain from an email address
*/
export const getEmailDomain = (email: string) => `@${email.split('@')[1]}`;
/**
* Check whether a timestamp is older than maximum epoch interval from the given reference
*/
export const isTimestampTooOlderThanReference = (time: number, referenceTime: number) =>
referenceTime > MAX_EPOCH_INTERVAL + time;
/**
* Check whether a timestamp is older than maximum epoch interval from now
*/
export const isTimestampTooOld = (time: number) => isTimestampTooOlderThanReference(time, +serverTime());
/**
* Check whether a timestamp is within a maximum epoch interval range
* from the given temporal reference, boundaries included
*/
export const isTimestampWithinSingleRange = (time: number, referenceTime: number) =>
Math.abs(referenceTime - time) <= MAX_EPOCH_INTERVAL;
/**
* Check whether a timestamp is within two limits, boundaries included
*/
export const isTimestampWithinDoubleRange = (time: number, start: number, end: number) => time >= start && time <= end;
/**
* Check whether a timestamp is within a maximum epoch interval range from
* 90 days in the past, which is the threshold after which epoch certificates
* expire
*/
export const isTimestampOldEnough = (time: number) =>
isTimestampWithinSingleRange(time, +sub(serverTime(), { days: 90 }));
/**
* Check whether a timestamp is older than 90 days in the past,
* which is the threshold after which epoch certificates expire
*/
export const isTimestampOlderThanThreshold = (time: number) => time < +sub(serverTime(), { days: 90 });
/**
* Helper to send outbound public key verification failures to the telemetry endpoint
*/
export const ktKeyVerificationFailureTelemetry = (api: Api, visible: boolean): Promise<void> => {
const dimensions: SimpleMap<string> = {
visibility: visible ? 'visible' : 'hidden',
};
return sendTelemetryReport({
api,
measurementGroup: TelemetryMeasurementGroups.keyTransparency,
event: TelemetryKeyTransparencyErrorEvents.key_verification_failure,
dimensions,
});
};
/**
* Helper to send KT-related sentry reports
*/
export const ktSentryReport = (errorMessage: string, extra?: { [key: string]: any }) => {
const isoServerTime = serverTime().toISOString();
const extraWithServerTime = { ...extra, server_time: isoServerTime };
captureMessage(`[KeyTransparency] ${errorMessage}`, { extra: extraWithServerTime });
};
/**
* Helper to send KT-related sentry reports
*/
export const ktSentryReportError = (error: any, extra?: { [key: string]: any }) => {
const errorMessage = error instanceof Error ? `${error.name}: ${error.message}` : 'unknown error';
const stack = error instanceof Error ? error.stack : undefined;
ktSentryReport(errorMessage, { ...extra, stack });
};
export class KeyTransparencyError extends Error {}
export class StaleEpochError extends Error {}
export const throwKTError = (errorMessage: string, extra?: { [key: string]: any }): never => {
ktSentryReport(errorMessage, extra);
throw new KeyTransparencyError(errorMessage);
};
/**
* Derive which base domain is being used, whether production or test
*/
export const getBaseDomain = (sendReport: boolean = true) => {
// The app name is removed
const { hostname } = window.location;
const currentDomain = hostname.slice(hostname.indexOf('.') + 1);
// Production domain, e.g. protonmail.com -> PROD
if (PROTON_DOMAINS.includes(currentDomain)) {
return KT_DOMAINS.PROD;
}
// Development or test environments
const domainParts = currentDomain.split('.');
if (domainParts.length > 1 && domainParts[domainParts.length - 2] === 'proton') {
const postfix = domainParts[domainParts.length - 1];
switch (postfix) {
case 'pink':
// {env}.proton.pink -> prod
return KT_DOMAINS.PROD;
case 'black':
if (domainParts.length < 3) {
// proton.black -> ATLAS_DEV
return KT_DOMAINS.ATLAS_DEV;
} else {
// {env}.proton.black -> {env} + DEV_POSTFIX
return domainParts[domainParts.length - 3] + KT_DOMAINS.DEV_POSTFIX;
}
case 'local':
// proton.local -> ATLAS_DEV
return KT_DOMAINS.ATLAS_DEV;
}
}
// Any other domain.
// Since this function is also used to test whether to use KT at all, we don't want to spam sentry with
// attempts to figure this out, in which case sendReport should be false
if (sendReport) {
return throwKTError('Domain not recognised', {
hostname,
currentDomain,
domainParts: JSON.stringify(domainParts),
});
}
return KT_DOMAINS.UNKNOWN;
};
export const getSelfAuditInterval = () => {
return EXPECTED_EPOCH_INTERVAL;
};
| 7,386
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/storage/index.ts
|
export * from './storageHelpers';
export * from './ktStorageAPI';
| 7,387
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/storage/ktStorageAPI.ts
|
import { instance } from '@proton/cross-storage/account-impl/guestInstance';
import { APPS, APP_NAMES } from '@proton/shared/lib/constants';
import { KTLocalStorageAPI } from '@proton/shared/lib/interfaces';
import { getDefaultKTLS } from '@proton/shared/lib/keyTransparency';
const isCrossStorageAvailable = ((): (() => Promise<boolean>) => {
let crossStorageAvailable: Promise<boolean> | undefined;
return async () => {
if (crossStorageAvailable === undefined) {
crossStorageAvailable = (async () => {
try {
const test = 'kttest';
await instance.setLocalStorage(test, test);
await instance.removeLocalStorage(test);
return true;
} catch (error) {
return false;
}
})();
}
return crossStorageAvailable;
};
})();
/**
* Return the set of functions to use account's local storage
*/
export const getKTLocalStorage = async (APP_NAME: APP_NAMES): Promise<KTLocalStorageAPI> => {
if (APP_NAME === APPS.PROTONACCOUNT || APP_NAME === APPS.PROTONVPN_SETTINGS) {
// If we are in account, we use its local storage directly
return getDefaultKTLS();
}
// Check if cross storage is available
const crossStorageAvailable = await isCrossStorageAvailable();
if (!crossStorageAvailable) {
return getDefaultKTLS();
}
// Otherwise we access it via cross-storage
return {
getItem: async (key: string) => instance.getLocalStorage(key),
setItem: async (key: string, value: string) => instance.setLocalStorage(key, value),
removeItem: async (key: string) => instance.removeLocalStorage(key),
getBlobs: () => instance.getLocalStorageKeys().then((keys) => keys || []),
};
};
| 7,388
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/storage/storageHelpers.ts
|
import { CryptoProxy, PrivateKeyReference, PublicKeyReference } from '@proton/crypto';
import { KTLocalStorageAPI } from '@proton/shared/lib/interfaces';
import { ktSentryReportError, throwKTError } from '../helpers/utils';
import { KTBlobContent, KTBlobValuesWithInfo, SelfAuditResult } from '../interfaces';
/**
* Get all KT-related blobs from localStorage for the specified user
* and decrypt them. If an addressID is specified, only those related
* to it are returned
*/
export const getAllKTBlobValuesWithInfo = async (
userID: string,
userPrivateKeys: PrivateKeyReference[],
ktLSAPI: KTLocalStorageAPI,
addressID?: string
): Promise<Map<string, KTBlobValuesWithInfo>> => {
const keys = await ktLSAPI.getBlobs();
const ktBlobValuesWithInfoMap: Map<string, KTBlobValuesWithInfo> = new Map();
for (const key of keys) {
// Format is KT:{userID}:{addressID}
const chunks = key.split(':');
if (chunks.length !== 3) {
continue;
}
const [ktTag, storedUserID, storedAddress] = chunks;
if (
ktTag !== 'KT' ||
storedUserID !== userID ||
storedAddress === 'audit' ||
(!!addressID && storedAddress !== addressID)
) {
continue;
}
const armoredMessage = await ktLSAPI.getItem(key);
if (!armoredMessage) {
return throwKTError('No value found for an existing key', {
context: 'getAllKTBlobValuesWithInfo',
});
}
try {
const decrypted = await CryptoProxy.decryptMessage({
armoredMessage,
decryptionKeys: userPrivateKeys,
}).catch((error) => {
console.warn(error, 'This is expected after a password reset');
return null;
});
if (!decrypted) {
continue;
}
const ktBlobsContent: KTBlobContent[] = JSON.parse(decrypted.data);
// Legacy blob did not set the revision, we ignore them
const newKTBlobs = ktBlobsContent.filter(({ revision }) => revision !== undefined);
ktBlobValuesWithInfoMap.set(storedAddress, {
userID,
addressID: storedAddress,
ktBlobsContent: newKTBlobs,
});
} catch (error: any) {
ktSentryReportError(error, { context: 'getAllKTBlobValuesWithInfo' });
}
}
return ktBlobValuesWithInfoMap;
};
/**
* Generate a key name according to the KT format
*/
const generateKeyFullName = (userID: string, addressID: string) => `KT:${userID}:${addressID}`;
/**
* Remove a specific KT blob from localStorage
*/
export const removeKTFromLS = async (userID: string, addressID: string, ktLSAPI: KTLocalStorageAPI) =>
ktLSAPI.removeItem(generateKeyFullName(userID, addressID));
/**
* Encrypt a spefic KT blob to localStorage
*/
export const encryptKTtoLS = async (
ktBlobContentWithInfo: KTBlobValuesWithInfo,
userPrimaryKey: PublicKeyReference,
ktLSAPI: KTLocalStorageAPI
) => {
const { userID, addressID, ktBlobsContent } = ktBlobContentWithInfo;
const ciphertext = (
await CryptoProxy.encryptMessage({
textData: JSON.stringify(ktBlobsContent),
encryptionKeys: userPrimaryKey,
})
).message;
return ktLSAPI.setItem(generateKeyFullName(userID, addressID), ciphertext);
};
/**
* Commit SKLs to local storage for later checking.
*/
export const commitSKLToLS = async (
ktBlobContent: KTBlobContent,
userPrivateKeys: PrivateKeyReference[],
ktLSAPI: KTLocalStorageAPI,
userID: string,
addressID: string
) => {
try {
const ktBlobsMap = await getAllKTBlobValuesWithInfo(userID, userPrivateKeys, ktLSAPI, addressID);
const ktBlobsContent = ktBlobsMap.get(addressID)?.ktBlobsContent || [];
const isAlreadyInLS =
ktBlobsContent.filter(
(ktBlob) => ktBlob.data === ktBlobContent.data && ktBlob.revision === ktBlobContent.revision
).length != 0;
if (!isAlreadyInLS) {
ktBlobsContent.push(ktBlobContent);
return await encryptKTtoLS(
{
userID,
addressID,
ktBlobsContent,
},
userPrivateKeys[0],
ktLSAPI
);
}
} catch (error: any) {
ktSentryReportError(error, { context: 'commitSKLToLS' });
}
};
/**
* Generate a key name according to the KT format for self-audit
*/
const generateKeyAuditName = (userID: string) => `KT:${userID}:audit`;
/**
* Store the last result of self-audit
*/
export const storeAuditResult = async (
userID: string,
selfAuditResult: SelfAuditResult,
userPrimaryKey: PublicKeyReference,
ktLSAPI: KTLocalStorageAPI
) => {
const ciphertext = (
await CryptoProxy.encryptMessage({
textData: JSON.stringify(selfAuditResult),
encryptionKeys: userPrimaryKey,
})
).message;
ktLSAPI.setItem(generateKeyAuditName(userID), ciphertext);
};
/**
* Retrieve the last time self-audit was executed. It defaults
* to null if none can be found
*/
export const getAuditResult = async (
userID: string,
userPrivateKeys: PrivateKeyReference[],
ktLSAPI: KTLocalStorageAPI
): Promise<SelfAuditResult | undefined> => {
try {
const armoredMessage = await ktLSAPI.getItem(generateKeyAuditName(userID));
if (armoredMessage) {
if (!armoredMessage.startsWith('-----BEGIN PGP MESSAGE-----')) {
// Old audits blob were only containing the audit time, not encrypted.
return;
}
const decrypted = await CryptoProxy.decryptMessage({
armoredMessage,
decryptionKeys: userPrivateKeys,
}).catch((error) => {
console.warn(error, 'This is expected after a password reset');
return null;
});
if (!decrypted) {
return;
}
const parsed = JSON.parse(decrypted.data);
if (!parsed.nextAuditTime) {
return;
}
return parsed;
}
} catch (error: any) {
ktSentryReportError(error, { context: 'getAuditResult' });
}
};
| 7,389
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/index.ts
|
export * from './verifyCertificates';
export * from './verifyEpochs';
export * from './verifyKeys';
export * from './verifyProofs';
export * from './vrf';
export * from './self-audit';
export * from './verifyAddress';
| 7,390
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/verifyAddress.ts
|
import { Api, FetchedSignedKeyList } from '@proton/shared/lib/interfaces';
import { fetchProof, throwKTError } from '../helpers';
import { Epoch } from '../interfaces';
import {
verifyProofOfAbsenceForAllRevision,
verifyProofOfAbsenceForRevision,
verifyProofOfObsolescence,
} from './verifyProofs';
/**
* Check if the address is obsolete in key transparency by fetching the proofs
* at the SKL revision and the next revision. If the first is a valid obsolescence proof and
* the second is a valid absence proof (i.e., the obsolete SKL is at the latest revision),
* the address is verifiably obsolete in KT.
*/
export const verifyAddressIsObsolete = async (
epoch: Epoch,
email: string,
signedKeyList: Partial<FetchedSignedKeyList>,
api: Api
) => {
const { Revision } = signedKeyList;
if (!Revision) {
return throwKTError('Obsolescence proof with incomplete information', {
email,
signedKeyList,
});
}
const checkObsolescence = async () => {
const obsolescenceProof = await fetchProof(epoch.EpochID, email, Revision, api);
await verifyProofOfObsolescence(obsolescenceProof, email, epoch.TreeHash, signedKeyList);
};
const checkAbsence = async () => {
const absenceProof = await fetchProof(epoch.EpochID, email, Revision + 1, api);
await verifyProofOfAbsenceForRevision(absenceProof, email, epoch.TreeHash, Revision + 1);
};
await Promise.all([checkObsolescence(), checkAbsence()]);
};
/**
* Check if the address is absent in key transparency by fetching the proof at revision 1.
* If it is a valid absence proof for all revisions, the address is verifiably
* absent in KT.
*/
export const verifyAddressIsAbsent = async (epoch: Epoch, email: string, api: Api) => {
const absenceProof = await fetchProof(epoch.EpochID, email, 1, api);
await verifyProofOfAbsenceForAllRevision(absenceProof, email, epoch.TreeHash);
};
| 7,391
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/verifyCertificates.ts
|
import { fromBER } from 'asn1js';
import { Certificate, CertificateChainValidationEngine, GeneralName, verifySCTsForCertificate } from 'pkijs';
import { getParametersValue } from 'pvutils';
import { hexStringToArray } from '@proton/crypto/lib/utils';
import { base64StringToUint8Array, uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { KT_CERTIFICATE_ISSUER, SCT_THRESHOLD, epochChainVersion } from '../constants';
import { ctLogs, rootCertificates } from '../constants/certificates';
import { getBaseDomain, throwKTError } from '../helpers/utils';
/**
* Extract the content of a string Certificate
*/
export const pemToString = (cert: string) => {
const lines = cert.split('\n');
let encoded = '';
for (let i = 0; i < lines.length; i++) {
if (
lines[i].trim().length > 0 &&
lines[i].indexOf('-BEGIN CERTIFICATE-') < 0 &&
lines[i].indexOf('-END CERTIFICATE-') < 0
) {
encoded += lines[i].trim();
}
}
return encoded;
};
/**
* Parse a string certificate into a Certificate object
*/
export const parseCertificate = (cert: string) => {
const asn1Certificate = fromBER(base64StringToUint8Array(pemToString(cert)).buffer);
return new Certificate({ schema: asn1Certificate.result });
};
/**
* Parse a chain of certificates into an array of Certificate objects
*/
export const parseCertChain = (certChain: string) => {
const certArr = certChain.split('-----END CERTIFICATE-----\n\n-----BEGIN CERTIFICATE-----');
for (let i = 0; i < certArr.length; i++) {
switch (i) {
case 0:
certArr[i] = `${certArr[i]}-----END CERTIFICATE-----`;
break;
case certArr.length - 1:
certArr[i] = `-----BEGIN CERTIFICATE-----${certArr[i]}`;
break;
default:
certArr[i] = `-----BEGIN CERTIFICATE-----${certArr[i]}-----END CERTIFICATE-----`;
break;
}
}
return certArr.map((cert) => parseCertificate(cert));
};
/**
* Check the alternative name inside a certificate matches the one given by the server
*/
export const verifyAltName = (
certificate: Certificate,
ChainHash: string,
EpochID: number,
CertificateTime: number
) => {
if (!certificate.extensions) {
return throwKTError('Epoch certificate does not have extensions', {
extensions: JSON.stringify(certificate.extensions),
});
}
const altNamesExt = certificate.extensions.find((ext) => ext.extnID === '2.5.29.17');
if (!altNamesExt) {
return throwKTError('Epoch certificate does not have AltName extension', {
altNamesExt: JSON.stringify(altNamesExt),
});
}
altNamesExt.parsedValue.altNames.sort((firstEl: GeneralName, secondEl: GeneralName) => {
const firstLenght = getParametersValue<string>(firstEl, 'value', '').length;
const secondLenght = getParametersValue<string>(secondEl, 'value', '').length;
return secondLenght - firstLenght;
});
// The primary name cannot be longer than 64 chars due to TLS certificate restrictions, which
// means that it will be the shorter of the two. The alternative name is the one containing ChainHash
// and is therefore the longest of the two
const alternativeName = altNamesExt.parsedValue.altNames[0].value;
const baseDomain = getBaseDomain();
if (
`${ChainHash.slice(0, 32)}.${ChainHash.slice(
32
)}.${CertificateTime}.${EpochID}.${epochChainVersion}.${baseDomain}` !== alternativeName
) {
return throwKTError('Epoch certificate alternative name does not match', {
ChainHash,
EpochID,
alternativeName,
baseDomain,
CertificateTime,
});
}
};
/**
* Convert a certificate back to string
*/
const printCertificate = (cert: Certificate) => {
const body = uint8ArrayToBase64String(new Uint8Array(cert.toSchema().toBER()));
let result = `-----BEGIN CERTIFICATE-----`;
let i = 0;
while (i < body.length) {
result = `${result}\n${body.slice(i, i + 64)}`;
i += 64;
}
result = `${result}\n-----END CERTIFICATE-----`;
return result;
};
/**
* Verify a full certificate chain
*/
export const verifyCertChain = async (
certChain: Certificate[],
CertificateIssuer: KT_CERTIFICATE_ISSUER,
now: Date
): Promise<void> => {
const rootCerts = rootCertificates.get(CertificateIssuer)?.map((cert) => parseCertificate(cert));
if (!rootCerts?.length) {
return throwKTError('Unknown issuer', {
CertificateIssuer,
});
}
const chainEngine = new CertificateChainValidationEngine({
certs: certChain.slice().reverse(), // the engine expects the root cert first and the leaf cert last
checkDate: now,
trustedCerts: rootCerts,
});
const verificationResult = await chainEngine.verify();
const throwError = () => {
return throwKTError("Epoch certificate did not pass verification against issuer's certificate chain", {
certChain: JSON.stringify(certChain.map((cert) => printCertificate(cert))),
resultMessage: verificationResult.resultMessage,
});
};
if (!verificationResult.result || !verificationResult.certificatePath?.length) {
return throwError();
}
// Check that the path starts at the epoch cert and ends at the root cert
if (verificationResult.certificatePath[0] !== certChain[0]) {
return throwError();
}
if (!rootCerts.includes(verificationResult.certificatePath[verificationResult.certificatePath.length - 1])) {
return throwError();
}
};
/**
* Extract the list of CT log IDs from the SCTs of the certificate, in the order they appear
*/
export const extractSCTs = (certificate: Certificate) => {
const SignedCertificateTimestampListID = '1.3.6.1.4.1.11129.2.4.2';
const timestamps: string[] = [];
for (let i = 0; certificate.extensions && i < certificate.extensions.length; i++) {
if (certificate.extensions[i].extnID === SignedCertificateTimestampListID) {
const { parsedValue } = certificate.extensions[i];
if (parsedValue) {
timestamps.push(
...parsedValue
.toJSON()
.timestamps.map(({ logID }: { logID: string }) =>
uint8ArrayToBase64String(hexStringToArray(logID))
)
);
}
break;
}
}
return timestamps;
};
/**
* Verify the SignedCertificateTimestamp of the given certificate. issuerCert is the certificate
* of the issuer, which we assume was already verified as part of the certificate chain verification
*/
export const verifySCT = async (certificate: Certificate, issuerCert: Certificate) => {
const scts = extractSCTs(certificate);
const logs = ctLogs.operators.map(({ logs }) => logs.map(({ log_id, key }) => ({ log_id, key }))).flat();
const verified: boolean[] = [];
try {
verified.push(...(await verifySCTsForCertificate(certificate, issuerCert, logs)));
} catch (error: any) {
return throwKTError('SCT verification failed', {
errorMessage: error.message,
certificate: printCertificate(certificate),
issuerCert: printCertificate(issuerCert),
});
}
if (verified.length !== scts.length) {
return throwKTError('The number of verified SCTs does not match with the number of SCTs', {
scts: JSON.stringify(scts),
verified: JSON.stringify(verified),
certificate: printCertificate(certificate),
issuerCert: printCertificate(issuerCert),
});
}
const sctsFromOperators = new Map<string, number>();
for (let i = 0; i < scts.length; i++) {
const isVerified = verified[i];
const logID = scts[i];
if (isVerified) {
for (const operator of ctLogs.operators) {
if (operator.logs.findIndex(({ log_id }) => log_id === logID) !== -1) {
const operatorName = operator.name;
const previousCount = sctsFromOperators.get(operatorName) || 0;
sctsFromOperators.set(operatorName, previousCount + 1);
break;
}
}
}
}
if (sctsFromOperators.size < SCT_THRESHOLD) {
return throwKTError('The number of verified SCTs does not reach the number of operator threshold', {
scts: JSON.stringify(scts),
verified: JSON.stringify(verified),
certificate: printCertificate(certificate),
issuerCert: printCertificate(issuerCert),
sctsFromOperators: JSON.stringify([...sctsFromOperators.entries()]),
});
}
};
export const parseCertTime = (cert: Certificate) => {
let returnedDate: number;
switch (cert.notBefore.type) {
case 0:
case 1:
returnedDate = cert.notBefore.value.getTime();
break;
default:
return throwKTError("Certificate's notBefore date is invalid", {
certType: cert.notBefore.type,
});
}
return returnedDate;
};
| 7,392
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/verifyEpochs.ts
|
import { CryptoProxy, serverTime } from '@proton/crypto';
import { arrayToHexString, hexStringToArray } from '@proton/crypto/lib/utils';
import { throwKTError } from '../helpers/utils';
import { Epoch } from '../interfaces';
import { parseCertChain, parseCertTime, verifyAltName, verifyCertChain, verifySCT } from './verifyCertificates';
/**
* Verify the consistency and correctness of an epoch
*/
export const verifyEpoch = async (epoch: Epoch) => {
const { ChainHash, PrevChainHash, TreeHash, Certificate, EpochID, CertificateIssuer, CertificateTime } = epoch;
// 1. Validate the certificate
const certChain = parseCertChain(Certificate);
await verifyCertChain(certChain, CertificateIssuer, serverTime());
const [epochCert, issuerCert] = certChain;
await verifySCT(epochCert, issuerCert);
// 2. Validate the epoch
const checkChainHash = arrayToHexString(
await CryptoProxy.computeHash({
algorithm: 'SHA256',
data: hexStringToArray(`${PrevChainHash}${TreeHash}`),
})
);
if (ChainHash !== checkChainHash) {
return throwKTError('Chain hash of fetched epoch is not consistent', {
ChainHash,
PrevChainHash,
TreeHash,
EpochID,
});
}
verifyAltName(epochCert, ChainHash, EpochID, CertificateTime);
return parseCertTime(epochCert);
};
| 7,393
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/verifyKeys.ts
|
import { CryptoProxy, KeyReference, PublicKeyReference, VERIFICATION_STATUS } from '@proton/crypto';
import {
Api,
FetchedSignedKeyList,
GetLatestEpoch,
KT_VERIFICATION_STATUS,
KeyTransparencyVerificationResult,
ProcessedApiAddressKey,
SaveSKLToLS,
SignedKeyListItem,
} from '@proton/shared/lib/interfaces';
import { getParsedSignedKeyList } from '@proton/shared/lib/keys';
import { KT_SKL_VERIFICATION_CONTEXT } from '../constants';
import { NO_KT_DOMAINS } from '../constants/domains';
import { fetchProof } from '../helpers/apiHelpers';
import { KeyTransparencyError, getEmailDomain, throwKTError } from '../helpers/utils';
import {
verifyProofOfAbsenceForAllRevision,
verifyProofOfAbsenceForRevision,
verifyProofOfExistence,
verifyProofOfObsolescence,
} from './verifyProofs';
/**
* Check that two SKLs are identical
*/
export const checkSKLEquality = (skl1: FetchedSignedKeyList, skl2: FetchedSignedKeyList) =>
skl1.Data === skl2.Data && skl1.Signature === skl2.Signature;
/**
* Parse a key list into a list of key info
*/
export const parseKeyList = async (keyList: KeyWithFlags[]): Promise<SignedKeyListItem[]> =>
Promise.all(
keyList.map(async ({ key, flags, primary }, index) => ({
Fingerprint: key.getFingerprint(),
SHA256Fingerprints: await CryptoProxy.getSHA256Fingerprints({ key }),
Primary: primary ?? index === 0 ? 1 : 0,
Flags: flags,
}))
);
/**
* Check whether the metadata of a key matches what is stored in the Signed Key List
*/
const compareKeyInfo = (email: string, keyInfo: SignedKeyListItem, sklKeyInfo: SignedKeyListItem) => {
// Check fingerprints
if (keyInfo.Fingerprint !== sklKeyInfo.Fingerprint) {
return throwKTError('Fingerprints differ', { email });
}
// Check SHA256Fingerprints
if (keyInfo.SHA256Fingerprints.length !== sklKeyInfo.SHA256Fingerprints.length) {
return throwKTError('SHA256Fingerprints length differ', { email });
}
keyInfo.SHA256Fingerprints.forEach((sha256Fingerprint, i) => {
if (sha256Fingerprint !== sklKeyInfo.SHA256Fingerprints[i]) {
return throwKTError('SHA256Fingerprints differ', { email });
}
});
// Check Flags
if (keyInfo.Flags !== sklKeyInfo.Flags) {
return throwKTError('Flags differ', { email });
}
// Check primariness
if (keyInfo.Primary !== sklKeyInfo.Primary) {
return throwKTError('Primariness differs', { email });
}
};
/**
* Check that a list of keys is correctly represented by a Signed Key List
*/
export const verifyKeyList = async (
email: string,
keyListInfo: SignedKeyListItem[],
signedKeyListInfo: SignedKeyListItem[]
) => {
// Check arrays validity
if (keyListInfo.length === 0) {
return throwKTError('No keys detected', { email });
}
if (keyListInfo.length !== signedKeyListInfo.length) {
return throwKTError('Key list and signed key list have different lengths', { email });
}
// Sorting both lists just to make sure key infos appear in the same order
keyListInfo.sort((key1, key2) => {
return key1.Fingerprint.localeCompare(key2.Fingerprint);
});
signedKeyListInfo.sort((key1, key2) => {
return key1.Fingerprint.localeCompare(key2.Fingerprint);
});
// Check keys
keyListInfo.forEach((key, i) => compareKeyInfo(email, key, signedKeyListInfo[i]));
};
interface KeyWithFlags {
key: KeyReference;
flags: number;
primary?: 1 | 0;
}
/**
* Check that the given keys mirror what's inside the given SKL Data.
*/
export const checkKeysInSKL = async (email: string, apiKeys: KeyWithFlags[], sklData: string) => {
const parsedSKL = getParsedSignedKeyList(sklData);
if (!parsedSKL) {
return throwKTError('SignedKeyList data parsing failed', { sklData });
}
const keyListInfo = await parseKeyList(apiKeys);
return verifyKeyList(email, keyListInfo, parsedSKL);
};
export const verifySKLSignature = async (
verificationKeys: PublicKeyReference[],
signedKeyListData: string,
signedKeyListSignature: string,
verificationTime?: Date
): Promise<Date | null> => {
const { verified, signatureTimestamp } = await CryptoProxy.verifyMessage({
armoredSignature: signedKeyListSignature,
verificationKeys,
textData: signedKeyListData,
context: KT_SKL_VERIFICATION_CONTEXT,
date: verificationTime,
});
if (verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) {
return null;
}
return signatureTimestamp;
};
/**
* Verify that public keys associated to an email address are correctly stored in KT
*/
const verifyPublicKeys = async (
apiKeys: ProcessedApiAddressKey[],
email: string,
signedKeyList: FetchedSignedKeyList | null,
api: Api,
saveSKLToLS: SaveSKLToLS,
getLatestEpoch: GetLatestEpoch,
/**
* Optimisations for apps where users with external domains do not have valid keys (e.g. Mail)
*/
skipVerificationOfExternalDomains: boolean,
isCatchall?: boolean
): Promise<KeyTransparencyVerificationResult> => {
try {
if (!signedKeyList || !signedKeyList.Signature) {
// Absent or obsolete address
if (skipVerificationOfExternalDomains && NO_KT_DOMAINS.includes(getEmailDomain(email))) {
return { status: KT_VERIFICATION_STATUS.UNVERIFIED_KEYS };
}
}
if (signedKeyList?.Revision === 0) {
return throwKTError('Signed key list with revision 0', { email });
}
// The following checks can only be executed if the SKL is non-obsolescent
const verifySKL = async () => {
if (signedKeyList?.Data) {
// Verify key list matches the signed key list
await checkKeysInSKL(
email,
apiKeys.map(({ publicKeyRef, flags }) => ({ key: publicKeyRef, flags })),
signedKeyList.Data!
);
}
};
const sklVerificationPromise = verifySKL();
const identifier = isCatchall ? getEmailDomain(email) : email;
if (signedKeyList && !signedKeyList.MinEpochID) {
if (!signedKeyList.ExpectedMinEpochID) {
return throwKTError("SKL doesn't have a MinEpochID or ExpectedMinEpochID set", {
email,
signedKeyList,
});
}
const data = signedKeyList.Data ?? signedKeyList.ObsolescenceToken;
if (!data) {
return throwKTError("SKL doesn't have data or obsolescence token", { email, signedKeyList });
}
await sklVerificationPromise;
await saveSKLToLS(
email,
data,
signedKeyList.Revision,
signedKeyList.ExpectedMinEpochID,
undefined,
isCatchall
);
if (signedKeyList.ObsolescenceToken) {
return { status: KT_VERIFICATION_STATUS.UNVERIFIED_KEYS, keysChangedRecently: true };
} else {
return { status: KT_VERIFICATION_STATUS.VERIFIED_KEYS, keysChangedRecently: true };
}
}
let epoch = await getLatestEpoch(true);
if (!signedKeyList) {
const proof = await fetchProof(epoch.EpochID, identifier, 1, api);
await verifyProofOfAbsenceForAllRevision(proof, identifier, epoch.TreeHash);
return { status: KT_VERIFICATION_STATUS.UNVERIFIED_KEYS };
}
if (epoch.EpochID < signedKeyList.MinEpochID!) {
// Cache is too old, refetch the last epoch
epoch = await getLatestEpoch(true);
}
const [proof, nextRevisionProof] = await Promise.all([
fetchProof(epoch.EpochID, identifier, signedKeyList.Revision, api),
fetchProof(epoch.EpochID, identifier, signedKeyList.Revision + 1, api),
]);
const nextProofVerification = verifyProofOfAbsenceForRevision(
nextRevisionProof,
identifier,
epoch.TreeHash,
signedKeyList.Revision + 1
);
if (signedKeyList.Signature) {
await Promise.all([
sklVerificationPromise,
nextProofVerification,
verifyProofOfExistence(proof, identifier, epoch.TreeHash, signedKeyList),
]);
return { status: KT_VERIFICATION_STATUS.VERIFIED_KEYS };
} else {
await Promise.all([
sklVerificationPromise,
nextProofVerification,
verifyProofOfObsolescence(proof, identifier, epoch.TreeHash, signedKeyList),
]);
return { status: KT_VERIFICATION_STATUS.UNVERIFIED_KEYS };
}
} catch (error: any) {
if (error instanceof KeyTransparencyError) {
return { status: KT_VERIFICATION_STATUS.VERIFICATION_FAILED };
}
throw error;
}
};
export const verifyPublicKeysAddressAndCatchall = async (
api: Api,
saveSKLToLS: SaveSKLToLS,
getLatestEpoch: GetLatestEpoch,
email: string,
skipVerificationOfExternalDomains: boolean,
address: {
keyList: ProcessedApiAddressKey[];
signedKeyList: FetchedSignedKeyList | null;
},
catchAll?: {
keyList: ProcessedApiAddressKey[];
signedKeyList: FetchedSignedKeyList | null;
}
): Promise<{
addressKTResult?: KeyTransparencyVerificationResult;
catchAllKTResult?: KeyTransparencyVerificationResult;
}> => {
const addressKTStatusPromise = verifyPublicKeys(
address.keyList,
email,
address.signedKeyList,
api,
saveSKLToLS,
getLatestEpoch,
skipVerificationOfExternalDomains
);
let catchAllKTStatusPromise: Promise<KeyTransparencyVerificationResult> | undefined;
if (address.keyList.length == 0 || catchAll) {
catchAllKTStatusPromise = verifyPublicKeys(
catchAll?.keyList ?? [],
email,
catchAll?.signedKeyList ?? null,
api,
saveSKLToLS,
getLatestEpoch,
skipVerificationOfExternalDomains,
true
);
}
const [addressKTStatus, catchAllKTStatus] = await Promise.all([addressKTStatusPromise, catchAllKTStatusPromise]);
return {
addressKTResult: addressKTStatus,
catchAllKTResult: catchAllKTStatus,
};
};
| 7,394
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/verifyProofs.ts
|
import { CryptoProxy } from '@proton/crypto';
import { arrayToHexString, binaryStringToArray, hexStringToArray } from '@proton/crypto/lib/utils';
import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email';
import { FetchedSignedKeyList } from '@proton/shared/lib/interfaces';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
import { KT_DOMAINS, KT_LEN, LEFT_N, vrfHexKeyDev, vrfHexKeyProd } from '../constants/constants';
import { getBaseDomain, throwKTError } from '../helpers/utils';
import { KTPROOF_TYPE, Proof } from '../interfaces';
import { vrfVerify } from './vrf';
/**
* Pick the correct VRF key based on the domain
*/
const getVRFKey = () => hexStringToArray(getBaseDomain() === KT_DOMAINS.PROD ? vrfHexKeyProd : vrfHexKeyDev);
/**
* Verify the VRF proof given by the server for a specific email address
*/
const verifyVRFProof = async (proof: Proof, email: string) => {
try {
const vrfHash = await vrfVerify(
binaryStringToArray(canonicalizeInternalEmail(email)),
hexStringToArray(proof.Verifier),
getVRFKey()
);
return vrfHash;
} catch (error: any) {
const isProxyError = error instanceof Error && error.message.includes('CryptoProxy: endpoint not initialized');
if (isProxyError) {
throw error;
}
return throwKTError('VRF proof verification failed', { email, verifier: proof.Verifier, cause: error });
}
};
const getMerkleTreePath = (vrfHash: Uint8Array, revision: number): Uint8Array => {
return mergeUint8Arrays([
vrfHash.subarray(0, 28),
new Uint8Array([revision >>> 24, revision >>> 18, revision >>> 8, revision]),
]);
};
/**
* Verify the given leafValue exists in the provided chain of the Merkle Tree.
* The leafValue defaults to the empty node if not provided, which is used in
* Proofs of Absence. The incompleteHashing parameter informs whether to start
* hashing only after the first non-null neighbor or from the very beginning
*/
const verifyNeighbors = async (
Neighbors: (string | null)[],
TreeHash: string,
vrfHash: Uint8Array,
email: string,
revision: number,
proofType: KTPROOF_TYPE,
leafValue: Uint8Array = new Uint8Array(KT_LEN).fill(0),
incompleteHashing: boolean = true
) => {
if (Neighbors.length !== KT_LEN * 8) {
return throwKTError('Inconsistent number of neighbors', {
neighborsLength: Neighbors.length,
});
}
const key = getMerkleTreePath(vrfHash, revision);
const emptyNode = new Uint8Array(KT_LEN);
let startHashing = false;
for (let i = Neighbors.length - 1; i >= 0; i--) {
const neighborToCheck = Neighbors[i];
// Don't hash as long as initial neighbours are null, but only if incompleteHashing
// is set to true
if (incompleteHashing && !startHashing && neighborToCheck === null) {
continue;
}
startHashing = true;
const bit = (key[Math.floor(i / 8)] >>> (8 - (i % 8) - 1)) & 1;
let neighbor = emptyNode;
if (neighborToCheck !== null) {
neighbor = hexStringToArray(neighborToCheck);
}
const toHash =
bit === LEFT_N ? mergeUint8Arrays([neighbor, leafValue]) : mergeUint8Arrays([leafValue, neighbor]);
leafValue = await CryptoProxy.computeHash({
algorithm: 'SHA256',
data: toHash,
});
}
if (arrayToHexString(leafValue) !== TreeHash) {
return throwKTError('Hash chain does not result in TreeHash', {
Neighbors: JSON.stringify(Neighbors),
TreeHash,
vrfHash: arrayToHexString(vrfHash),
leafValue: arrayToHexString(leafValue),
incompleteHashing,
email,
proofType,
revision,
});
}
};
/**
* Verify an address is not in KT by checking the Merkle Tree from the leaf 00...000. It only
* starts hashing from the first non-null neighbour from the bottom of the tree
*/
export const verifyProofOfAbsenceForRevision = async (
proof: Proof,
email: string,
TreeHash: string,
Revision: number
) => {
if (proof.Type !== KTPROOF_TYPE.ABSENCE) {
return throwKTError('Proof type should be of absence', {
email,
proofType: proof.Type,
});
}
const vrfHash = await verifyVRFProof(proof, email);
return verifyNeighbors(proof.Neighbors, TreeHash, vrfHash, email, Revision, proof.Type);
};
/**
* Verify an address is not in KT by checking the Merkle Tree from the leaf 00...000. It only
* starts hashing from the first non-null neighbour from the bottom of the tree
*
*/
export const verifyProofOfAbsenceForAllRevision = async (proof: Proof, email: string, TreeHash: string) => {
await verifyProofOfAbsenceForRevision(proof, email, TreeHash, 0);
proof.Neighbors.slice(224).forEach((neighbor) => {
if (neighbor != null) {
return throwKTError('Revision subtree is not empty', {
Neighbors: JSON.stringify(proof.Neighbors),
});
}
});
};
/**
* Compute the leaf value as the SHA256 of the concatenation of the content,
* either an obsolescence token or a SKL's data, and the revision
*/
const computeLeafValue = async (content: Uint8Array, minEpochID: number): Promise<Uint8Array> => {
return CryptoProxy.computeHash({
algorithm: 'SHA256',
data: mergeUint8Arrays([
await CryptoProxy.computeHash({
algorithm: 'SHA256',
data: content,
}),
new Uint8Array([minEpochID >>> 24, minEpochID >>> 16, minEpochID >>> 8, minEpochID]),
]),
});
};
/**
* Verify proof of obscolescence, i.e. with an ObsolescenceToken instead of a SKL. This also
* entails to verifying that the server didn't place a valid SKL in the ObsolescenceToken field
*/
export const verifyProofOfObsolescence = async (
proof: Proof,
email: string,
TreeHash: string,
signedKeyList: Partial<FetchedSignedKeyList>
) => {
const { Type } = proof;
if (Type !== KTPROOF_TYPE.OBSOLESCENCE) {
return throwKTError('Proof type should be of obsolescence', {
email,
proofType: Type,
});
}
const { ObsolescenceToken, MinEpochID, Revision } = signedKeyList;
if (!ObsolescenceToken || !MinEpochID || !Revision) {
return throwKTError('Obsolescence proof with incomplete information', {
email,
signedKeyList,
});
}
if (!/^[a-f0-9]+$/.test(ObsolescenceToken)) {
return throwKTError('ObsolescenceToken should be an hex string', {
email,
ObsolescenceToken,
});
}
const vrfHash = await verifyVRFProof(proof, email);
const leafValue = await computeLeafValue(binaryStringToArray(ObsolescenceToken), MinEpochID);
await verifyNeighbors(proof.Neighbors, TreeHash, vrfHash, email, Revision, proof.Type, leafValue, false);
};
/**
* Verify the KT proof given by the server for a specific email address
*/
export const verifyProofOfExistence = async (
proof: Proof,
email: string,
TreeHash: string,
signedKeyList: Partial<FetchedSignedKeyList>
) => {
const { Type } = proof;
if (Type !== KTPROOF_TYPE.EXISTENCE) {
return throwKTError('Proof type should be of existence', {
email,
proofType: Type,
});
}
const { Data, MinEpochID, Revision } = signedKeyList;
if (!Data || !MinEpochID || !Revision) {
return throwKTError('Existence proof with incomplete information', {
email,
signedKeyList,
});
}
const vrfHash = await verifyVRFProof(proof, email);
const leafValue = await computeLeafValue(binaryStringToArray(Data), MinEpochID);
await verifyNeighbors(proof.Neighbors, TreeHash, vrfHash, email, Revision, proof.Type, leafValue, false);
};
export const verifyProofOfExistenceOrObsolescence = async (
proof: Proof,
email: string,
TreeHash: string,
signedKeyList: Partial<FetchedSignedKeyList>
) => {
if (proof.Type === KTPROOF_TYPE.EXISTENCE) {
await verifyProofOfExistence(proof, email, TreeHash, signedKeyList);
} else if (proof.Type === KTPROOF_TYPE.OBSOLESCENCE) {
await verifyProofOfObsolescence(proof, email, TreeHash, signedKeyList);
} else {
return throwKTError('Proof type should be of existence or obsolescence', {
email,
proofType: proof.Type,
});
}
};
| 7,395
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/vrf.ts
|
import { CURVE, Point } from '@noble/ed25519';
import { CryptoProxy } from '@proton/crypto';
import { arrayToHexString } from '@proton/crypto/lib/utils';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
import { CO_FACTOR, N, ptLen } from '../constants/constants';
/**
* Convert an Uint8Array representing a scalar to a bigint instance, also swapping endianness
*/
const stringToScalar = (array: Uint8Array) => BigInt(`0x${arrayToHexString(array.reverse())}`);
/**
* Convert a ptLen-octet Uint8Array to EC point, according to section 5.1.3 of rfc8032.
* It returns null if the octet string does not convert to a valid EC point
*/
const stringToPoint = (array: Uint8Array) => {
if (array.length !== ptLen) {
throw new Error('Input length is inconsistent for conversion to point');
}
return Point.fromHex(array);
};
/**
* Parse a VRF proof, according to section 5.4.4, ECVRF Decode Proof, of draft-irtf-cfrg-vrf-10
*/
const decodeProof = (pi: Uint8Array) => {
if (pi.length !== 2 * ptLen + N) {
throw new Error('Inconsistent proof length');
}
const Gamma = stringToPoint(pi.slice(0, ptLen));
const c = stringToScalar(pi.slice(ptLen, ptLen + N));
const s = stringToScalar(pi.slice(ptLen + N, 2 * ptLen + N));
if (s >= CURVE.P) {
throw new Error('Scalar from proof out of range');
}
return { Gamma, c, s };
};
/**
* Hash strings to an EC point, according to section 5.4.1.1, ECVRF_hash_to_curve_try_and_increment, of
* draft-irtf-cfrg-vrf-10. It is instantiated for ECVRF-EDWARDS25519-SHA512-TAI according to section 5.5
*/
const hashToCurveTAI = async (alpha: Uint8Array, Y: Uint8Array) => {
for (let ctr = 0x00; ctr <= 0xff; ctr++) {
const hash = await CryptoProxy.computeHash({
algorithm: 'SHA512',
data: mergeUint8Arrays([new Uint8Array([0x03, 0x01]), Y, alpha, new Uint8Array([ctr, 0x00])]),
});
let H: Point;
try {
H = stringToPoint(hash.slice(0, ptLen));
} catch (error: any) {
continue;
}
if (!H.equals(Point.BASE)) {
return H.multiply(CO_FACTOR);
}
}
throw new Error('Hashing to curve failed to generate a valid point');
};
/**
* Hash several points together, according to section 5.4.3, ECVRF Hash Points, of
* draft-irtf-cfrg-vrf-10
*/
const hashPoints = async (...points: Point[]) => {
const digest = await CryptoProxy.computeHash({
algorithm: 'SHA512',
data: mergeUint8Arrays([
new Uint8Array([0x03, 0x02]),
...points.map((p) => p.toRawBytes()),
new Uint8Array([0x00]),
]),
});
return stringToScalar(digest.slice(0, N));
};
/**
* Hash the VRF proof, according to section 5.2, ECVRF Proof to Hash, of
* draft-irtf-cfrg-vrf-10
*/
const proofToHash = async (Gamma: Point) =>
CryptoProxy.computeHash({
algorithm: 'SHA512',
data: mergeUint8Arrays([
new Uint8Array([0x03, 0x03]),
Gamma.multiply(CO_FACTOR).toRawBytes(),
new Uint8Array([0x00]),
]),
});
/**
* VRF verify a proof, according to section 5.3, ECVRF Verifying, of draft-irtf-cfrg-vrf-10
*/
export const vrfVerify = async (alpha: Uint8Array, pi: Uint8Array, vrfHexKey: Uint8Array) => {
const Y = stringToPoint(vrfHexKey);
const H = await hashToCurveTAI(alpha, vrfHexKey);
const D = decodeProof(pi);
const { Gamma, c, s } = D;
const U = Point.BASE.multiply(s).subtract(Y.multiply(c));
const V = H.multiply(s).subtract(Gamma.multiply(c));
const cPrime = await hashPoints(H, Gamma, U, V);
if (cPrime !== c) {
throw new Error('Verification failed');
}
return proofToHash(Gamma);
};
| 7,396
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/self-audit/addressAudit.ts
|
import { CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import { KEY_FLAG } from '@proton/shared/lib/constants';
import { hasBit } from '@proton/shared/lib/helpers/bitset';
import {
ActiveSignedKeyList,
Address,
Api,
DecryptedAddressKey,
FetchedSignedKeyList,
KeyPair,
SaveSKLToLS,
UploadMissingSKL,
} from '@proton/shared/lib/interfaces';
import { getSignedKeyListSignature } from '@proton/shared/lib/keys';
import isTruthy from '@proton/utils/isTruthy';
import {
fetchProof,
fetchSignedKeyLists,
fetchVerifiedEpoch,
updateSignedKeyListSignature,
uploadVerifiedEpoch,
} from '../../helpers/apiHelpers';
import { KeyTransparencyError, throwKTError } from '../../helpers/utils';
import {
AddressAuditResult,
AddressAuditStatus,
AddressAuditWarningReason,
Epoch,
VerifiedEpoch,
} from '../../interfaces';
import { checkKeysInSKL, verifySKLSignature } from '../verifyKeys';
import {
verifyProofOfAbsenceForAllRevision,
verifyProofOfAbsenceForRevision,
verifyProofOfObsolescence,
} from '../verifyProofs';
import { SKLAuditResult, SKLAuditStatus, auditSKL } from './sklAudit';
const millisecondsToSeconds = (milliseconds: number) => Math.floor(milliseconds / 1000);
const secondsToMilliseconds = (seconds: number) => seconds * 1000;
const findLastIncludedSKL = (newSKLs: FetchedSignedKeyList[], epoch: Epoch): FetchedSignedKeyList | null => {
const includedSKLs = newSKLs.filter(({ MinEpochID }) => MinEpochID !== null && MinEpochID <= epoch.EpochID);
if (includedSKLs.length) {
return includedSKLs.reduce((maxRevisionSKL, currentSKL) => {
if (maxRevisionSKL.Revision > currentSKL.Revision) {
return maxRevisionSKL;
}
return currentSKL;
});
}
return null;
};
// Both bounds are included
const range = (begin: number, end: number) => {
if (begin > end) {
return [];
}
return [...Array(end - begin + 1).keys()].map((i) => begin + i);
};
const isMonotonicallyIncreasing = <T>(elements: T[], start: T): boolean => {
var lowerBound = start;
for (const element of elements) {
if (element < lowerBound) {
return false;
}
lowerBound = element;
}
return true;
};
const uploadNewVerifiedEpoch = async (
sklAudits: SKLAuditResult[],
epoch: Epoch,
address: Address,
userPrimaryKey: PrivateKeyReference,
api: Api
) => {
if (sklAudits.length) {
const maxRevisionAudit = sklAudits[sklAudits.length - 1];
if (maxRevisionAudit.status === SKLAuditStatus.ExistentVerified) {
await uploadVerifiedEpoch(
{
EpochID: epoch.EpochID,
Revision: maxRevisionAudit.revision,
SKLCreationTime: millisecondsToSeconds(+maxRevisionAudit.sklCreationTimestamp!),
},
address.ID,
userPrimaryKey,
api
);
}
}
};
const earlyTermination = async (
verifiedEpoch: VerifiedEpoch,
epoch: Epoch,
address: Address,
inputSKL: ActiveSignedKeyList,
userPrimaryKey: PrivateKeyReference,
api: Api
) => {
if (verifiedEpoch.EpochID === epoch.EpochID) {
return true;
}
if (verifiedEpoch.Revision === inputSKL.Revision) {
const proof = await fetchProof(epoch.EpochID, address.Email, inputSKL.Revision + 1, api);
await verifyProofOfAbsenceForRevision(proof, address.Email, epoch.TreeHash, inputSKL.Revision + 1);
await uploadVerifiedEpoch(
{
EpochID: epoch.EpochID,
Revision: verifiedEpoch.Revision,
SKLCreationTime: verifiedEpoch.SKLCreationTime,
},
address.ID,
userPrimaryKey,
api
);
return true;
}
return false;
};
const successOrWarning = (email: string, sklAudits: SKLAuditResult[], signatureWasInTheFuture: boolean) => {
const addressWasDisabled = sklAudits.filter((audit) => audit.status === SKLAuditStatus.Obsolete).length != 0;
const numberOfFailedSig = sklAudits.filter((audit) => audit.status === SKLAuditStatus.ExistentUnverified).length;
/**
* If the SKL sig was in the future (and got fixed), then we don't show a warning.
*/
const sklVerificationFailed = numberOfFailedSig > 1 || (numberOfFailedSig == 1 && !signatureWasInTheFuture);
if (addressWasDisabled || sklVerificationFailed) {
return {
email,
status: AddressAuditStatus.Warning,
warningDetails: {
reason: AddressAuditWarningReason.UnverifiableHistory,
addressWasDisabled,
sklVerificationFailed,
},
};
}
return { email, status: AddressAuditStatus.Success };
};
/**
* Some SKL will fail verification because
* they were signed with a time in the future.
* In this case we resign them.
*/
const checkAndFixSKLInTheFuture = async (address: Address, primaryAddressKey: PrivateKeyReference, api: Api) => {
const { Email, ID, SignedKeyList } = address;
const { Revision, Data, Signature } = SignedKeyList!;
if (Revision === 1) {
const signatureIsInTheFuture = await verifySKLSignature(
[primaryAddressKey],
Data,
Signature,
new Date(0xffffffff * 1000) // max date in the future
);
if (signatureIsInTheFuture) {
const newSignature = await getSignedKeyListSignature(Data, primaryAddressKey);
await updateSignedKeyListSignature(ID, Revision, newSignature, api);
return;
}
}
return throwKTError('Input SKL signature was not verified', { email: Email, inputSKL: SignedKeyList });
};
/**
* An admin can create an address with no keys that cannot be audited
* we verify the absence or obsolescence proof, and will warn the user in
* in the UI.
*/
const checkAddressWithNoKeys = async (epoch: Epoch, address: Address, api: Api, saveSKLToLS: SaveSKLToLS) => {
const inputSKL = address.SignedKeyList;
const revisionToCheck = inputSKL?.Revision ?? 1;
const proof = await fetchProof(epoch.EpochID, address.Email, revisionToCheck, api);
if (!inputSKL) {
await verifyProofOfAbsenceForAllRevision(proof, address.Email, epoch.TreeHash);
return;
}
if (!inputSKL.ObsolescenceToken) {
return throwKTError('Expected an obsolescence token for an address without keys', {
inputSKL,
});
}
// If MinEpochID is not set, the SKL is not yet included in KT.
if (!inputSKL.MinEpochID) {
if (!inputSKL.Revision || !inputSKL.ExpectedMinEpochID) {
return throwKTError('Expected an ExpectedMinEpochID and Revision', {
inputSKL,
});
}
await saveSKLToLS(
address.Email,
inputSKL.ObsolescenceToken!,
inputSKL.Revision!,
inputSKL.ExpectedMinEpochID!,
address.ID,
false
);
return;
}
// Check that proof is a valid obsolescence proof.
await verifyProofOfObsolescence(proof, address.Email, epoch.TreeHash, inputSKL);
// The proof of the next revision must be an absence proof.
const absenceProof = await fetchProof(epoch.EpochID, address.Email, revisionToCheck + 1, api);
await verifyProofOfAbsenceForRevision(absenceProof, address.Email, epoch.TreeHash, revisionToCheck + 1);
};
const auditAddressImplementation = async (
address: Address,
userKeys: KeyPair[],
addressKeys: DecryptedAddressKey[],
epoch: Epoch,
saveSKLToLS: SaveSKLToLS,
api: Api,
uploadMissingSKL: UploadMissingSKL
): Promise<AddressAuditResult> => {
const inputSKL = address.SignedKeyList;
const email = address.Email;
if (address.Keys.length === 0) {
await checkAddressWithNoKeys(epoch, address, api, saveSKLToLS);
return {
email,
status: AddressAuditStatus.Warning,
warningDetails: {
reason: AddressAuditWarningReason.AddressWithNoKeys,
},
};
}
if (inputSKL === null) {
await uploadMissingSKL(address, epoch, saveSKLToLS);
return {
email,
status: AddressAuditStatus.Success,
};
}
if (!inputSKL.Revision) {
return throwKTError('Input SKL has no revision set', { email, inputSKL });
}
if (!userKeys.length) {
return throwKTError('Account key list was empty', { email });
}
const userPrimaryKey = userKeys[0].privateKey;
const userVerificationKeys = userKeys.map(({ publicKey }) => publicKey);
const verifiedEpoch = await fetchVerifiedEpoch(address, api, userVerificationKeys);
if (verifiedEpoch && (await earlyTermination(verifiedEpoch, epoch, address, inputSKL, userPrimaryKey, api))) {
return { email, status: AddressAuditStatus.Success };
}
const verifiedRevision = verifiedEpoch?.Revision ?? 0;
const newSKLs = await fetchSignedKeyLists(api, verifiedEpoch?.Revision ?? 0, email);
const lastIncludedRevision = findLastIncludedSKL(newSKLs, epoch)?.Revision ?? verifiedRevision;
const proofs = await Promise.all(
range(verifiedRevision + 1, lastIncludedRevision + 1).map((revision) => {
const proofPromise = fetchProof(epoch.EpochID, email, revision, api);
return proofPromise.then((proof) => {
return { revision, proof };
});
})
);
const addressVerificationKeys = addressKeys
.filter(({ Flags }) => hasBit(Flags, KEY_FLAG.FLAG_NOT_COMPROMISED))
.map(({ publicKey }) => publicKey);
const sklAudits = await Promise.all(
range(verifiedRevision + 1, lastIncludedRevision).map((revision) => {
const skl = newSKLs.find((skl) => skl.Revision == revision);
const proof = proofs.find(({ revision: proofRevision }) => proofRevision == revision)?.proof!;
return auditSKL(email, addressVerificationKeys, revision, skl ?? null, epoch, proof);
})
);
const minEpochIDs = newSKLs.map((skl) => skl.MinEpochID).filter((minEpochID) => minEpochID != null);
const minEpochIDsIncrease = isMonotonicallyIncreasing(minEpochIDs, verifiedEpoch?.EpochID ?? 0);
if (!minEpochIDsIncrease) {
return throwKTError('MinEpochIDs are not increasing', { email, minEpochIDs });
}
const sklCreationTimestamps = sklAudits
.map(({ sklCreationTimestamp }) => sklCreationTimestamp)
.filter((timestamp) => timestamp !== undefined);
const sklCreationTimestampsIncrease = isMonotonicallyIncreasing(
sklCreationTimestamps,
new Date(secondsToMilliseconds(verifiedEpoch?.SKLCreationTime ?? 0))
);
if (!sklCreationTimestampsIncrease) {
return throwKTError('SKL timestamps are not increasing', { email, sklCreationTimestamps });
}
const nextRevisionProof = proofs.find(({ revision }) => revision === lastIncludedRevision + 1)?.proof!;
await verifyProofOfAbsenceForRevision(nextRevisionProof, email, epoch.TreeHash, lastIncludedRevision + 1);
const audit = sklAudits.find(({ revision }) => revision === inputSKL.Revision);
let signatureWasInTheFuture = false;
if (audit) {
if (audit.signedKeyList?.Data !== inputSKL.Data) {
return throwKTError('Audited SKL doesnt match the input SKL', { email, inputSKL });
}
if (audit.status !== SKLAuditStatus.ExistentVerified) {
const primaryAddressKey = addressKeys[0].privateKey;
await checkAndFixSKLInTheFuture(address, primaryAddressKey, api);
signatureWasInTheFuture = true;
}
} else {
const verified = await verifySKLSignature(addressVerificationKeys, inputSKL.Data, inputSKL.Signature);
if (verified === null) {
const primaryAddressKey = addressKeys[0].privateKey;
await checkAndFixSKLInTheFuture(address, primaryAddressKey, api);
signatureWasInTheFuture = true;
}
const expectedMinEpochID = inputSKL.MinEpochID ?? inputSKL.ExpectedMinEpochID;
if (!expectedMinEpochID) {
return throwKTError('Input SKL has not minEpochID or expectedMinEpochID', { email, inputSKL });
}
await saveSKLToLS(email, inputSKL.Data, inputSKL.Revision, expectedMinEpochID, address.ID);
}
const addressKeysWithoutForwarding = (
await Promise.all(
addressKeys.map(async ({ Flags, privateKey, Primary }) => {
const result = await CryptoProxy.isE2EEForwardingKey({ key: privateKey });
return result ? false : { flags: Flags, key: privateKey, primary: Primary };
})
)
).filter(isTruthy);
await checkKeysInSKL(email, addressKeysWithoutForwarding, inputSKL.Data);
await uploadNewVerifiedEpoch(sklAudits, epoch, address, userPrimaryKey, api);
return successOrWarning(email, sklAudits, signatureWasInTheFuture);
};
export const auditAddress = async (
address: Address,
userKeys: KeyPair[],
addressKeys: DecryptedAddressKey[],
epoch: Epoch,
saveSKLToLS: SaveSKLToLS,
api: Api,
uploadMissingSKL: UploadMissingSKL
): Promise<AddressAuditResult> => {
try {
return await auditAddressImplementation(
address,
userKeys,
addressKeys,
epoch,
saveSKLToLS,
api,
uploadMissingSKL
);
} catch (error: any) {
if (error instanceof KeyTransparencyError) {
return { email: address.Email, status: AddressAuditStatus.Failure, error };
}
throw error;
}
};
| 7,397
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/self-audit/index.ts
|
export * from './selfAudit';
| 7,398
|
0
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification
|
petrpan-code/ProtonMail/WebClients/packages/key-transparency/lib/verification/self-audit/selfAudit.ts
|
import { serverTime } from '@proton/crypto';
import { getIsAddressDisabled } from '@proton/shared/lib/helpers/address';
import { Api, KTLocalStorageAPI, SaveSKLToLS, SelfAuditState, UploadMissingSKL } from '@proton/shared/lib/interfaces';
import { getSelfAuditInterval } from '../../helpers';
import { SelfAuditResult } from '../../interfaces';
import { auditAddress } from './addressAudit';
import { checkLSBlobs } from './verifyLocalStorage';
/**
* Audit both the user's own SKLs and any SKL the user has used
* to send messages to
*/
export const selfAudit = async (
userID: string,
state: SelfAuditState,
api: Api,
ktLSAPI: KTLocalStorageAPI,
saveSKLToLS: SaveSKLToLS,
uploadMissingSKL: UploadMissingSKL
): Promise<SelfAuditResult> => {
const userPrivateKeys = state.userKeys.map(({ privateKey }) => privateKey);
const ownEmails = state.addresses.map(({ address }) => address.Email);
const localStorageAuditResults = await checkLSBlobs(userID, userPrivateKeys, ktLSAPI, state.epoch, api);
const localStorageAuditResultsOwnAddress = localStorageAuditResults.filter(({ email }) =>
ownEmails.includes(email)
);
const localStorageAuditResultsOtherAddress = localStorageAuditResults.filter(
({ email }) => !ownEmails.includes(email)
);
const addressAuditResults = await Promise.all(
state.addresses
.filter(({ address }) => !getIsAddressDisabled(address))
.map((address) => {
return auditAddress(
address.address,
state.userKeys,
address.addressKeys,
state.epoch,
saveSKLToLS,
api,
uploadMissingSKL
);
})
);
const currentTime = +serverTime();
return {
auditTime: currentTime,
nextAuditTime: currentTime + getSelfAuditInterval(),
addressAuditResults,
localStorageAuditResultsOwnAddress,
localStorageAuditResultsOtherAddress,
};
};
| 7,399
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.