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/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/auth.ts
|
/* eslint-disable @typescript-eslint/no-throw-literal */
import { SSO_URL } from 'proton-pass-extension/app/config';
import { c } from 'ttag';
import { AccountForkResponse, getAccountForkResponsePayload } from '@proton/pass/lib/auth/fork';
import {
type AuthService,
type AuthServiceConfig,
createAuthService as createCoreAuthService,
} from '@proton/pass/lib/auth/service';
import { clientLocked, clientReady } from '@proton/pass/lib/client';
import type { MessageHandlerCallback } from '@proton/pass/lib/extension/message';
import browser from '@proton/pass/lib/globals/browser';
import { sessionUnlockFailure, sessionUnlockIntent, sessionUnlockSuccess } from '@proton/pass/store/actions';
import { selectUser } from '@proton/pass/store/selectors';
import type { WorkerMessageResponse } from '@proton/pass/types';
import { SessionLockStatus, WorkerMessageType } from '@proton/pass/types';
import { withPayload } from '@proton/pass/utils/fp/lens';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import { PASS_APP_NAME } from '@proton/shared/lib/constants';
import noop from '@proton/utils/noop';
import WorkerMessageBroker from '../channel';
import { withContext } from '../context';
import store from '../store';
export const SESSION_LOCK_ALARM = 'alarm::session-lock';
export const createAuthService = (options: AuthServiceConfig): AuthService => {
const authService = createCoreAuthService(options);
const handleAccountFork = withContext<MessageHandlerCallback<WorkerMessageType.ACCOUNT_FORK>>(
async (ctx, { payload }) => {
if (ctx.getState().loggedIn) throw getAccountForkResponsePayload(AccountForkResponse.CONFLICT);
try {
await authService.consumeFork({ mode: 'secure', ...payload }, `${SSO_URL}/api`);
if (clientLocked(ctx.status)) await ctx.service.storage.session.set(options.authStore.getSession());
return getAccountForkResponsePayload(AccountForkResponse.SUCCESS);
} catch (error: unknown) {
authService.logout({ soft: true }).catch(noop);
const additionalMessage = error instanceof Error ? error.message : '';
options.onNotification?.(c('Warning').t`Unable to sign in to ${PASS_APP_NAME}. ${additionalMessage}`);
throw getAccountForkResponsePayload(AccountForkResponse.ERROR, error);
}
}
);
const handleUnlockRequest = (request: { pin: string }) =>
new Promise<WorkerMessageResponse<WorkerMessageType.UNLOCK_REQUEST>>((resolve) => {
store.dispatch(
sessionUnlockIntent({ pin: request.pin }, (action) => {
if (sessionUnlockSuccess.match(action)) return resolve({ ok: true });
if (sessionUnlockFailure.match(action)) return resolve({ ok: false, ...action.payload });
})
);
});
/* only extend the session lock if a lock is registered and we've reached at least 50%
* of the lock TTL since the last extension. Calling `AuthService::syncLock` will extend
* the lock via the `checkSessionLock` call */
const handleActivityProbe = withContext<MessageHandlerCallback<WorkerMessageType.ACTIVITY_PROBE>>(
async ({ status }) => {
const registeredLock = options.authStore.getLockStatus() === SessionLockStatus.REGISTERED;
const ttl = options.authStore.getLockTTL();
if (clientReady(status) && registeredLock && ttl) {
const now = getEpoch();
const diff = now - (options.authStore.getLockLastExtendTime() ?? 0);
if (diff > ttl * 0.5) await authService.checkLock();
}
return true;
}
);
const resolveUserData = () => ({ user: selectUser(store.getState()) });
WorkerMessageBroker.registerMessage(WorkerMessageType.ACCOUNT_FORK, handleAccountFork);
WorkerMessageBroker.registerMessage(WorkerMessageType.UNLOCK_REQUEST, withPayload(handleUnlockRequest));
WorkerMessageBroker.registerMessage(WorkerMessageType.ACTIVITY_PROBE, handleActivityProbe);
WorkerMessageBroker.registerMessage(WorkerMessageType.RESOLVE_USER_DATA, resolveUserData);
browser.alarms.onAlarm.addListener(({ name }) => name === SESSION_LOCK_ALARM && authService.lock({ soft: false }));
return authService;
};
| 4,400
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/autofill.ts
|
import WorkerMessageBroker from 'proton-pass-extension/app/worker/channel';
import { onContextReady, withContext } from 'proton-pass-extension/app/worker/context';
import store from 'proton-pass-extension/app/worker/store';
import { setPopupIconBadge } from 'proton-pass-extension/lib/utils/popup-icon';
import { isContentScriptPort } from 'proton-pass-extension/lib/utils/port';
import { DEFAULT_RANDOM_PW_OPTIONS } from '@proton/pass/hooks/usePasswordGenerator';
import { clientReady } from '@proton/pass/lib/client';
import browser from '@proton/pass/lib/globals/browser';
import type { SelectAutofillCandidatesOptions } from '@proton/pass/lib/search/types';
import { itemAutofilled } from '@proton/pass/store/actions';
import {
selectAutofillCandidates,
selectItemByShareIdAndId,
selectPopupPasswordOptions,
selectVaultLimits,
selectWritableVaults,
} from '@proton/pass/store/selectors';
import type { Maybe, SafeLoginItem } from '@proton/pass/types';
import { WorkerMessageType } from '@proton/pass/types';
import { prop } from '@proton/pass/utils/fp/lens';
import { deobfuscate } from '@proton/pass/utils/obfuscate/xor';
import { parseSender, parseUrl } from '@proton/pass/utils/url/parser';
import noop from '@proton/utils/noop';
export const createAutoFillService = () => {
const getAutofillCandidates = (options: SelectAutofillCandidatesOptions): SafeLoginItem[] =>
selectAutofillCandidates(options)(store.getState()).map((item) => ({
name: item.data.metadata.name,
username: deobfuscate(item.data.content.username),
itemId: item.itemId,
shareId: item.shareId,
url: item.data.content.urls?.[0],
}));
const getAutofillData = ({
shareId,
itemId,
}: {
shareId: string;
itemId: string;
}): Maybe<{ username: string; password: string }> => {
const state = store.getState();
const item = selectItemByShareIdAndId(shareId, itemId)(state);
if (item !== undefined && item.data.type === 'login') {
store.dispatch(itemAutofilled({ shareId, itemId }));
return {
username: deobfuscate(item.data.content.username),
password: deobfuscate(item.data.content.password),
};
}
};
const updateTabsBadgeCount = withContext(({ status }) => {
if (!clientReady(status)) return;
browser.tabs
.query({ active: true })
.then((tabs) =>
Promise.all(
tabs.map(({ id: tabId, url }) => {
if (tabId) {
const state = store.getState();
const items = getAutofillCandidates(parseUrl(url));
const writableShareIds = selectWritableVaults(state).map(prop('shareId'));
const { didDowngrade } = selectVaultLimits(state);
/* if the user has downgraded : we want to keep the tab badge count
* with the total items matched, but sync the autofillable candidates
* in the content-scripts to be only the ones from the writable vaults */
const count = items.length;
const safeItems = items.filter(
(item) => !didDowngrade || writableShareIds.includes(item.shareId)
);
WorkerMessageBroker.ports.broadcast(
{
type: WorkerMessageType.AUTOFILL_SYNC,
payload: { items: safeItems, needsUpgrade: didDowngrade },
},
isContentScriptPort(tabId)
);
return setPopupIconBadge(tabId, count);
}
})
)
)
.catch(noop);
});
/* Clears badge count for each valid tab
* Triggered on logout detection to avoid
* showing stale counts */
const clearTabsBadgeCount = () => {
browser.tabs
.query({})
.then((tabs) => Promise.all(tabs.map(({ id: tabId }) => tabId && setPopupIconBadge(tabId, 0))))
.catch(noop);
};
WorkerMessageBroker.registerMessage(
WorkerMessageType.AUTOFILL_QUERY,
onContextReady(({ getState }, _, sender) => {
if (!getState().loggedIn) return { items: [], needsUpgrade: false };
const { url, tabId } = parseSender(sender);
const writableShareIds = selectWritableVaults(store.getState()).map(prop('shareId'));
const { didDowngrade } = selectVaultLimits(store.getState());
/* if user has exceeded his vault count limit - this likely means
* has downgraded to a free plan : only allow him to autofill from
* his writable vaults */
const items = getAutofillCandidates({
...url,
...(didDowngrade ? { shareIds: writableShareIds } : {}),
});
if (tabId) void setPopupIconBadge(tabId, items.length);
return { items: tabId !== undefined && items.length > 0 ? items : [], needsUpgrade: didDowngrade };
})
);
WorkerMessageBroker.registerMessage(WorkerMessageType.AUTOFILL_PASSWORD_OPTIONS, () => {
return { options: selectPopupPasswordOptions(store.getState()) ?? DEFAULT_RANDOM_PW_OPTIONS };
});
WorkerMessageBroker.registerMessage(
WorkerMessageType.AUTOFILL_SELECT,
onContextReady(async (_, message) => {
const credentials = getAutofillData(message.payload);
if (credentials === undefined) throw new Error('Could not get credentials for autofill request');
return credentials;
})
);
/* onUpdated will be triggered every time a tab
* has been loaded with a new url : update the
* badge count accordingly */
browser.tabs.onUpdated.addListener(
onContextReady(async (_, tabId, __, tab) => {
if (tabId) {
const items = getAutofillCandidates(parseUrl(tab.url));
return setPopupIconBadge(tabId, items.length);
}
})
);
return { getAutofillCandidates, updateTabsBadgeCount, clearTabsBadgeCount };
};
export type AutoFillService = ReturnType<typeof createAutoFillService>;
| 4,401
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/autosave.ts
|
import { itemCreationIntent, itemCreationSuccess, itemEditIntent, itemEditSuccess } from '@proton/pass/store/actions';
import { selectAutosaveCandidate, selectAutosaveVault } from '@proton/pass/store/selectors';
import type { AutoSavePromptOptions, FormEntry, FormEntryStatus } from '@proton/pass/types';
import { AutoSaveType, WorkerMessageType } from '@proton/pass/types';
import { first } from '@proton/pass/utils/array/first';
import { deobfuscate } from '@proton/pass/utils/obfuscate/xor';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import WorkerMessageBroker from '../channel';
import store from '../store';
export const createAutoSaveService = () => {
const resolvePromptOptions = (submission: FormEntry<FormEntryStatus.COMMITTED>): AutoSavePromptOptions => {
const candidates = selectAutosaveCandidate({
domain: submission.domain,
subdomain: submission.subdomain,
username: submission.data.username,
})(store.getState());
/* If no login items found for the current domain & the current
* username - prompt for autosaving a new entry */
if (candidates.length === 0) return { shouldPrompt: true, data: { action: AutoSaveType.NEW } };
/* If we cannot find an entry which also matches the current submission's
* password then we should prompt for update */
const match = candidates.filter((item) => deobfuscate(item.data.content.password) === submission.data.password);
return match.length > 0
? { shouldPrompt: false }
: {
shouldPrompt: true,
data: {
action: AutoSaveType.UPDATE,
item: first(candidates)!,
},
};
};
WorkerMessageBroker.registerMessage(WorkerMessageType.AUTOSAVE_REQUEST, async ({ payload }) => {
const autosave = payload.submission.autosave.data;
if (autosave.action === AutoSaveType.NEW) {
const selectedVault = selectAutosaveVault(store.getState());
return new Promise<boolean>((resolve) =>
store.dispatch(
itemCreationIntent(
{
...payload.item,
optimisticId: uniqueId(),
shareId: selectedVault.shareId,
createTime: getEpoch(),
extraData: { withAlias: false },
},
(intentResultAction) =>
itemCreationSuccess.match(intentResultAction) ? resolve(true) : resolve(false)
)
)
);
}
if (autosave.action === AutoSaveType.UPDATE) {
const { itemId, shareId, revision: lastRevision } = autosave.item;
return new Promise<boolean>((resolve) =>
store.dispatch(
itemEditIntent({ ...payload.item, itemId, shareId, lastRevision }, (intentResultAction) =>
itemEditSuccess.match(intentResultAction) ? resolve(true) : resolve(false)
)
)
);
}
return false;
});
return { resolvePromptOptions };
};
export type AutoSaveService = ReturnType<typeof createAutoSaveService>;
| 4,402
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/cache-proxy.ts
|
import { api } from '@proton/pass/lib/api/api';
import {
API_PROXY_IMAGE_ENDPOINT,
API_PROXY_KEY,
cleanAPIProxyCache,
clearAPIProxyCache,
handleAPIProxy,
} from '@proton/pass/lib/api/proxy';
import { authentication } from '@proton/pass/lib/auth/store';
import browser from '@proton/pass/lib/globals/browser';
import { selectCanLoadDomainImages } from '@proton/pass/store/selectors';
import { API_URL } from '../../config';
import store from '../store';
export const createCacheProxyService = () => {
const canLoadDomainImages = () => selectCanLoadDomainImages(store.getState());
if (BUILD_TARGET === 'chrome') {
(self as any as ServiceWorkerGlobalScope).onfetch = handleAPIProxy({
apiUrl: API_URL,
apiProxyUrl: browser.runtime.getURL(`${API_PROXY_KEY}/`),
fetch: (url, init) => api<Response>({ url: url.toString(), method: init?.method, output: 'raw' }),
});
return { clean: cleanAPIProxyCache, clear: clearAPIProxyCache };
}
/* Firefox does not support service workers yet : reassess
* this workaround when full MV3 support is released */
if (BUILD_TARGET === 'firefox') {
browser.webRequest.onBeforeSendHeaders.addListener(
(details) => {
const UID = authentication.getUID();
const AccessToken = authentication.getAccessToken();
if (
UID &&
AccessToken &&
canLoadDomainImages() &&
details.url.startsWith(`${API_URL}/${API_PROXY_IMAGE_ENDPOINT}`)
) {
details.requestHeaders?.push({ name: 'x-pm-uid', value: UID });
details.requestHeaders?.push({ name: 'Authorization', value: `Bearer ${AccessToken}` });
}
return { requestHeaders: details.requestHeaders };
},
{ urls: [`${API_URL}/*/*`] },
['blocking', 'requestHeaders']
);
}
return {};
};
export type CacheProxyService = ReturnType<typeof createCacheProxyService>;
| 4,403
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/export.ts
|
import { createExportZip, decryptZip, encryptZip } from '@proton/pass/lib/export/export';
import type { ExportPayload } from '@proton/pass/lib/export/types';
import { deobfuscateItem } from '@proton/pass/lib/items/item.obfuscation';
import { unwrapOptimisticState } from '@proton/pass/store/optimistic/utils/transformers';
import { selectShareOrThrow, selectUser } from '@proton/pass/store/selectors';
import { SessionLockStatus, type VaultShareContent, WorkerMessageType } from '@proton/pass/types';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import * as config from '../../config';
import WorkerMessageBroker from '../channel';
import { onContextReady } from '../context';
import store from '../store';
export const createExportService = () => {
const getExportData = async (encrypted: boolean): Promise<ExportPayload> => {
const state = store.getState();
const itemsByShareId = unwrapOptimisticState(state.items.byShareId);
const user = selectUser(state);
const vaults = Object.fromEntries(
Object.entries(itemsByShareId).map(([shareId, itemsById]) => {
const share = selectShareOrThrow(shareId)(state);
return [
shareId,
{
...(share.content as VaultShareContent),
items: Object.values(itemsById).map((item) => ({
itemId: item.itemId,
shareId: item.shareId,
data: deobfuscateItem(item.data),
state: item.state,
aliasEmail: item.aliasEmail,
contentFormatVersion: item.contentFormatVersion,
createTime: item.createTime,
modifyTime: item.modifyTime,
})),
},
];
})
);
return {
version: config.APP_VERSION,
userId: user?.ID,
encrypted,
vaults,
};
};
WorkerMessageBroker.registerMessage(
WorkerMessageType.EXPORT_REQUEST,
onContextReady(async (ctx, { payload }) => {
const lock = await ctx.service.auth.checkLock();
if (lock.status === SessionLockStatus.LOCKED) throw Error('Session locked');
const exportData = await getExportData(payload.encrypted);
const zip = await createExportZip(exportData);
return {
data: payload.encrypted ? await encryptZip(zip, payload.passphrase) : uint8ArrayToBase64String(zip),
};
})
);
WorkerMessageBroker.registerMessage(
WorkerMessageType.EXPORT_DECRYPT,
async ({ payload: { data, passphrase } }) => ({ data: await decryptZip(data, passphrase) })
);
return {};
};
export type ExportService = ReturnType<typeof createExportService>;
| 4,404
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/form.tracker.ts
|
import type { FormEntry, FormIdentifier, Maybe, TabId, WithAutoSavePromptOptions } from '@proton/pass/types';
import { FormEntryStatus, WorkerMessageType } from '@proton/pass/types';
import { logger } from '@proton/pass/utils/logger';
import { merge } from '@proton/pass/utils/object/merge';
import { requestHasBodyFormData } from '@proton/pass/utils/requests';
import { parseSender } from '@proton/pass/utils/url/parser';
import { isFormEntryCommittable, isFormEntryCommitted } from '../../../lib/utils/form-entry';
import WorkerMessageBroker from '../channel';
import { withContext } from '../context';
import { createMainFrameRequestTracker } from './main-frame.tracker';
import { createXMLHTTPRequestTracker } from './xmlhttp-request.tracker';
const isPartialFormData = ({ type, data }: Pick<FormEntry, 'data' | 'type'>): boolean => {
switch (type) {
case 'login':
case 'register': {
return !(data.username?.trim() && data.password?.trim());
}
default:
return false;
}
};
const getFormId = (tabId: TabId, domain: string): FormIdentifier => `${tabId}:${domain}`;
export const createFormTrackerService = () => {
const submissions: Map<FormIdentifier, FormEntry> = new Map();
const get = (tabId: TabId, domain: string): Maybe<FormEntry> => {
const submission = submissions.get(getFormId(tabId, domain));
if (submission && submission.domain === domain) return submission;
};
const stash = (tabId: TabId, domain: string, reason: string): void => {
const formId = getFormId(tabId, domain);
if (submissions.has(formId)) {
logger.info(`[FormTracker::Stash]: on tab ${tabId} for domain "${domain}" {${reason}}`);
submissions.delete(formId);
}
};
const stage = (tabId: TabId, submission: Omit<FormEntry, 'status' | 'partial'>, reason: string): FormEntry => {
logger.info(`[FormTracker::Stage]: on tab ${tabId} for domain "${submission.domain}" {${reason}}`);
const formId = getFormId(tabId, submission.domain);
const pending = submissions.get(formId);
if (pending !== undefined && pending.status === FormEntryStatus.STAGING) {
/* do not override empty values when merging in order to properly
* support multi-step forms which may have partial data on each step */
const update = merge(pending, { ...submission, status: FormEntryStatus.STAGING }, { excludeEmpty: true });
const staging = merge(update, { partial: isPartialFormData(update) });
submissions.set(formId, staging);
return staging;
}
const staging = merge(submission, {
status: FormEntryStatus.STAGING,
partial: isPartialFormData(submission),
}) as FormEntry;
submissions.set(formId, staging);
return staging;
};
const commit = (tabId: TabId, domain: string, reason: string): Maybe<FormEntry<FormEntryStatus.COMMITTED>> => {
const formId = getFormId(tabId, domain);
const pending = submissions.get(formId);
if (pending !== undefined && pending.status === FormEntryStatus.STAGING) {
logger.info(`[FormTracker::Commit] on tab ${tabId} for domain "${domain}" {${reason}}`);
const commit = merge(pending, { status: FormEntryStatus.COMMITTED });
if (isFormEntryCommittable(commit)) {
submissions.set(formId, commit);
return commit;
}
}
};
createMainFrameRequestTracker({
onTabDelete: (tabId) => {
submissions.forEach((_, key) => {
if (key.startsWith(tabId.toString())) {
const [tabId, domain] = key.split(':');
stash(parseInt(tabId, 10), domain, 'TAB_DELETED');
}
});
},
onTabError: (tabId, domain) => domain && stash(tabId, domain, 'TAB_ERRORED'),
});
/* TODO: on failed request we should send out
* a message to the content-script : we should stash
* only if there was a recent form submission - if
* we directly stash we might get false positives */
createXMLHTTPRequestTracker({
acceptRequest: requestHasBodyFormData,
onFailedRequest: ({ tabId, domain }) => {
const submission = get(tabId, domain);
if (submission && submission.status === FormEntryStatus.STAGING) {
stash(tabId, domain, 'XMLHTTP_ERROR_DETECTED');
}
},
});
WorkerMessageBroker.registerMessage(
WorkerMessageType.FORM_ENTRY_STAGE,
withContext((ctx, { payload }, sender) => {
const { type, data } = payload;
if (ctx.getState().loggedIn) {
const { tabId, url } = parseSender(sender);
if (url.domain) {
return {
staged: stage(
tabId,
{
domain: url.domain,
subdomain: url.subdomain,
type,
data,
},
payload.reason
),
};
}
}
throw new Error('Cannot stage submission while logged out');
})
);
WorkerMessageBroker.registerMessage(
WorkerMessageType.FORM_ENTRY_STASH,
withContext((ctx, { payload: { reason } }, sender) => {
if (ctx.getState().loggedIn) {
const { tabId, url } = parseSender(sender);
if (url.domain) {
stash(tabId, url.domain, reason);
return true;
}
}
return false;
})
);
WorkerMessageBroker.registerMessage(
WorkerMessageType.FORM_ENTRY_COMMIT,
withContext((ctx, { payload: { reason } }, sender) => {
if (ctx.getState().loggedIn) {
const { tabId, url } = parseSender(sender);
if (url.domain) {
const committed = commit(tabId, url.domain, reason);
if (committed !== undefined) {
const promptOptions = ctx.service.autosave.resolvePromptOptions(committed);
return promptOptions.shouldPrompt
? { committed: merge(committed, { autosave: promptOptions }) }
: (() => {
stash(tabId, url.domain, 'PROMPT_IGNORE');
return { committed: undefined };
})();
}
throw new Error(`Cannot commit form submission for tab#${tabId} on domain "${url.domain}"`);
}
}
throw new Error('Cannot commit submission while logged out');
})
);
WorkerMessageBroker.registerMessage(
WorkerMessageType.FORM_ENTRY_REQUEST,
withContext((ctx, _, sender) => {
if (ctx.getState().loggedIn) {
const { tabId, url } = parseSender(sender);
if (url.domain) {
const submission = get(tabId, url.domain);
const isCommitted = submission !== undefined && isFormEntryCommitted(submission);
return {
submission:
submission !== undefined
? (merge(submission, {
autosave: isCommitted
? ctx.service.autosave.resolvePromptOptions(submission)
: { shouldPrompt: false },
}) as WithAutoSavePromptOptions<FormEntry>)
: submission,
};
}
}
return { submission: undefined };
})
);
const clear = () => {
logger.info(`[FormTracker::Clear]: removing every submission`);
submissions.clear();
};
return { get, stage, stash, commit, clear };
};
export type FormTrackerService = ReturnType<typeof createFormTrackerService>;
| 4,405
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/i18n.ts
|
import { WorkerMessageType } from '@proton/pass/types';
import { logger } from '@proton/pass/utils/logger';
import { DEFAULT_LOCALE } from '@proton/shared/lib/constants';
import { getClosestLocaleCode, getLanguageCode } from '@proton/shared/lib/i18n/helper';
import { loadLocale } from '@proton/shared/lib/i18n/loadLocale';
import { setTtagLocales } from '@proton/shared/lib/i18n/locales';
import noop from '@proton/utils/noop';
import locales from '../../locales';
import WorkerMessageBroker from '../channel';
import { withContext } from '../context';
export const createI18nService = () => {
const hasRegion = (locale: string) => /[_-]/.test(locale);
const getDefaultLocale = (): string => {
const [fst, snd] = navigator.languages;
if (!fst && !snd) return DEFAULT_LOCALE;
return !hasRegion(fst) && hasRegion(snd) && getLanguageCode(fst) === getLanguageCode(snd) ? snd : fst;
};
const getLocale = withContext<() => Promise<{ locale: string }>>(async (ctx) => ({
locale: getClosestLocaleCode(
await (async () => {
try {
const { locale } = await ctx.service.settings.resolve();
return locale ?? getDefaultLocale();
} catch {
return getDefaultLocale();
}
})(),
locales
),
}));
const setLocale = async (locale?: string) => {
logger.info(`[I18nService] changing locale to ${locale}`);
await loadLocale(locale ?? getDefaultLocale(), locales).catch(noop);
};
const init = async () => {
setTtagLocales(locales);
await setLocale((await getLocale()).locale);
};
WorkerMessageBroker.registerMessage(WorkerMessageType.LOCALE_REQUEST, getLocale);
return { init, setLocale };
};
export type I18NService = ReturnType<typeof createI18nService>;
| 4,406
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/injection.ts
|
import { captureMessage as sentryCaptureMessage } from '@sentry/browser';
import type { Runtime } from 'webextension-polyfill';
import { backgroundMessage } from '@proton/pass/lib/extension/message';
import browser from '@proton/pass/lib/globals/browser';
import type { Maybe } from '@proton/pass/types';
import { type TabId, WorkerMessageType } from '@proton/pass/types';
import { logger } from '@proton/pass/utils/logger';
import noop from '@proton/utils/noop';
import WorkerMessageBroker from '../channel';
const withTabEffect =
(fn: (tabId: TabId, frameId: Maybe<number>) => Promise<void>) =>
async (_: any, { tab, frameId }: Runtime.MessageSender) => {
try {
await (tab?.id && fn(tab.id, frameId));
return true;
} catch (_) {
/* in case the tab/frameId was discarded we may get an
* `Receiving end does not exist` error at this point -
* ignore it as the orchestrator will be re-injected */
return true;
}
};
export const createInjectionService = () => {
const inject = async (options: {
tabId: TabId;
allFrames?: boolean;
frameId?: Maybe<number>;
js: string[];
css?: string[];
}) => {
const { tabId } = options;
const frameIds = options.frameId ? [options.frameId] : undefined;
Promise.all([
options.css &&
browser.scripting.insertCSS({
target: { tabId, allFrames: options.allFrames ?? false, frameIds },
files: options.css,
}),
options.js &&
browser.scripting.executeScript({
target: { tabId, allFrames: options.allFrames ?? false, frameIds },
files: options.js,
}),
]).catch((e) => logger.info(`[InjectionService::inject] Injection error on tab ${tabId}`, e));
};
const updateInjections = async () => {
const tabs = await browser.tabs.query({ url: ['https://*/*', 'http://*/*'] }).catch(() => []);
await Promise.all(
tabs
.filter((tab) => !tab.url?.includes('pass.proton.'))
.map((tab) => {
logger.info(`[InjectionService::update] Re-injecting script on tab ${tab.id}`);
if (tab.id !== undefined) {
/* FIXME: re-inject in all frames when supporting iframes */
inject({ tabId: tab.id, allFrames: false, js: ['orchestrator.js'] }).catch(noop);
}
})
);
};
WorkerMessageBroker.registerMessage(
WorkerMessageType.LOAD_CONTENT_SCRIPT,
withTabEffect((tabId, frameId) => inject({ tabId, frameId, js: ['client.js'], css: ['styles/client.css'] }))
);
WorkerMessageBroker.registerMessage(
WorkerMessageType.UNLOAD_CONTENT_SCRIPT,
withTabEffect((tabId, frameId) =>
browser.tabs.sendMessage(tabId, backgroundMessage({ type: WorkerMessageType.UNLOAD_CONTENT_SCRIPT }), {
frameId,
})
)
);
WorkerMessageBroker.registerMessage(
WorkerMessageType.START_CONTENT_SCRIPT,
withTabEffect((tabId, frameId) =>
browser.tabs.sendMessage(tabId, backgroundMessage({ type: WorkerMessageType.START_CONTENT_SCRIPT }), {
frameId,
})
)
);
WorkerMessageBroker.registerMessage(WorkerMessageType.SENTRY_CS_EVENT, ({ payload }) => {
sentryCaptureMessage(payload.message, { extra: payload });
return true;
});
return { updateInjections };
};
export type InjectionService = ReturnType<typeof createInjectionService>;
| 4,407
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/logger.ts
|
import { WorkerMessageType } from '@proton/pass/types';
import { withPayloadLens } from '@proton/pass/utils/fp/lens';
import { logger } from '@proton/pass/utils/logger';
import WorkerMessageBroker from '../channel';
const LOG_BUFFER_MAX_LENGTH = 200;
export const createLoggerService = () => {
const buffer: string[] = [];
const pushLog = (message: string): boolean => {
buffer.unshift(`${new Date().toUTCString()} ${message}`);
if (buffer.length > LOG_BUFFER_MAX_LENGTH) {
buffer.pop();
}
return true;
};
WorkerMessageBroker.registerMessage(WorkerMessageType.LOG_EVENT, withPayloadLens('log', pushLog));
WorkerMessageBroker.registerMessage(WorkerMessageType.LOG_REQUEST, () => ({ logs: buffer }));
logger.setLogOptions({
onLog: (log, originalLog) => {
pushLog(log);
return ENV === 'development' && originalLog(log);
},
});
return { pushLog };
};
export type LoggerService = ReturnType<typeof createLoggerService>;
| 4,408
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/main-frame.tracker.ts
|
import type { WebRequest } from 'webextension-polyfill';
import browser from '@proton/pass/lib/globals/browser';
import type { MaybeNull, TabId } from '@proton/pass/types';
import { isFailedRequest } from '@proton/pass/utils/requests';
import { parseUrl } from '@proton/pass/utils/url/parser';
/**
* There is currently no way to retrieve the status
* code of a main frame request in the browser
* javascript API.
*
* After a form submission triggering a page change,
* in order to infer a potential failure from a
* redirection to an unauthorized page, we keep track
* of the active's tabs statuses.
*/
type MainFrameRequestTrackerOptions = {
onTabError: (tabId: TabId, domain: MaybeNull<string>) => void;
onTabDelete: (tabId: TabId) => void;
};
const filter: WebRequest.RequestFilter = {
urls: ['<all_urls>'],
types: ['main_frame'],
};
export const createMainFrameRequestTracker = ({ onTabDelete, onTabError }: MainFrameRequestTrackerOptions) => {
const onMainFrameCompleted = (req: WebRequest.OnCompletedDetailsType) =>
isFailedRequest(req) && onTabError(req.tabId, parseUrl(req.url).domain);
browser.tabs.onRemoved.addListener(onTabDelete);
browser.webRequest.onCompleted.addListener(onMainFrameCompleted, filter);
browser.webRequest.onErrorOccurred.addListener(({ tabId, url }) => onTabError(tabId, parseUrl(url).domain), filter);
return {};
};
| 4,409
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/onboarding.ts
|
import { PASS_BF_2023_DATES } from '@proton/pass/constants';
import { api } from '@proton/pass/lib/api/api';
import browser from '@proton/pass/lib/globals/browser';
import {
selectFeatureFlag,
selectHasRegisteredLock,
selectPassPlan,
selectUserState,
} from '@proton/pass/store/selectors';
import type { MaybeNull, TabId } from '@proton/pass/types';
import {
type Maybe,
type OnboardingAcknowledgment,
OnboardingMessage,
type OnboardingState,
WorkerMessageType,
} from '@proton/pass/types';
import { PassFeature } from '@proton/pass/types/api/features';
import { UserPassPlan } from '@proton/pass/types/api/plan';
import { withPayloadLens } from '@proton/pass/utils/fp/lens';
import { logger } from '@proton/pass/utils/logger';
import { merge } from '@proton/pass/utils/object/merge';
import { UNIX_DAY } from '@proton/pass/utils/time/constants';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import identity from '@proton/utils/identity';
import noop from '@proton/utils/noop';
import WorkerMessageBroker from '../channel';
import { withContext } from '../context';
import store from '../store';
type OnboardingContext = { state: OnboardingState };
type OnboardingWhen = (previousAck: Maybe<OnboardingAcknowledgment>, state: OnboardingState) => boolean;
type OnboardingOnAck = (ack: OnboardingAcknowledgment) => OnboardingAcknowledgment;
type OnboardingRule = { message: OnboardingMessage; when?: OnboardingWhen; onAcknowledge?: OnboardingOnAck };
export const INITIAL_ONBOARDING_STATE: OnboardingState = {
installedOn: -1,
updatedOn: -1,
acknowledged: [],
};
const createOnboardingRule = (options: OnboardingRule): OnboardingRule => ({
message: options.message,
onAcknowledge: options.onAcknowledge,
when: (previousAck, state) =>
options.when?.(previousAck, state) ?? !state.acknowledged.some((data) => data.message === options.message),
});
/* Define the onboarding rules here :
* - each rule must be registered on a specific `OnboardingMessage` type
* - define an optional predicate for when to show the message
* - order is important: we will apply the first matched rule */
const ONBOARDING_RULES: OnboardingRule[] = [
createOnboardingRule({
message: OnboardingMessage.PENDING_SHARE_ACCESS,
when: (previous) => {
if (previous) return false;
const state = store.getState();
const newUserSharingEnabled = selectFeatureFlag(PassFeature.PassSharingNewUsers)(state);
const { waitingNewUserInvites } = selectUserState(state);
return newUserSharingEnabled && (waitingNewUserInvites ?? 0) > 0;
},
}),
createOnboardingRule({
message: OnboardingMessage.PERMISSIONS_REQUIRED,
when: withContext<OnboardingWhen>((ctx) => !ctx.service.activation.getPermissionsGranted()),
}),
createOnboardingRule({
message: OnboardingMessage.STORAGE_ISSUE,
when: withContext<OnboardingWhen>((ctx) => ctx.service.storage.getState().storageFull),
}),
createOnboardingRule({
message: OnboardingMessage.UPDATE_AVAILABLE,
onAcknowledge: withContext<OnboardingOnAck>((ctx, ack) => {
/* keep a reference to the current available update so as
* not to re-prompt the user with this update if ignored */
return merge(ack, {
extraData: {
version: ctx.service.activation.getAvailableUpdate(),
},
});
}),
when: withContext<OnboardingWhen>((ctx, previous) => {
const availableVersion = ctx.service.activation.getAvailableUpdate();
const previousAckVersion = previous?.extraData?.version as MaybeNull<string>;
const shouldPrompt = !previous || previousAckVersion !== availableVersion;
return availableVersion !== null && shouldPrompt;
}),
}),
createOnboardingRule({
message: OnboardingMessage.BLACK_FRIDAY_OFFER,
when: (previous) => {
const passPlan = selectPassPlan(store.getState());
if (passPlan === UserPassPlan.PLUS) return false;
const now = api.getState().serverTime?.getTime() ?? Date.now();
return !previous && now > PASS_BF_2023_DATES[0] && now < PASS_BF_2023_DATES[1];
},
}),
createOnboardingRule({
message: OnboardingMessage.TRIAL,
when: (previous) => {
const passPlan = selectPassPlan(store.getState());
return !previous && passPlan === UserPassPlan.TRIAL;
},
}),
createOnboardingRule({
message: OnboardingMessage.SECURE_EXTENSION,
when: (previous, { installedOn }) => {
/* should prompt only if user has no extension lock AND
* message was not previously acknowledged AND user has
* installed at least one day ago */
const now = getEpoch();
const hasLock = selectHasRegisteredLock(store.getState());
const shouldPrompt = !previous && now - installedOn > UNIX_DAY;
return !hasLock && shouldPrompt;
},
}),
createOnboardingRule({
message: OnboardingMessage.USER_RATING,
when: (previous) => {
const PROMPT_ITEM_COUNT = 10;
const { createdItemsCount } = store.getState().settings;
return !previous && createdItemsCount >= PROMPT_ITEM_COUNT;
},
}),
];
export const createOnboardingService = () => {
const ctx: OnboardingContext = { state: INITIAL_ONBOARDING_STATE };
/* Every setState call will have the side-effect of
* updating the locally stored onboarding state */
const setState = withContext<(state: Partial<OnboardingState>) => void>(({ service }, state) => {
ctx.state = merge(ctx.state, state);
void service.storage.local.set({ onboarding: JSON.stringify(ctx.state) });
});
const onInstall = () => setState({ installedOn: getEpoch() });
const onUpdate = () => setState({ updatedOn: getEpoch() });
/* Reset the state's acknowledged messages. This may be
* useful when logging out a user - preserves timestamps */
const reset = () => setState({ acknowledged: [] });
/* Acknowledges the current onboarding message by either pushing
* it to the acknowledged messages list or updating the entry */
const acknowledge = (message: OnboardingMessage) => {
logger.info(`[Worker::Onboarding] Acknowledging "${OnboardingMessage[message]}"`);
const acknowledged = ctx.state.acknowledged.find((data) => data.message === message);
const onAcknowledge = ONBOARDING_RULES.find((rule) => rule.message === message)?.onAcknowledge ?? identity;
setState({
acknowledged: [
...ctx.state.acknowledged.filter((data) => data.message !== message),
onAcknowledge({ message, acknowledgedOn: getEpoch(), count: (acknowledged?.count ?? 0) + 1 }),
],
});
return true;
};
/* Define extra rules in the `ONBOARDING_RULES` constant :
* we will resolve the first message that matches the rule's
* `when` condition */
const getOnboardingMessage = () => ({
message: ONBOARDING_RULES.find(
({ message, when }) =>
when?.(
ctx.state.acknowledged.find((ack) => message === ack.message),
ctx.state
)
)?.message,
});
const navigateToOnboarding = async (tabId: TabId): Promise<boolean> => {
const welcomePage = browser.runtime.getURL('/onboarding.html#/welcome');
await browser.tabs.update(tabId, { url: welcomePage }).catch(noop);
return true;
};
/* hydrate the onboarding state value from the storage
* on service creation. This will noop on first install */
const hydrate = withContext(async ({ service }) => {
try {
const { onboarding } = await service.storage.local.get(['onboarding']);
if (onboarding) setState(JSON.parse(onboarding));
} catch {}
});
WorkerMessageBroker.registerMessage(WorkerMessageType.ONBOARDING_ACK, withPayloadLens('message', acknowledge));
WorkerMessageBroker.registerMessage(WorkerMessageType.ONBOARDING_REQUEST, () => getOnboardingMessage());
/* when reaching `account.proton.me/auth-ext` we want to
* redirect the user to the welcome page iif user has logged in.
* we check the `authStore` because the `ctx.state.loggedIn` will
* not be `true` until the worker is actually `READY` (booting
* sequence finished) */
WorkerMessageBroker.registerMessage(
WorkerMessageType.ACCOUNT_EXTENSION,
withContext((ctx, _, { tab }) => (ctx.authStore.hasSession() && tab?.id ? navigateToOnboarding(tab.id) : false))
);
/* used by account to redirect to the onboarding welcome page
* without user being necessarily logged in */
WorkerMessageBroker.registerMessage(WorkerMessageType.ACCOUNT_ONBOARDING, (_, { tab }) =>
tab?.id ? navigateToOnboarding(tab.id) : false
);
return { hydrate, reset, onInstall, onUpdate };
};
export type OnboardingService = ReturnType<typeof createOnboardingService>;
| 4,410
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/otp.ts
|
import { generateTOTPCode } from '@proton/pass/lib/otp/generate';
import { parseOTPValue } from '@proton/pass/lib/otp/otp';
import { selectAutofillCandidates, selectItemByShareIdAndId } from '@proton/pass/store/selectors';
import type { OtpRequest, WorkerMessageResponse } from '@proton/pass/types';
import { type OtpCode, WorkerMessageType } from '@proton/pass/types';
import { withPayload } from '@proton/pass/utils/fp/lens';
import { logId, logger } from '@proton/pass/utils/logger';
import { deobfuscate } from '@proton/pass/utils/obfuscate/xor';
import type { ParsedSender } from '@proton/pass/utils/url/parser';
import { parseSender } from '@proton/pass/utils/url/parser';
import WorkerMessageBroker from '../channel';
import { withContext } from '../context';
import store from '../store';
/* Although clients should store a complete OTP URI in the `totpUri` field.
* We take this with a grain of salt to account from possible faulty imports.
* And treat the `totpUri` field value as if it was user input, either:
* - a valid OTP URI
* - a valid secret from which we can create a valid TOTP URI with our defaults
* - an invalid string
* Each of the following OTP-related operations may throw. */
export const createOTPService = () => {
const handleTOTPRequest = (otpRequest: OtpRequest): OtpCode => {
const { shareId, itemId, ...request } = otpRequest;
try {
const item = selectItemByShareIdAndId(shareId, itemId)(store.getState());
if (item?.data.type === 'login') {
const extraField = request.type === 'extraField' ? item?.data.extraFields?.[request.index] : undefined;
const totpUri =
request.type === 'item'
? item?.data.content.totpUri
: extraField?.type === 'totp' && extraField.data.totpUri;
if (totpUri) {
const otp = generateTOTPCode(parseOTPValue(deobfuscate(totpUri)));
if (otp) return otp;
}
}
throw new Error('Cannot generate an OTP code from such item');
} catch (err: unknown) {
logger.error(`[Worker::OTP] OTP generation error for item ${logId(itemId)} on share ${logId(shareId)}`);
throw err;
}
};
const handleOTPCheck = withContext<
(sender: ParsedSender) => WorkerMessageResponse<WorkerMessageType.AUTOFILL_OTP_CHECK>
>(({ service: { formTracker } }, { tabId, url }) => {
const submission = formTracker.get(tabId, url.domain ?? '');
const candidates = selectAutofillCandidates(url)(store.getState());
const otpItems = candidates.filter((item) => Boolean(item.data.content.totpUri.v));
const match = submission
? otpItems.find((item) => deobfuscate(item.data.content.username) === submission.data.username)
: otpItems[0];
return match ? { shouldPrompt: true, shareId: match.shareId, itemId: match.itemId } : { shouldPrompt: false };
});
WorkerMessageBroker.registerMessage(WorkerMessageType.OTP_CODE_GENERATE, withPayload(handleTOTPRequest));
WorkerMessageBroker.registerMessage(WorkerMessageType.AUTOFILL_OTP_CHECK, (_, sender) =>
handleOTPCheck(parseSender(sender))
);
return {};
};
export type OTPService = ReturnType<typeof createOTPService>;
| 4,411
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/settings.ts
|
import WorkerMessageBroker from 'proton-pass-extension/app/worker/channel';
import { withContext } from 'proton-pass-extension/app/worker/context';
import store from 'proton-pass-extension/app/worker/store';
import { backgroundMessage } from '@proton/pass/lib/extension/message';
import { updatePauseListItem } from '@proton/pass/store/actions';
import { INITIAL_SETTINGS, type ProxiedSettings } from '@proton/pass/store/reducers/settings';
import { selectProxiedSettings } from '@proton/pass/store/selectors';
import { WorkerMessageType } from '@proton/pass/types';
import { withPayload } from '@proton/pass/utils/fp/lens';
import { logger } from '@proton/pass/utils/logger';
import noop from '@proton/utils/noop';
export type SettingsService = ReturnType<typeof createSettingsService>;
export const createSettingsService = () => {
/* We have to proxy the redux store settings in local storage
* in case the user is logged out (session invalidated, locked etc..)
* but need to preserve the user settings in the content-script */
const sync = withContext<(settings: ProxiedSettings) => Promise<void>>(async ({ service }, settings) => {
await service.i18n.setLocale(settings.locale).catch(noop);
await service.storage.local.set({ settings: JSON.stringify(settings) });
logger.info('[Worker::Settings] synced settings');
WorkerMessageBroker.ports.broadcast(
backgroundMessage({
type: WorkerMessageType.SETTINGS_UPDATE,
payload: settings,
})
);
});
const resolve = withContext<() => Promise<ProxiedSettings>>(async ({ service }) => {
try {
const { settings } = await service.storage.local.get(['settings']);
if (!settings) throw new Error();
return JSON.parse(settings);
} catch (e) {
return INITIAL_SETTINGS;
}
});
/* on extension install : Set the initial proxied
* locally stored settings with the results */
const onInstall = withContext<() => Promise<void>>(async ({ service }) => {
const initialSettings = selectProxiedSettings(store.getState());
return service.storage.local.set({ settings: JSON.stringify(initialSettings) });
});
WorkerMessageBroker.registerMessage(
WorkerMessageType.PAUSE_WEBSITE,
withPayload(async ({ criteria, hostname }) => {
store.dispatch(updatePauseListItem({ criteria, hostname }));
await sync(selectProxiedSettings(store.getState()));
return true;
})
);
return { onInstall, sync, resolve };
};
| 4,412
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/storage.ts
|
import { noop } from 'lodash';
import { browserLocalStorage, browserSessionStorage } from '@proton/pass/lib/extension/storage';
import type { StorageInterface, StorageQuery } from '@proton/pass/lib/extension/storage/types';
import {
type LocalStoreData,
type LocalStoreKeys,
type SessionStoreData,
type SessionStoreKeys,
} from '@proton/pass/types';
type StorageState = { storageFull: boolean };
export const createStorageService = () => {
const local = browserLocalStorage as StorageInterface<LocalStoreData>;
const session = browserSessionStorage as StorageInterface<SessionStoreData>;
const state: StorageState = { storageFull: false };
return {
local: {
get: <K extends LocalStoreKeys[]>(keys: K): Promise<StorageQuery<LocalStoreData, K>> =>
local.getItems(keys).catch(() => ({})),
/* if a local storage `setter` action throws, it likely
* means that we either reached the max quota or the user
* does not have any disk space left */
set: async (data: Partial<LocalStoreData>) => {
local
.setItems(data)
.then((result) => {
state.storageFull = false;
return result;
})
.catch(() => (state.storageFull = true));
},
unset: (keys: LocalStoreKeys[]) => local.removeItems(keys).catch(noop),
clear: () => local.clear().catch(noop),
},
session: {
get: <K extends SessionStoreKeys[]>(keys: K): Promise<StorageQuery<SessionStoreData, K>> =>
session.getItems(keys).catch(() => ({})),
set: (data: Partial<SessionStoreData>) => session.setItems(data).catch(noop),
unset: (keys: SessionStoreKeys[]) => session.removeItems(keys).catch(noop),
clear: () => session.clear().catch(noop),
},
getState: () => state,
};
};
export type StorageService = ReturnType<typeof createStorageService>;
| 4,413
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/store.ts
|
import { WorkerMessageType } from '@proton/pass/types';
import WorkerMessageBroker from '../channel';
import { onContextReady } from '../context';
import store from '../store';
export const createStoreService = () => {
WorkerMessageBroker.registerMessage(
WorkerMessageType.STORE_ACTION,
onContextReady((_, message) => {
store.dispatch(message.payload.action);
return true;
})
);
return {};
};
export type StoreService = ReturnType<typeof createStoreService>;
| 4,414
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/telemetry.ts
|
import { api } from '@proton/pass/lib/api/api';
import browser from '@proton/pass/lib/globals/browser';
import { selectTelemetryEnabled, selectUserTier } from '@proton/pass/store/selectors';
import { type Maybe, type MaybeNull, WorkerMessageType } from '@proton/pass/types';
import { type TelemetryEvent } from '@proton/pass/types/data/telemetry';
import { withPayloadLens } from '@proton/pass/utils/fp/lens';
import { logger } from '@proton/pass/utils/logger';
import { merge } from '@proton/pass/utils/object/merge';
import { UNIX_HOUR, UNIX_MINUTE } from '@proton/pass/utils/time/constants';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import chunk from '@proton/utils/chunk';
import debounce from '@proton/utils/debounce';
import noop from '@proton/utils/noop';
import WorkerMessageBroker from '../channel';
import { withContext } from '../context';
import store from '../store';
type TelemetryEventBundle = {
sendTime: number;
events: TelemetryEvent[];
retryCount: number;
};
type TelemetryServiceContext = {
active: boolean;
buffer: TelemetryEvent[];
job: MaybeNull<Promise<Maybe<TelemetryEventBundle>>>;
};
const MIN_DT = ENV === 'production' ? 6 * UNIX_HOUR : UNIX_MINUTE;
const MAX_DT = ENV === 'production' ? 12 * UNIX_HOUR : 5 * UNIX_MINUTE;
const TELEMETRY_ALARM_NAME = 'PassTelemetryAlarm';
const TELEMETRY_BATCH_SIZE = 100;
const TELEMETRY_MAX_RETRY = 2;
const getRandomSendTime = (): number => getEpoch() + MIN_DT + Math.floor(Math.random() * (MAX_DT - MIN_DT));
const shouldSendBundle = ({ sendTime }: TelemetryEventBundle): boolean => sendTime - getEpoch() <= 0;
const createBundle = (): TelemetryEventBundle => ({ sendTime: getRandomSendTime(), events: [], retryCount: 0 });
const deleteBundle = withContext<() => Promise<void>>((ctx) => ctx.service.storage.local.unset(['telemetry']));
const saveBundle = withContext<(bundle: TelemetryEventBundle) => Promise<void>>((ctx, bundle) =>
ctx.service.storage.local.set({ telemetry: JSON.stringify(bundle) })
);
/* resolves any currently cached telemetry bundle or creates a new one if non exists */
const resolveBundle = withContext<() => Promise<TelemetryEventBundle>>(async ({ service }) => {
try {
const { telemetry } = await service.storage.local.get(['telemetry']);
if (!telemetry) throw new Error();
return JSON.parse(telemetry);
} catch (_) {
const bundle = createBundle();
await saveBundle(bundle);
return bundle;
}
});
const isTelemetryEnabled = () => selectTelemetryEnabled(store.getState());
/* sends all events in current bundle to the telemetry endpoint
* and returns a boolean indicating success or failure */
const sendBundle = async (bundle: TelemetryEventBundle): Promise<{ ok: true } | { ok: false; retry: boolean }> => {
try {
/* skip bundle if we have reached the max retry count or */
/* if the user settings do not allow telemetry */
if (bundle.retryCount >= TELEMETRY_MAX_RETRY || !isTelemetryEnabled()) {
return { ok: false, retry: false };
}
logger.info(`[Worker::Telemetry] dispatching current bundle [${bundle.events.length} event(s)]`);
await Promise.all(
chunk(bundle.events, TELEMETRY_BATCH_SIZE).map((EventInfo) =>
api({
url: 'data/v1/stats/multiple',
method: 'post',
data: { EventInfo },
})
)
);
return { ok: true };
} catch (e) {
logger.warn(`[Worker::Telemetry] failed to send telemetry bundle`);
return { ok: false, retry: true };
}
};
export const createTelemetryService = () => {
const ctx: TelemetryServiceContext = { active: false, buffer: [], job: null };
/* If the API call failed we may hit a sendTime lower than the
* current time, in this case, retry in 1 minute */
const setAlarm = async (bundle: TelemetryEventBundle) => {
if (bundle.events.length > 0 && !(await browser.alarms.get(TELEMETRY_ALARM_NAME))) {
const when = Math.max(bundle.sendTime - getEpoch(), UNIX_MINUTE);
logger.info(`[Worker::Telemetry] new telemetry alarm in ${when}s`);
browser.alarms.create(TELEMETRY_ALARM_NAME, { when: (getEpoch() + when) * 1000 });
}
};
/* try to consume the current context's buffer of events - if this
* method returns a `TelemetryEventBundle` it means it was not sent
* out and is still "active" - debounce this function in case we have-
* concurrent events being pushed to the buffer */
const consumeBuffer = debounce(async (): Promise<void> => {
await ctx.job; /* ensure no-ongoing job */
const buffer = ctx.buffer.slice();
ctx.buffer.length = 0;
ctx.job = new Promise<Maybe<TelemetryEventBundle>>(async (resolve) => {
const bundle = await resolveBundle();
bundle.events = bundle.events.concat(buffer);
/* if bundle should be sent - ping the telemetry service ASAP
* and clear the cached bundle only on success */
if (bundle.events.length > 0 && shouldSendBundle(bundle)) {
const result = await sendBundle(bundle);
if (result.ok || !result.retry) {
await deleteBundle();
return resolve(undefined);
} else bundle.retryCount += 1;
}
/* if the bundle has not reached its sendTime or if the api
* call failed : update bundle & set the alarm */
await saveBundle(bundle);
await setAlarm(bundle);
return resolve(bundle);
}).catch(noop);
}, 500);
/* resets the service's context and both clears any registered
* alarms and any locally stored event bundle */
const stop = () => {
logger.info('[Worker::Telemetry] Clearing telemetry service...');
browser.alarms.clear(TELEMETRY_ALARM_NAME).catch(noop);
ctx.buffer.length = 0;
ctx.job = null;
ctx.active = false;
void deleteBundle();
};
const start = async () => {
try {
ctx.active = isTelemetryEnabled();
logger.info(`[Worker::Telemetry] starting service - [enabled: ${ctx.active}]`);
const alarm = await browser.alarms.get(TELEMETRY_ALARM_NAME);
if (alarm) {
const when = Math.max(alarm.scheduledTime / 1000 - getEpoch(), 0);
logger.info(`[Worker::Telemetry] found telemetry alarm in ${when}s`);
if (!ctx.active) stop(); /* clear any alarms if telemetry disabled */
} else await consumeBuffer();
} catch (_) {
ctx.active = false;
}
};
const pushEvent = async (event: TelemetryEvent): Promise<boolean> => {
try {
if (ctx.active) {
logger.info(`[Worker::Telemetry] Adding ${event.Event} to current bundle`);
ctx.buffer.push(
merge(event, {
Dimensions: {
user_tier: selectUserTier(store.getState()),
},
})
);
await consumeBuffer();
return true;
}
} catch (_) {}
return false;
};
WorkerMessageBroker.registerMessage(WorkerMessageType.TELEMETRY_EVENT, withPayloadLens('event', pushEvent));
browser.alarms.onAlarm.addListener(({ name }) => name === TELEMETRY_ALARM_NAME && consumeBuffer());
return { stop, start, pushEvent };
};
export type TelemetryService = ReturnType<typeof createTelemetryService>;
| 4,415
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/services/xmlhttp-request.tracker.ts
|
import type { WebRequest } from 'webextension-polyfill';
import browser from '@proton/pass/lib/globals/browser';
import type { TabId } from '@proton/pass/types';
import { isFailedRequest } from '@proton/pass/utils/requests';
import { UNIX_MINUTE } from '@proton/pass/utils/time/constants';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import { parseUrl } from '@proton/pass/utils/url/parser';
const filter: WebRequest.RequestFilter = {
urls: ['<all_urls>'],
types: ['xmlhttprequest'],
};
type TrackedRequestData = { tabId: TabId; domain: string; requestedAt: number };
type XMLHTTPRequestTrackerOptions = {
acceptRequest: (request: WebRequest.OnBeforeRequestDetailsType) => boolean;
onFailedRequest: (data: TrackedRequestData) => void;
};
const MAX_REQUEST_RETENTION_TIME = UNIX_MINUTE;
export const createXMLHTTPRequestTracker = ({ acceptRequest, onFailedRequest }: XMLHTTPRequestTrackerOptions) => {
const pendingRequests: Map<string, TrackedRequestData> = new Map();
const garbageCollect = (() => {
let lastGC = getEpoch();
return () => {
const now = getEpoch();
if (now - lastGC < UNIX_MINUTE) return;
const limit = (now - MAX_REQUEST_RETENTION_TIME) * 1_000;
for (const [requestId, { requestedAt }] of pendingRequests.entries()) {
if (requestedAt < limit) pendingRequests.delete(requestId);
}
lastGC = now;
};
})();
const onBeforeRequest = async (request: WebRequest.OnBeforeRequestDetailsType) => {
const { tabId, requestId } = request;
if (tabId >= 0 && acceptRequest(request)) {
try {
const tab = await browser.tabs.get(tabId);
if (tab.url !== undefined) {
const { domain } = parseUrl(tab.url);
if (domain) pendingRequests.set(requestId, { tabId, domain, requestedAt: request.timeStamp });
}
} catch (_) {}
}
garbageCollect();
return {}; /* non-blocking */
};
const onCompleted = async (request: WebRequest.OnCompletedDetailsType) => {
const { requestId } = request;
const trackedRequest = pendingRequests.get(requestId);
if (trackedRequest !== undefined) {
if (isFailedRequest(request)) onFailedRequest(trackedRequest);
pendingRequests.delete(requestId);
}
};
const onErrorOccured = async (request: WebRequest.OnErrorOccurredDetailsType) => {
const { requestId } = request;
const trackedRequest = pendingRequests.get(requestId);
if (trackedRequest !== undefined) {
pendingRequests.delete(requestId);
}
};
browser.webRequest.onBeforeRequest.addListener(onBeforeRequest, filter, ['requestBody']);
browser.webRequest.onCompleted.addListener(onCompleted, filter);
browser.webRequest.onErrorOccurred.addListener(onErrorOccured, filter);
};
| 4,416
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/store/index.ts
|
import { devToolsEnhancer } from '@redux-devtools/remote';
import { configureStore } from '@reduxjs/toolkit';
import WorkerMessageBroker from 'proton-pass-extension/app/worker/channel';
import { withContext } from 'proton-pass-extension/app/worker/context';
import { isPopupPort } from 'proton-pass-extension/lib/utils/port';
import { getExtensionVersion } from 'proton-pass-extension/lib/utils/version';
import createSagaMiddleware from 'redux-saga';
import { ACTIVE_POLLING_TIMEOUT, INACTIVE_POLLING_TIMEOUT } from '@proton/pass/lib/events/constants';
import { backgroundMessage } from '@proton/pass/lib/extension/message';
import { startEventPolling } from '@proton/pass/store/actions';
import { requestMiddleware } from '@proton/pass/store/middlewares/request-middleware';
import reducer from '@proton/pass/store/reducers';
import { workerRootSaga } from '@proton/pass/store/sagas';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import { AppStatus, ShareEventType, WorkerMessageType } from '@proton/pass/types';
import { logger } from '@proton/pass/utils/logger';
import { workerMiddleware } from './worker.middleware';
const sagaMiddleware = createSagaMiddleware();
const store = configureStore({
reducer,
middleware: [requestMiddleware, workerMiddleware, sagaMiddleware],
enhancers:
ENV === 'development'
? [
devToolsEnhancer({
name: 'background',
port: REDUX_DEVTOOLS_PORT,
realtime: true,
}),
]
: [],
});
const options: WorkerRootSagaOptions = {
endpoint: 'background',
getAuthStore: withContext((ctx) => ctx.authStore),
getAuthService: withContext((ctx) => ctx.service.auth),
getCache: withContext(async (ctx) => {
/* cache is considered valid if versions match */
const cache = await ctx.service.storage.local.get(['state', 'snapshot', 'salt', 'version']);
return cache.version === getExtensionVersion() ? cache : {};
}),
/* adapt event polling interval based on popup activity :
* 30 seconds if popup is opened / 30 minutes if closed */
getEventInterval: () =>
WorkerMessageBroker.ports.query(isPopupPort()).length > 0 ? ACTIVE_POLLING_TIMEOUT : INACTIVE_POLLING_TIMEOUT,
setCache: withContext((ctx, encryptedCache) =>
ctx.service.storage.local.set({
...encryptedCache,
version: getExtensionVersion(),
})
),
getLocalSettings: withContext((ctx) => ctx.service.settings.resolve()),
getTelemetry: withContext((ctx) => ctx.service.telemetry),
getAppState: withContext((ctx) => ctx.getState()),
/* Sets the worker status according to the
* boot sequence's result. On boot failure,
* clear */
onBoot: withContext(async (ctx, res) => {
if (res.ok) {
store.dispatch(startEventPolling());
void ctx.service.telemetry?.start();
ctx.setStatus(AppStatus.READY);
WorkerMessageBroker.buffer.flush();
} else {
ctx.service.telemetry?.stop();
ctx.setStatus(AppStatus.ERROR);
if (res.clearCache) await ctx.service.storage.local.unset(['salt', 'state', 'snapshot']);
}
}),
onFeatureFlagsUpdate: (features) =>
WorkerMessageBroker.ports.broadcast(
backgroundMessage({
type: WorkerMessageType.FEATURE_FLAGS_UPDATE,
payload: features,
})
),
/* Update the extension's badge count on every item state change */
onItemsChange: withContext((ctx) => ctx.service.autofill.updateTabsBadgeCount()),
/* Either broadcast notification or buffer it
* if no target ports are opened. Assume that if no
* target is specified then notification is for popup */
onNotification: (notification) => {
const { endpoint } = notification;
const reg = new RegExp(`^${endpoint ?? 'popup'}`);
const ports = WorkerMessageBroker.ports.query((key) => reg.test(key));
const canConsume = ports.length > 0;
const message = backgroundMessage({
type: WorkerMessageType.NOTIFICATION,
payload: { notification },
});
logger.info(`[Notification::${notification.type}] ${notification.text} - broadcasting`);
return canConsume || notification.type === 'success'
? WorkerMessageBroker.ports.broadcast(message)
: WorkerMessageBroker.buffer.push(message);
},
onSettingUpdate: withContext((ctx, update) => ctx.service.settings.sync(update)),
onShareEventDisabled: (shareId) => {
WorkerMessageBroker.ports.broadcast(
backgroundMessage({
type: WorkerMessageType.SHARE_SERVER_EVENT,
payload: {
type: ShareEventType.SHARE_DISABLED,
shareId,
},
}),
isPopupPort()
);
},
onShareEventItemsDeleted: (shareId, itemIds) => {
WorkerMessageBroker.ports.broadcast(
backgroundMessage({
type: WorkerMessageType.SHARE_SERVER_EVENT,
payload: {
type: ShareEventType.ITEMS_DELETED,
shareId,
itemIds,
},
}),
isPopupPort()
);
},
};
sagaMiddleware.run(workerRootSaga.bind(null, options));
export default store;
| 4,417
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/app/worker/store/worker.middleware.ts
|
import type { AnyAction, Middleware } from 'redux';
import { backgroundMessage } from '@proton/pass/lib/extension/message';
import { sanitizeWithCallbackAction } from '@proton/pass/store/actions/with-callback';
import { WorkerMessageType } from '@proton/pass/types';
import WorkerMessageBroker from '../channel';
/**
* Redux middleware for service-worker action flow :
* - proxies every action through the extension's message channel
* - forwards actions to saga middleware
*/
export const workerMiddleware: Middleware = () => (next) => (action: AnyAction) => {
WorkerMessageBroker.ports.broadcast(
backgroundMessage({
type: WorkerMessageType.STORE_ACTION,
payload: { action: sanitizeWithCallbackAction(action) },
}),
(name) => /^(popup|page)/.test(name)
);
next(action);
};
| 4,418
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Context
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Context/Items/ItemEffects.ts
|
/**
* Regression check-list :
*
* [ ] items filter update -> noop (if `selectedItem` in `items`) | (unselect -> autoselect)
* [ ] optimistic item creation [success] -> select `itemFromSelectedOptimisticId`
* [ ] optimistic item creation [failure] -> noop
* [ ] optimistic item creation [dismiss] -> unselect -> autoselect
* [ ] optimistic item trash [success] -> unselect -> autoselect
* [ ] optimistic item trash [failure] -> unselect -> autoselect first in `items` (won't reselect the previous trashed item)
* [ ] optimistic item move [success] -> select `itemFromSelectedOptimisticId`
* [ ] optimistic item move [failure] -> select `itemFromSelectedOptimisticId`
* [ ] optimistic share delete [success|failure] -> if current filter or item matches current share : unselect -> autoselect from different share
* [ ] event-loop share deletion -> unselect if `selectedItem` in deleted share -> autoselect from different share
* [ ] event-loop item deletion -> unselect if deleted item is `selectedItem` -> autoselect
* [ ] event-loop item creation -> noop
*/
import { useEffect, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useItems } from 'proton-pass-extension/lib/hooks/useItems';
import { useNavigationContext } from 'proton-pass-extension/lib/hooks/useNavigationContext';
import { usePopupContext } from 'proton-pass-extension/lib/hooks/usePopupContext';
import { useShareEventEffect } from 'proton-pass-extension/lib/hooks/useShareEventEffect';
import { useInviteContext } from '@proton/pass/components/Invite/InviteContextProvider';
import { belongsToShare, itemEq } from '@proton/pass/lib/items/item.predicates';
import { popupTabStateSave } from '@proton/pass/store/actions/creators/popup';
import { selectItemIdByOptimisticId } from '@proton/pass/store/selectors';
import { invert } from '@proton/pass/utils/fp/predicates';
import type { ItemsFilteringContextType } from './ItemsFilteringContext';
export function vaultDeletionEffect(
shareBeingDeleted: string,
itemsFilteringVaultUtilities: Pick<ItemsFilteringContextType, 'shareId' | 'setShareBeingDeleted' | 'setShareId'>
) {
const { shareId, setShareId, setShareBeingDeleted } = itemsFilteringVaultUtilities;
/* used in `ItemEffects` to check wether the currently
* selected item matches the vault being deleted */
setShareBeingDeleted(shareBeingDeleted);
/* reset the share filter if it matches the
* vault being deleted */
if (shareBeingDeleted === shareId) setShareId(null);
}
export const ItemEffects = () => {
const dispatch = useDispatch();
const popup = usePopupContext();
const inviteContext = useInviteContext();
const { selectedItem, selectItem, unselectItem, isCreating, isEditing, inTrash } = useNavigationContext();
const {
filtering: { search, sort, type, shareId, shareBeingDeleted, setShareId, setShareBeingDeleted },
filtered: items,
} = useItems({ trashed: inTrash });
const itemFromSelectedOptimisticId = useSelector(selectItemIdByOptimisticId(selectedItem?.itemId));
const autoselect = !(isEditing || isCreating) && popup.ready;
const popupTabState = useMemo(
() => ({
domain: popup.url.subdomain ?? popup.url.domain ?? null,
filters: { search, sort, type, selectedShareId: shareId },
search,
selectedItem: selectedItem ? { shareId: selectedItem.shareId, itemId: selectedItem.itemId } : null,
tabId: popup.context!.tabId,
}),
[selectedItem, search, sort, type, shareId]
);
useShareEventEffect({
onShareDisabled: (shareId) => {
inviteContext.onShareDisabled(shareId);
vaultDeletionEffect(shareId, { shareId, setShareBeingDeleted, setShareId });
},
onItemsDeleted: (shareId, itemIds) => {
if (shareId === selectedItem?.shareId && itemIds.includes(selectedItem?.itemId)) {
unselectItem();
}
},
});
useEffect(() => {
/* if the current selected item has an optimistic id
* and can be mapped to a non-optimistic item - select it */
if (itemFromSelectedOptimisticId !== undefined) {
const { shareId, itemId } = itemFromSelectedOptimisticId;
return selectItem(shareId, itemId);
}
/* if the current selected item belongs to a share
* being deleted (either optimistically or through
* event-loop syncing) OR if it is not in the current
* `items` sub-list (ie: item filter change, deletion
* or event-loop) - unselect it : this will re-trigger
* this effect */
if (selectedItem) {
const selectedItemShareDeleted = selectedItem.shareId === shareBeingDeleted;
const selectedItemNotInItems = !items.some(itemEq(selectedItem));
void ((selectedItemShareDeleted || selectedItemNotInItems) && unselectItem({ inTrash }));
return;
}
/* if we can autoselect AND have no selected item (ie: initial
* boot or if an item was unselected) AND we can autoselect :
* -> select the first item in the current `items` sub-list excluding
* those belonging to any current share being deleted. */
if (autoselect) {
const next = shareBeingDeleted ? items.find(invert(belongsToShare(shareBeingDeleted))) : items[0];
if (next) {
const { shareId, itemId } = next;
selectItem(shareId, itemId, { action: 'replace', inTrash });
}
}
}, [selectedItem, inTrash, items, autoselect, shareBeingDeleted, itemFromSelectedOptimisticId]);
useEffect(() => {
if (shareBeingDeleted) {
/* if no items in the current `items` sub-list
* belong to the share being deleted - reset */
const itemsPendingDeletion = items.some(belongsToShare(shareBeingDeleted));
if (!itemsPendingDeletion) {
setShareBeingDeleted(null);
}
}
}, [shareBeingDeleted, items]);
useEffect(() => {
dispatch(popupTabStateSave(popupTabState));
}, [popupTabState]);
return null;
};
| 4,419
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Context
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Context/Items/ItemsFilteringContext.tsx
|
import { type FC, createContext, useMemo, useState } from 'react';
import { usePopupContext } from 'proton-pass-extension/lib/hooks/usePopupContext';
import type { ItemSortFilter, ItemTypeFilter, MaybeNull } from '@proton/pass/types';
import noop from '@proton/utils/noop';
export type ItemsFilteringContextType = {
search: string;
sort: ItemSortFilter;
type: ItemTypeFilter;
shareId: MaybeNull<string>;
shareBeingDeleted: MaybeNull<string>;
setSearch: (value: string) => void;
setSort: (value: ItemSortFilter) => void;
setType: (value: ItemTypeFilter) => void;
setShareId: (shareId: MaybeNull<string>) => void;
setShareBeingDeleted: (shareId: MaybeNull<string>) => void;
};
export const INITIAL_SORT: ItemSortFilter = 'recent';
export const ItemsFilteringContext = createContext<ItemsFilteringContextType>({
search: '',
sort: INITIAL_SORT,
type: '*',
shareId: null,
shareBeingDeleted: null,
setSearch: noop,
setSort: noop,
setType: noop,
setShareId: noop,
setShareBeingDeleted: noop,
});
export const ItemsFilteringContextProvider: FC = ({ children }) => {
const popup = usePopupContext();
const [search, setSearch] = useState<string>(popup.state.initial?.search ?? '');
const [sort, setSort] = useState<ItemSortFilter>(popup.state.initial.filters?.sort ?? INITIAL_SORT);
const [type, setType] = useState<ItemTypeFilter>(popup.state.initial.filters?.type ?? '*');
const [shareId, setShareId] = useState<MaybeNull<string>>(popup.state.initial.filters?.selectedShareId ?? null);
const [shareBeingDeleted, setShareBeingDeleted] = useState<MaybeNull<string>>(null);
const context: ItemsFilteringContextType = useMemo(
() => ({
search,
sort,
type,
shareId,
shareBeingDeleted,
setSearch,
setSort,
setType,
setShareId,
setShareBeingDeleted,
}),
[search, sort, type, shareId, shareBeingDeleted]
);
return <ItemsFilteringContext.Provider value={context}>{children}</ItemsFilteringContext.Provider>;
};
| 4,420
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Context
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Context/Navigation/NavigationContext.tsx
|
import { type FC, createContext, useCallback, useEffect, useState } from 'react';
import { useHistory, useRouteMatch } from 'react-router-dom';
import { usePopupContext } from 'proton-pass-extension/lib/hooks/usePopupContext';
import type { Maybe, SelectedItem } from '@proton/pass/types';
import noop from '@proton/utils/noop';
export type NavigationOptions = { inTrash?: boolean; action?: 'replace' | 'push' };
export type NavigationContextValue = {
selectedItem: Maybe<SelectedItem>;
selectItem: (shareId: string, itemId: string, options?: NavigationOptions) => void;
unselectItem: (options?: NavigationOptions) => void;
inTrash: boolean;
isEditing: boolean;
isCreating: boolean;
};
export const NavigationContext = createContext<NavigationContextValue>({
selectedItem: undefined,
selectItem: noop,
unselectItem: noop,
inTrash: false,
isEditing: false,
isCreating: false,
});
export const NavigationContextProvider: FC = ({ children }) => {
const popup = usePopupContext();
const history = useHistory();
const [selectedItem, setSelectedItem] = useState<Maybe<SelectedItem>>(undefined);
const inTrash = useRouteMatch('/trash') !== null;
const isEditing = history.location.pathname.includes('/edit');
const isCreating = history.location.pathname.includes('/new');
const selectItem = useCallback((shareId: string, itemId: string, options?: NavigationOptions) => {
setSelectedItem({ shareId, itemId });
history[options?.action ?? 'push'](`${options?.inTrash ? '/trash' : ''}/share/${shareId}/item/${itemId}`);
}, []);
const unselectItem = useCallback((options?: NavigationOptions) => {
setSelectedItem(undefined);
history[options?.action ?? 'push'](options?.inTrash ? '/trash' : '');
}, []);
useEffect(() => {
const { selectedItem, draft } = popup.state.initial;
if (selectedItem) selectItem(selectedItem.shareId, selectedItem.itemId, { action: 'replace' });
if (draft !== null) {
const { itemId, shareId, type, mode } = draft;
switch (mode) {
case 'new':
return history.push(`/item/new/${type}`, { draft });
case 'edit':
return history.push(`/share/${shareId}/item/${itemId}/edit`, { draft });
}
}
}, []);
return (
<NavigationContext.Provider
value={{
selectedItem,
inTrash,
isEditing,
isCreating,
selectItem,
unselectItem,
}}
>
{children}
</NavigationContext.Provider>
);
};
| 4,421
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Context
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Context/Popup/PopupContext.tsx
|
import { type FC, createContext, useContext, useEffect, useMemo, useState } from 'react';
import {
ExtensionConnect,
type ExtensionConnectContextValue,
INITIAL_WORKER_STATE,
} from 'proton-pass-extension/lib/components/Extension/ExtensionConnect';
import { useExpanded } from 'proton-pass-extension/lib/hooks/useExpanded';
import { useExtensionConnectContext } from 'proton-pass-extension/lib/hooks/useExtensionConnectContext';
import { NotificationsContext } from '@proton/components';
import { useNotifications } from '@proton/components/hooks';
import { usePassCore } from '@proton/pass/components/Core/PassCoreProvider';
import { useActionRequestEffect } from '@proton/pass/hooks/useActionRequestEffect';
import { useNotificationEnhancer } from '@proton/pass/hooks/useNotificationEnhancer';
import { clientReady } from '@proton/pass/lib/client';
import { popupMessage, sendMessage } from '@proton/pass/lib/extension/message';
import { syncRequest } from '@proton/pass/store/actions/requests';
import type { AppState, MaybeNull, PopupInitialState } from '@proton/pass/types';
import { AppStatus, WorkerMessageType, type WorkerMessageWithSender } from '@proton/pass/types';
import type { ParsedUrl } from '@proton/pass/utils/url/parser';
import { parseUrl } from '@proton/pass/utils/url/parser';
import noop from '@proton/utils/noop';
export interface PopupContextValue extends ExtensionConnectContextValue {
initialized: boolean /* retrieved popup initial state */;
expanded: boolean /* is popup expanded into a separate window */;
ready: boolean /* enable UI user actions */;
state: AppState & { initial: PopupInitialState };
url: ParsedUrl /* current tab parsed URL */;
sync: () => void;
}
export const INITIAL_POPUP_STATE: PopupInitialState = {
search: '',
draft: null,
filters: null,
selectedItem: null,
passwordOptions: null,
};
export const PopupContext = createContext<PopupContextValue>({
context: null,
initialized: false,
expanded: false,
ready: false,
state: { ...INITIAL_WORKER_STATE, initial: INITIAL_POPUP_STATE },
url: parseUrl(),
lock: noop,
logout: noop,
sync: noop,
});
/* this cannot be included directly in `PopupContextProvider` because
* of the `useExtensionContext` call which requires this component to
* be a descendant of `ExtensionConnect` */
const PopupContextContainer: FC = ({ children }) => {
const extensionContext = useExtensionConnectContext();
const { status } = extensionContext.state;
const { url, tabId } = extensionContext.context!;
const notificationsManager = useContext(NotificationsContext);
useEffect(() => notificationsManager.setOffset({ y: 10 }), []);
const [initial, setInitial] = useState<MaybeNull<PopupInitialState>>(null);
const expanded = useExpanded();
const sync = useActionRequestEffect(syncRequest(), {});
const syncing = sync.loading || extensionContext.state.status === AppStatus.BOOTING;
useEffect(() => {
if (clientReady(status)) {
void sendMessage.onSuccess(
popupMessage({ type: WorkerMessageType.POPUP_INIT, payload: { tabId } }),
setInitial
);
}
}, [status]);
const popupContext = useMemo<PopupContextValue>(() => {
const { state, ready } = extensionContext;
return {
...extensionContext,
initialized: initial !== null /* `POPUP_INIT` response resolved */,
expanded,
ready: ready && !syncing /* worker ready and no ongoing syncs */,
state: { ...state, initial: initial ?? INITIAL_POPUP_STATE },
url,
};
}, [extensionContext, syncing, initial]);
return <PopupContext.Provider value={popupContext}>{children}</PopupContext.Provider>;
};
export const PopupContextProvider: FC = ({ children }) => {
const { createNotification } = useNotifications();
const { onLink } = usePassCore();
const notificationEnhancer = useNotificationEnhancer({ onLink });
const onWorkerMessage = (message: WorkerMessageWithSender) => {
if (message.type === WorkerMessageType.NOTIFICATION) {
createNotification(notificationEnhancer(message.payload.notification));
}
};
return (
<ExtensionConnect endpoint="popup" messageFactory={popupMessage} onWorkerMessage={onWorkerMessage}>
<PopupContextContainer>{children}</PopupContextContainer>
</ExtensionConnect>
);
};
| 4,422
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Extension/ExtensionApp.tsx
|
import { type FC, type ReactNode, useEffect, useState } from 'react';
import { setupExtensionContext } from 'proton-pass-extension/lib/context/extension-context';
import {
Icons,
ModalsChildren,
ModalsProvider,
NotificationsChildren,
NotificationsProvider,
} from '@proton/components';
import { Portal } from '@proton/components/components/portal';
import { ThemeProvider } from '@proton/pass/components/Layout/Theme/ThemeProvider';
import { resolveMessageFactory, sendMessage } from '@proton/pass/lib/extension/message';
import type { WorkerMessage } from '@proton/pass/types';
import { type ClientEndpoint, WorkerMessageType } from '@proton/pass/types';
import { DEFAULT_LOCALE } from '@proton/shared/lib/constants';
import { loadLocale } from '@proton/shared/lib/i18n/loadLocale';
import { setTtagLocales } from '@proton/shared/lib/i18n/locales';
import noop from '@proton/utils/noop';
import locales from '../../../app/locales';
import { PassExtensionCore } from './PassExtensionCore';
export const ExtensionApp: FC<{
endpoint: ClientEndpoint;
children: (ready: boolean, locale: string) => ReactNode;
}> = ({ endpoint, children }) => {
const [ready, setReady] = useState(false);
const [locale, setLocale] = useState(DEFAULT_LOCALE);
/* resolve the extension locale through the I18nService instead of reading
* from the store as some extension sub-apps are not redux connected but
* should be aware of the current localisation setting */
const getExtensionLocale = () =>
sendMessage.on(resolveMessageFactory(endpoint)({ type: WorkerMessageType.LOCALE_REQUEST }), (res) =>
res.type === 'success' ? res.locale : DEFAULT_LOCALE
);
const watchLocale = (message: WorkerMessage) => {
if (message.type === WorkerMessageType.SETTINGS_UPDATE) {
const nextLocale = message.payload.locale ?? locale;
loadLocale(nextLocale, locales)
.then(() => setLocale(nextLocale))
.catch(noop);
}
};
useEffect(() => {
setupExtensionContext({
endpoint,
onDisconnect: () => {
window.location.reload();
return { recycle: false };
},
onRecycle: noop,
})
.then(async (ctx) => {
const currentLocale = await getExtensionLocale();
setLocale(currentLocale);
setTtagLocales(locales);
ctx.port.onMessage.addListener(watchLocale);
return loadLocale(currentLocale, locales);
})
.then(() => setReady(true))
.catch(console.warn);
}, []);
return (
<PassExtensionCore endpoint={endpoint}>
<Icons />
<ThemeProvider />
<NotificationsProvider>
<ModalsProvider>
{children(ready, locale)}
<Portal>
<ModalsChildren />
<NotificationsChildren />
</Portal>
</ModalsProvider>
</NotificationsProvider>
</PassExtensionCore>
);
};
| 4,423
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Extension/ExtensionConnect.tsx
|
import { createContext, useCallback, useEffect, useMemo, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useWorkerStateEvents } from 'proton-pass-extension/lib/hooks/useWorkerStateEvents';
import { useActivityProbe } from '@proton/pass/hooks/useActivityProbe';
import { clientReady } from '@proton/pass/lib/client';
import type { MessageWithSenderFactory } from '@proton/pass/lib/extension/message';
import { sessionLockIntent, signoutIntent, syncIntent } from '@proton/pass/store/actions';
import { wakeupRequest } from '@proton/pass/store/actions/requests';
import { selectRequestInFlight } from '@proton/pass/store/selectors';
import type { AppState, ClientEndpoint, MaybeNull, WorkerMessageWithSender } from '@proton/pass/types';
import { AppStatus } from '@proton/pass/types';
import { setUID as setSentryUID } from '@proton/shared/lib/helpers/sentry';
import noop from '@proton/utils/noop';
import { ExtensionContext, type ExtensionContextType } from '../../context/extension-context';
export const INITIAL_WORKER_STATE: AppState = {
loggedIn: false,
status: AppStatus.IDLE,
UID: undefined,
};
export interface ExtensionConnectContextValue {
context: MaybeNull<ExtensionContextType>;
state: AppState;
ready: boolean;
logout: (options: { soft: boolean }) => void;
lock: () => void;
sync: () => void;
}
export const ExtensionConnectContext = createContext<ExtensionConnectContextValue>({
context: null,
state: INITIAL_WORKER_STATE,
ready: false,
logout: noop,
lock: noop,
sync: noop,
});
type ExtensionConnectProps<T extends ClientEndpoint> = {
endpoint: T;
messageFactory: MessageWithSenderFactory;
onWorkerMessage?: (message: WorkerMessageWithSender) => void;
children: React.ReactNode;
};
export const ExtensionConnect = <T extends ClientEndpoint>({
endpoint,
messageFactory,
onWorkerMessage,
children,
}: ExtensionConnectProps<T>) => {
const dispatch = useDispatch();
const { tabId } = ExtensionContext.get();
const activityProbe = useActivityProbe(messageFactory);
const [state, setState] = useState<AppState>(INITIAL_WORKER_STATE);
const wakeupLoading = useSelector(selectRequestInFlight(wakeupRequest({ endpoint, tabId })));
const ready = !wakeupLoading && clientReady(state.status);
const logout = useCallback(({ soft }: { soft: boolean }) => {
setState(INITIAL_WORKER_STATE);
dispatch(signoutIntent({ soft }));
}, []);
const lock = useCallback(() => {
setState({ ...INITIAL_WORKER_STATE, status: AppStatus.LOCKED });
dispatch(sessionLockIntent());
}, []);
const sync = useCallback(() => dispatch(syncIntent()), []);
useWorkerStateEvents({
tabId,
endpoint,
messageFactory,
onWorkerStateChange: (workerState) => {
setSentryUID(workerState.UID);
setState((prevState) => ({ ...prevState, ...workerState }));
},
});
useEffect(() => {
if (!onWorkerMessage) return;
ExtensionContext.get().port.onMessage.addListener(onWorkerMessage);
return () => ExtensionContext.get().port.onMessage.removeListener(onWorkerMessage);
});
useEffect(() => {
const onVisibilityChange = () => activityProbe[document.visibilityState === 'visible' ? 'start' : 'cancel']();
document.addEventListener('visibilitychange', onVisibilityChange);
onVisibilityChange();
return () => document.removeEventListener('visibilitychange', onVisibilityChange);
}, []);
const context = useMemo<ExtensionConnectContextValue>(
() => ({ context: ExtensionContext.get(), state, ready, logout, lock, sync }),
[state, ready]
);
return <ExtensionConnectContext.Provider value={context}>{children}</ExtensionConnectContext.Provider>;
};
| 4,424
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Extension/ExtensionError.tsx
|
import type { VFC } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { LobbyLayout } from '@proton/pass/components/Layout/Lobby/LobbyLayout';
import browser from '@proton/pass/lib/globals/browser';
import { PASS_APP_NAME } from '@proton/shared/lib/constants';
/* This component uses buttons leveraging `ui-orange` &
* `ui-red` themes because we don't currently
* support weak & danger|warning buttons */
export const PromptForReload: VFC<{ message: string }> = ({ message }) => (
<div key="prompt-for-reload" className="mt-12 w-full flex flex-column flex-align-items-center gap-2 anime-fade-in">
<span className="block text-sm text-weak">{message}</span>
<Button pill shape="solid" color="weak" className="ui-red w-full" onClick={() => browser.runtime.reload()}>
{c('Action').t`Reload extension`}
</Button>
</div>
);
export const ExtensionError: VFC = () => (
<LobbyLayout overlay>
<PromptForReload
message={c('Error')
.t`Something went wrong. Please reload the ${PASS_APP_NAME} extension. This issue has been logged`}
/>
</LobbyLayout>
);
| 4,425
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Extension/ExtensionHead.tsx
|
import type { FC } from 'react';
import { Helmet } from 'react-helmet';
export const ExtensionHead: FC<{ title: string }> = ({ title }) => {
return (
<Helmet>
<link rel="icon" href={'/assets/protonpass-icon.svg'} type="image/svg+xml" />
<title>{title}</title>
</Helmet>
);
};
| 4,426
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Extension/PassExtensionCore.tsx
|
import { type FC, useCallback } from 'react';
import * as config from 'proton-pass-extension/app/config';
import { PassCoreProvider } from '@proton/pass/components/Core/PassCoreProvider';
import { API_PROXY_KEY } from '@proton/pass/lib/api/proxy';
import { resolveMessageFactory, sendMessage } from '@proton/pass/lib/extension/message';
import browser from '@proton/pass/lib/globals/browser';
import { type ClientEndpoint, type Maybe, type OtpRequest, WorkerMessageType } from '@proton/pass/types';
import type { TelemetryEvent } from '@proton/pass/types/data/telemetry';
import noop from '@proton/utils/noop';
const getDomainImageURL = (domain?: string): Maybe<string> => {
if (!domain) return;
const basePath = BUILD_TARGET === 'firefox' ? config.API_URL : API_PROXY_KEY;
return `${basePath}/core/v4/images/logo?Domain=${domain}&Size=32&Mode=light&MaxScaleUpFactor=4`;
};
const createOTPGenerator = (endpoint: ClientEndpoint) => (payload: OtpRequest) =>
sendMessage.on(
resolveMessageFactory(endpoint)({ type: WorkerMessageType.OTP_CODE_GENERATE, payload }),
(response) => (response.type === 'success' ? response : null)
);
const onLink = (url: string) => browser.tabs.create({ url }).catch(noop);
const createTelemetryHandler = (endpoint: ClientEndpoint) => (event: TelemetryEvent) =>
sendMessage(
resolveMessageFactory(endpoint)({
type: WorkerMessageType.TELEMETRY_EVENT,
payload: { event },
})
);
const openSettings = (page?: string) => {
const settingsUrl = browser.runtime.getURL('/settings.html');
const url = `${settingsUrl}#/${page ?? ''}`;
browser.tabs
.query({ url: settingsUrl })
.then(async (match) => {
await (match.length > 0 && match[0].id
? browser.tabs.update(match[0].id, { highlighted: true, url })
: browser.tabs.create({ url }));
window.close();
})
.catch(noop);
};
export const PassExtensionCore: FC<{ endpoint: ClientEndpoint }> = ({ children, endpoint }) => (
<PassCoreProvider
config={config}
generateOTP={useCallback(createOTPGenerator(endpoint), [])}
getDomainImageURL={getDomainImageURL}
onLink={onLink}
onTelemetry={useCallback(createTelemetryHandler(endpoint), [])}
openSettings={openSettings}
>
{children}
</PassCoreProvider>
);
| 4,427
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/ApplicationLogs.tsx
|
import { type VFC, useCallback, useEffect, useRef, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Icon } from '@proton/components/components';
import { pageMessage, sendMessage } from '@proton/pass/lib/extension/message';
import { type Maybe, type MaybeNull, WorkerMessageType } from '@proton/pass/types';
import { PASS_APP_NAME } from '@proton/shared/lib/constants';
import { SettingsPanel } from './SettingsPanel';
export const ApplicationLogs: VFC = () => {
const [showLogs, setShowLogs] = useState(false);
const [logs, setLogs] = useState<MaybeNull<string[]>>(null);
const intervalRef = useRef<Maybe<ReturnType<typeof setInterval>>>();
useEffect(() => {
const getLogs = () =>
sendMessage.onSuccess(pageMessage({ type: WorkerMessageType.LOG_REQUEST }), ({ logs }) => setLogs(logs));
void (showLogs && getLogs());
intervalRef.current = showLogs ? setInterval(getLogs, 1000) : undefined;
return () => clearInterval(intervalRef.current);
}, [showLogs]);
const downloadLogs = useCallback(() => {
void sendMessage.onSuccess(pageMessage({ type: WorkerMessageType.LOG_REQUEST }), ({ logs }) => {
const file = new File(
logs.map((line) => `${line}\n`),
`${PASS_APP_NAME}_logs_${Date.now()}`,
{ type: 'text/plain' }
);
const link = document.createElement('a');
const url = URL.createObjectURL(file);
link.href = url;
link.download = file.name;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
});
}, []);
return (
<SettingsPanel title={c('Label').t`Application logs`}>
{showLogs && logs && (
<>
<Button
icon
shape="ghost"
color="weak"
size="small"
onClick={() => setShowLogs(false)}
className="absolute top right mt-2 mr-2"
>
<Icon name="cross" size={12} />
</Button>
<div className="scroll-if-needed max-h-custom" style={{ '--max-h-custom': '18.75rem' }}>
{logs.map((log, i) => (
<span key={i} className="block text-xs color-weak">
{log}
</span>
))}
</div>
</>
)}
{!showLogs && (
<Button icon shape="ghost" className="w-full" onClick={() => setShowLogs(true)}>
<div className="flex flex-align-items-center">
<Icon name="window-terminal" className="mr-2" />
<span className="flex-item-fluid">{c('Label').t`View logs`}</span>
<Icon name="chevron-down" />
</div>
</Button>
)}
<hr className="border-weak my-2" />
<Button icon shape="ghost" onClick={downloadLogs} className="w-full">
<div className="flex flex-align-items-center flex flex-align-items-center">
<Icon name="arrow-down-to-square" className="mr-2" />
<span className="flex-item-fluid">{c('Label').t`Download logs`}</span>
</div>
</Button>
</SettingsPanel>
);
};
| 4,428
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/Behaviors.tsx
|
import type { ReactNode } from 'react';
import { type VFC, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import type { Dispatch } from 'redux';
import { c } from 'ttag';
import { Checkbox } from '@proton/components/components';
import { settingsEditIntent } from '@proton/pass/store/actions';
import { settingsEditRequest } from '@proton/pass/store/actions/requests';
import type { ProxiedSettings } from '@proton/pass/store/reducers/settings';
import {
selectAutosaveVault,
selectProxiedSettings,
selectRequestInFlight,
selectWritableVaults,
} from '@proton/pass/store/selectors';
import type { RecursivePartial } from '@proton/pass/types';
import { BRAND_NAME, PASS_APP_NAME } from '@proton/shared/lib/constants';
import clsx from '@proton/utils/clsx';
import { PauseList } from './PauseList';
import { SettingsPanel } from './SettingsPanel';
import { VaultSetting } from './VaultSetting';
type SettingDefinition = {
label: string;
description: string;
checked: boolean;
disabled?: boolean;
onChange: (value: boolean) => void;
};
type SettingsSection = {
label: string;
description?: string;
settings: SettingDefinition[];
extra?: ReactNode;
};
const getSettings =
(settings: ProxiedSettings) =>
(dispatch: Dispatch): SettingsSection[] => {
const onSettingsUpdate = (update: RecursivePartial<ProxiedSettings>) =>
dispatch(settingsEditIntent('behaviors', update));
return [
{
label: c('Label').t`Autofill`,
settings: [
{
label: c('Label').t`Display ${PASS_APP_NAME} icon on login fields`,
description: c('Info')
.t`You can quickly autofill your credentials by clicking on the ${PASS_APP_NAME} icon.`,
checked: settings.autofill.inject,
onChange: (checked) =>
onSettingsUpdate({
autofill: {
inject: checked,
...(!checked ? { openOnFocus: false } : {}),
},
}),
},
{
label: c('Label').t`Automatically open autofill when a login field is focused`,
description: c('Info')
.t`The autofill dropdown will automatically open when you click or focus on the field.`,
checked: settings.autofill.inject && settings.autofill.openOnFocus,
disabled: !settings.autofill.inject,
onChange: (checked) => onSettingsUpdate({ autofill: { openOnFocus: checked } }),
},
],
},
{
label: c('Label').t`Autosave`,
settings: [
{
label: c('Label').t`Prompt for auto-save`,
description: c('Info').t`${PASS_APP_NAME} will prompt you to save or update credentials.`,
checked: settings.autosave.prompt,
onChange: (checked) => onSettingsUpdate({ autosave: { prompt: checked } }),
},
],
extra: (
<VaultSetting
label={c('Label').t`Autosave vault`}
optionsSelector={selectWritableVaults}
valueSelector={selectAutosaveVault}
onSubmit={({ shareId }) => onSettingsUpdate({ autosave: { shareId } })}
/>
),
},
{
label: c('Label').t`Autosuggest`,
settings: [
{
label: c('Label').t`Passwords`,
description: c('Info')
.t`${PASS_APP_NAME} will suggest creating strong passwords on sign-up forms.`,
checked: settings.autosuggest.password,
onChange: (checked) => onSettingsUpdate({ autosuggest: { password: checked } }),
},
{
label: c('Label').t`Email aliases`,
description: c('Info')
.t`${PASS_APP_NAME} will suggest creating an email alias on sign-up forms.`,
checked: settings.autosuggest.email,
onChange: (checked) => onSettingsUpdate({ autosuggest: { email: checked } }),
},
],
},
{
label: c('Label').t`Display`,
settings: [
{
label: c('Label').t`Show website favicons`,
description: c('Info')
.t`${PASS_APP_NAME} will display the item favicon via ${BRAND_NAME} anonymized image proxy.`,
checked: settings.loadDomainImages,
onChange: (loadDomainImages) => onSettingsUpdate({ loadDomainImages }),
},
],
},
];
};
export const Behaviors: VFC = () => {
const dispatch = useDispatch();
const settings = useSelector(selectProxiedSettings);
const loading = useSelector(selectRequestInFlight(settingsEditRequest('behaviors')));
return (
<>
{useMemo(
() => getSettings(settings),
[settings]
)(dispatch).map((section, i) => (
<SettingsPanel key={`settings-section-${i}`} title={section.label}>
{section.settings.map((setting, j) => (
<Checkbox
key={`setting-${i}-${j}`}
className={clsx(j !== section.settings.length - 1 && 'mb-4')}
checked={setting.checked}
disabled={setting.disabled || loading}
loading={loading}
onChange={() => setting.onChange(!setting.checked)}
>
<span>
{setting.label}
<span className="block color-weak text-sm">{setting.description}</span>
</span>
</Checkbox>
))}
{section.extra && <hr className="mt-2 mb-4 border-weak" />}
{section.extra}
</SettingsPanel>
))}
<PauseList />
</>
);
};
| 4,429
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/Locale.tsx
|
import { type VFC } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { c } from 'ttag';
import { LocaleSelect } from '@proton/pass/components/Form/legacy/LocaleSelect';
import { settingsEditIntent } from '@proton/pass/store/actions';
import { selectLocale } from '@proton/pass/store/selectors';
import { DEFAULT_LOCALE } from '@proton/shared/lib/constants';
import { SettingsPanel } from './SettingsPanel';
export const Locale: VFC = () => {
const locale = useSelector(selectLocale);
const dispatch = useDispatch();
return (
<SettingsPanel title={c('Label').t`Language`}>
<LocaleSelect
value={locale ?? DEFAULT_LOCALE}
onChange={(locale) => dispatch(settingsEditIntent('locale', { locale }))}
/>
</SettingsPanel>
);
};
| 4,430
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/PauseList.scss
|
@import '~@proton/styles/scss/lib';
table {
th small {
display: block;
}
@include media('<=medium') {
tr {
position: relative;
td {
display: flex !important;
align-items: center;
gap: em(10);
label {
order: -1;
}
&.pass-pause-list--remove button {
position: absolute;
inset-block-start: em(10);
inset-inline-end: em(10);
}
&:first-of-type p {
display: none !important;
}
}
}
}
}
| 4,431
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/PauseList.tsx
|
import type { KeyboardEvent } from 'react';
import { type VFC, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import {
Checkbox,
Icon,
InputFieldTwo,
Table,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow,
} from '@proton/components/components';
import { useNotifications } from '@proton/components/hooks';
import { hasCriteria, toggleCriteria } from '@proton/pass/lib/settings/criteria';
import { settingsEditIntent } from '@proton/pass/store/actions';
import { selectDisallowedDomains } from '@proton/pass/store/selectors';
import type { CriteriaMasks } from '@proton/pass/types/worker/settings';
import { CRITERIAS_SETTING_CREATE, CRITERIA_MASKS } from '@proton/pass/types/worker/settings';
import { merge } from '@proton/pass/utils/object/merge';
import { parseUrl } from '@proton/pass/utils/url/parser';
import { PASS_SHORT_APP_NAME } from '@proton/shared/lib/constants';
import { SettingsPanel } from './SettingsPanel';
import './PauseList.scss';
const criterias = Object.keys(CRITERIA_MASKS) as CriteriaMasks[];
export const PauseList: VFC = () => {
const disallowedDomains = useSelector(selectDisallowedDomains);
const { createNotification } = useNotifications();
const dispatch = useDispatch();
const [url, setUrl] = useState<string>('');
const addDisallowedUrl = (url: string) => {
const { subdomain, domain } = parseUrl(url);
const hostname = subdomain ?? domain;
if (!hostname) return createNotification({ text: c('Error').t`Invalid URL`, type: 'error' });
if (disallowedDomains[hostname]) {
return createNotification({
text: c('Error').t`The URL is in the list`,
type: 'error',
});
}
dispatch(
settingsEditIntent('pause-list', {
disallowedDomains: merge(disallowedDomains, {
[hostname]: CRITERIAS_SETTING_CREATE,
}),
})
);
setUrl('');
};
const toggleUrlMask = (hostname: string, criteria: CriteriaMasks) => {
const setting = disallowedDomains[hostname];
dispatch(
settingsEditIntent('pause-list', {
disallowedDomains: merge(disallowedDomains, {
[hostname]: toggleCriteria(setting, criteria),
}),
})
);
};
const deleteDisallowedUrl = (hostname: string) => {
const update = { ...disallowedDomains };
delete update[hostname];
dispatch(settingsEditIntent('pause-list', { disallowedDomains: update }));
};
const nonEmptyList = Object.keys(disallowedDomains).length > 0;
const infoText = nonEmptyList ? ` ${c('Description').t`A checked box means the feature is disabled.`}` : '';
return (
<SettingsPanel
title={c('Label').t`Pause list`}
subTitle={c('Description')
.t`List of domains where certain auto functions in ${PASS_SHORT_APP_NAME} (Autofill, Autosuggest, Autosave) should not be run.${infoText}`}
>
{Object.keys(disallowedDomains).length > 0 && (
<Table responsive="cards" hasActions>
<TableHeader>
<TableRow>
<TableHeaderCell className="w-1/4">
<small>{c('Label').t`Domain`}</small>
</TableHeaderCell>
<TableHeaderCell>
<small>{c('Label').t`Autofill`}</small>
</TableHeaderCell>
<TableHeaderCell>
<small>{c('Label').t`Autofill 2FA`}</small>
</TableHeaderCell>
<TableHeaderCell>
<small>{c('Label').t`Autosuggest`}</small>
</TableHeaderCell>
<TableHeaderCell>
<small>{c('Label').t`Autosave`}</small>
</TableHeaderCell>
<TableHeaderCell>
<Icon name="pass-trash" size={16} className="mr-2" />
</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{Object.entries(disallowedDomains).map(([url, mask], i) => (
<TableRow key={`${url}-${i}`}>
<TableCell label={c('Label').t`Domains`}>
<div className="text-ellipsis">{url}</div>
</TableCell>
{criterias.map((criteria) => (
<TableCell
key={criteria}
label={(() => {
switch (criteria) {
case 'Autofill':
return c('Label').t`Autofill`;
case 'Autofill2FA':
return c('Label').t`Autofill 2FA`;
case 'Autosuggest':
return c('Label').t`Autosuggest`;
case 'Autosave':
return c('Label').t`Autosave`;
}
})()}
>
<Checkbox
checked={hasCriteria(mask, criteria)}
onChange={() => toggleUrlMask(url, criteria)}
/>
</TableCell>
))}
<TableCell className="pass-pause-list--remove">
<button
className="button button-pill button-for-icon button-solid-weak"
onClick={() => deleteDisallowedUrl(url)}
aria-label={c('Action').t`Remove`}
>
<Icon name="cross" size={12} />
</button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
<div className="flex mt-2">
<div className="flex-item-fluid mr-2">
<InputFieldTwo
value={url}
onValue={setUrl}
onKeyUp={(e: KeyboardEvent) => e.key === 'Enter' && addDisallowedUrl(url)}
dense
placeholder={'https://domain.com/path'}
/>
</div>
<Button color="norm" shape="solid" onClick={() => addDisallowedUrl(url)}>
{c('Action').t`Add domain to pause list`}
</Button>
</div>
</SettingsPanel>
);
};
| 4,432
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/ReportAProblem.tsx
|
import { type VFC, useRef } from 'react';
import { useSelector } from 'react-redux';
import type { FormikContextType, FormikErrors } from 'formik';
import { Form, FormikProvider, useFormik } from 'formik';
import { APP_NAME, APP_VERSION, CLIENT_TYPE } from 'proton-pass-extension/app/config';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { TextAreaTwo } from '@proton/components/components';
import { getClientName, getReportInfo } from '@proton/components/helpers/report';
import { useActionRequest } from '@proton/pass/hooks/useActionRequest';
import { reportBugIntent } from '@proton/pass/store/actions';
import { selectUser } from '@proton/pass/store/selectors';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { type BugPayload } from '@proton/shared/lib/api/reports';
import { SettingsPanel } from './SettingsPanel';
type FormValues = { description: string };
const INITIAL_VALUES: FormValues = { description: '' };
const REPORT_TITLE = 'Pass extension bug report';
const validate = ({ description }: FormValues): FormikErrors<FormValues> => {
const errors: FormikErrors<FormValues> = {};
if (isEmptyString(description)) {
errors.description = c('Warning').t`A description of the problem is required`;
}
return errors;
};
export const ReportAProblem: VFC = () => {
const user = useSelector(selectUser);
const formRef = useRef<FormikContextType<FormValues>>();
const reportBug = useActionRequest({ action: reportBugIntent, onSuccess: () => formRef.current?.resetForm() });
const form = useFormik<FormValues>({
initialValues: INITIAL_VALUES,
initialErrors: validate(INITIAL_VALUES),
validateOnChange: true,
validateOnMount: true,
validate,
onSubmit: async ({ description }) => {
const payload: BugPayload = {
...getReportInfo(),
Client: getClientName(APP_NAME),
ClientType: CLIENT_TYPE,
ClientVersion: APP_VERSION,
Title: REPORT_TITLE,
Username: user?.DisplayName || '',
Email: user?.Email || '',
Description: description,
};
reportBug.dispatch(payload);
},
});
formRef.current = form;
return (
<SettingsPanel
title={c('Label').t`Report a problem`}
subTitle={c('Warning')
.t`Reports are not end-to-end encrypted, please do not send any sensitive information.`}
>
<FormikProvider value={form}>
<Form>
<TextAreaTwo
className="mb-4"
id="description"
onChange={form.handleChange}
placeholder={c('Placeholder').t`Please describe the problem and include any error messages`}
autoGrow
minRows={5}
value={form.values.description}
disabled={reportBug.loading}
/>
<Button
className="mt-4 w-full"
color="norm"
disabled={!form.isValid}
loading={reportBug.loading}
type="submit"
>
{reportBug.loading && c('Action').t`Submitting report...`}
{!reportBug.loading && c('Action').t`Submit`}
</Button>
</Form>
</FormikProvider>
</SettingsPanel>
);
};
| 4,433
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/SettingsPanel.tsx
|
import type { FC, ReactNode } from 'react';
import { Card } from '@proton/atoms/Card';
type Props = {
title: string;
subTitle?: string;
children: ReactNode;
};
export const SettingsPanel: FC<Props> = ({ title, subTitle, children }) => (
<Card rounded className="mb-4 p-3 relative">
<strong className="color-norm block mb-1">{title}</strong>
{subTitle && <em className="block text-sm color-weak mb-2">{subTitle}</em>}
<hr className="mt-2 mb-4 border-weak" />
{children}
</Card>
);
| 4,434
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/VaultSetting.scss
|
.pass-vault--select-field {
padding: 0 !important;
}
| 4,435
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/VaultSetting.tsx
|
/* TODO: move this to shared components */
import { type VFC } from 'react';
import type { Selector } from 'react-redux';
import { useSelector } from 'react-redux';
import { Form, FormikProvider, useFormik } from 'formik';
import { Field } from '@proton/pass/components/Form/Field/Field';
import { VaultSelectField } from '@proton/pass/components/Form/Field/VaultSelectField';
import type { ShareItem } from '@proton/pass/store/reducers';
import type { State } from '@proton/pass/store/types';
import type { Maybe, ShareType } from '@proton/pass/types';
import './VaultSetting.scss';
type FormValues = { shareId: Maybe<string> };
type Props = {
label: string;
onSubmit: (share: ShareItem<ShareType.Vault>) => void;
optionsSelector: Selector<State, ShareItem<ShareType.Vault>[]>;
valueSelector: Selector<State, Maybe<ShareItem<ShareType.Vault>>>;
};
export const VaultSetting: VFC<Props> = ({ label, onSubmit, optionsSelector, valueSelector }) => {
const vaults = useSelector(optionsSelector);
const shareId = useSelector(valueSelector)?.shareId;
const form = useFormik<FormValues>({
initialValues: { shareId },
enableReinitialize: true,
onSubmit: async (values) => {
const match = vaults.find((vault) => vault.shareId === values.shareId);
if (match && match.shareId !== shareId) onSubmit(match);
},
});
return (
<div>
<FormikProvider value={form}>
<Form>
<Field
name="shareId"
className="pass-vault--select-field pass-input-group--no-focus"
component={VaultSelectField}
label={label}
onValue={() => form.handleSubmit()}
/>
</Form>
</FormikProvider>
</div>
);
};
| 4,436
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/debug/DropdownDebug.tsx
|
import type { ReactNode, VFC } from 'react';
import { DEFAULT_RANDOM_PW_OPTIONS } from '@proton/pass/hooks/usePasswordGenerator';
import type { SafeLoginItem } from '@proton/pass/types';
import { AppStatus } from '@proton/pass/types';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
import { DROPDOWN_WIDTH } from '../../../../app/content/constants.static';
import { DropdownSwitch } from '../../../../app/content/injections/apps/dropdown/components/DropdownSwitch';
import { DropdownAction } from '../../../../app/content/types';
import { SettingsPanel } from '../SettingsPanel';
const LOGIN_ITEMS: SafeLoginItem[] = [
{
name: 'Netflix account',
username: 'netflix+nobody@proton.me',
shareId: uniqueId(),
itemId: uniqueId(),
url: 'https://netflix.com',
},
{
name: 'Proton credentials',
username: 'nobody@proton.me',
shareId: uniqueId(),
itemId: uniqueId(),
},
];
const MockIFrameContainer: VFC<{ children: ReactNode }> = ({ children }) => (
<div
style={{
width: '100%',
maxWidth: DROPDOWN_WIDTH,
overflow: 'hidden',
background: '#191927',
boxShadow: '0 2px 10px rgb(0 0 0 / 0.3)',
borderRadius: 12,
marginBottom: 12,
}}
>
{children}
</div>
);
export const DropdownDebug: VFC = () => {
return (
<SettingsPanel title="Dropdown">
<div className="gap-4" style={{ columnCount: 2 }}>
<MockIFrameContainer>
<DropdownSwitch loggedIn={false} status={AppStatus.IDLE} state={null} />
</MockIFrameContainer>
<MockIFrameContainer>
<DropdownSwitch
loggedIn={false}
status={AppStatus.READY}
state={{
action: DropdownAction.AUTOFILL,
hostname: 'proton.me',
needsUpgrade: false,
items: [],
}}
/>
</MockIFrameContainer>
<MockIFrameContainer>
<DropdownSwitch
loggedIn={false}
status={AppStatus.LOCKED}
state={{
action: DropdownAction.AUTOFILL,
hostname: 'proton.me',
needsUpgrade: false,
items: [],
}}
/>
</MockIFrameContainer>
<MockIFrameContainer>
<DropdownSwitch
loggedIn
status={AppStatus.READY}
state={{
action: DropdownAction.AUTOFILL,
hostname: 'proton.me',
needsUpgrade: false,
items: [LOGIN_ITEMS[1]],
}}
/>
</MockIFrameContainer>
<MockIFrameContainer>
<DropdownSwitch
loggedIn
status={AppStatus.READY}
state={{
action: DropdownAction.AUTOFILL,
hostname: 'proton.me',
needsUpgrade: true,
items: [LOGIN_ITEMS[0]],
}}
/>
</MockIFrameContainer>
<MockIFrameContainer>
<DropdownSwitch
loggedIn
status={AppStatus.READY}
state={{
action: DropdownAction.AUTOFILL,
hostname: 'proton.me',
needsUpgrade: false,
items: LOGIN_ITEMS,
}}
/>
</MockIFrameContainer>
<MockIFrameContainer>
<DropdownSwitch
loggedIn
status={AppStatus.READY}
state={{
action: DropdownAction.AUTOSUGGEST_PASSWORD,
options: DEFAULT_RANDOM_PW_OPTIONS,
hostname: 'proton.me',
}}
/>
</MockIFrameContainer>
<MockIFrameContainer>
<DropdownSwitch
loggedIn
status={AppStatus.READY}
state={{ action: DropdownAction.AUTOSUGGEST_ALIAS, hostname: 'proton.me', prefix: 'secret' }}
/>
</MockIFrameContainer>
</div>
</SettingsPanel>
);
};
| 4,437
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/components/Settings/debug/NotificationDebug.tsx
|
import type { ReactNode, VFC } from 'react';
import { useSelector } from 'react-redux';
import type { ProxiedSettings } from '@proton/pass/store/reducers/settings';
import { selectItemsByType } from '@proton/pass/store/selectors';
import { AutoSaveType, FormEntryStatus } from '@proton/pass/types';
import { NOTIFICATION_HEIGHT, NOTIFICATION_WIDTH } from '../../../../app/content/constants.static';
import { NotificationSwitch } from '../../../../app/content/injections/apps/notification/components/NotificationSwitch';
import { NotificationAction } from '../../../../app/content/types';
import { SettingsPanel } from '../SettingsPanel';
const MockIFrameContainer: VFC<{ children: ReactNode; height?: number }> = ({
children,
height = NOTIFICATION_HEIGHT,
}) => (
<div
style={{
width: NOTIFICATION_WIDTH,
height,
overflow: 'hidden',
background: '#191927',
boxShadow: '0 2px 10px rgb(0 0 0 / 0.3)',
borderRadius: 12,
marginBottom: 12,
}}
>
{children}
</div>
);
const MockSettings = { loadDomainImages: true } as ProxiedSettings;
export const NotificationDebug: VFC = () => {
const otpItem = useSelector(selectItemsByType('login')).find((item) => Boolean(item.data.content.totpUri.v));
return (
<SettingsPanel title="Notification">
<div className="gap-4" style={{ columnCount: 2 }}>
<MockIFrameContainer>
<NotificationSwitch state={null} settings={MockSettings} />
</MockIFrameContainer>
<MockIFrameContainer>
<NotificationSwitch
state={{
action: NotificationAction.AUTOSAVE_PROMPT,
submission: {
status: FormEntryStatus.COMMITTED,
domain: 'proton.me',
subdomain: null,
type: 'login',
partial: false,
autosave: {
shouldPrompt: true,
data: { action: AutoSaveType.NEW },
},
data: {
username: 'nobody@proton.me',
password: 'proton123',
},
},
}}
settings={MockSettings}
/>
</MockIFrameContainer>
<MockIFrameContainer>
<NotificationSwitch
state={{
action: NotificationAction.AUTOSAVE_PROMPT,
submission: {
status: FormEntryStatus.COMMITTED,
domain: 'netflix.com',
subdomain: null,
type: 'login',
partial: false,
autosave: {
shouldPrompt: true,
data: {
action: AutoSaveType.UPDATE,
item: {
data: {
type: 'login',
metadata: { name: 'netflix.com', note: 'Autosaved', itemUuid: '' },
content: {
username: 'nobody@proton.me',
password: '',
urls: [],
totpUri: '',
},
extraFields: [],
},
} as any,
},
},
data: {
username: 'nobody@proton.me',
password: 'password',
},
},
}}
settings={MockSettings}
/>
</MockIFrameContainer>
{otpItem && (
<MockIFrameContainer height={220}>
<NotificationSwitch
state={{
action: NotificationAction.AUTOFILL_OTP_PROMPT,
item: { shareId: otpItem.shareId, itemId: otpItem.itemId },
hostname: 'proton.me',
}}
settings={MockSettings}
/>
</MockIFrameContainer>
)}
</div>
</SettingsPanel>
);
};
| 4,438
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/context/extension-context.ts
|
import { generatePortName } from 'proton-pass-extension/lib/utils/port';
import type { Runtime } from 'webextension-polyfill';
import { resolveMessageFactory, sendMessage } from '@proton/pass/lib/extension/message';
import { getCurrentTab } from '@proton/pass/lib/extension/utils/tabs';
import browser from '@proton/pass/lib/globals/browser';
import { type ClientEndpoint, type TabId, WorkerMessageType } from '@proton/pass/types';
import { createSharedContext } from '@proton/pass/utils/context';
import { safeCall } from '@proton/pass/utils/fp/safe-call';
import { logger } from '@proton/pass/utils/logger';
import type { ParsedUrl } from '@proton/pass/utils/url/parser';
import { parseUrl } from '@proton/pass/utils/url/parser';
import.meta.webpackHot?.decline();
export type ExtensionContextType = {
endpoint: ClientEndpoint;
tabId: TabId;
port: Runtime.Port;
url: ParsedUrl;
destroy: () => void;
};
export type ExtensionContextOptions = {
endpoint: ClientEndpoint;
onDisconnect: (previousCtx?: ExtensionContextType) => { recycle: boolean };
onRecycle: (nextCtx: ExtensionContextType) => void;
};
export const ExtensionContext = createSharedContext<ExtensionContextType>('extension');
export const setupExtensionContext = async (options: ExtensionContextOptions): Promise<ExtensionContextType> => {
const { endpoint, onDisconnect, onRecycle } = options;
try {
const tab = await getCurrentTab();
if (tab !== undefined && tab.id !== undefined) {
const name = generatePortName(endpoint, tab.id);
const port = browser.runtime.connect(browser.runtime.id, { name });
const ctx = ExtensionContext.set({
endpoint,
port,
tabId: tab.id,
url: parseUrl(tab.url ?? ''),
destroy: () => {
safeCall(() => port.disconnect())();
ExtensionContext.clear();
},
});
logger.setLogOptions({
onLog: (log, originalLog) => {
void sendMessage(
resolveMessageFactory(endpoint)({
type: WorkerMessageType.LOG_EVENT,
payload: { log },
})
);
return ENV === 'development' && originalLog(log);
},
});
logger.info('[Context::Extension] tabId resolved & port opened');
ctx.port.onDisconnect.addListener(async () => {
logger.info('[Context::Extension] port disconnected - reconnecting');
const { recycle } = onDisconnect?.(ExtensionContext.read());
return recycle && onRecycle(await setupExtensionContext(options));
});
return ctx;
}
throw new Error('Invalid runtime');
} catch (e) {
logger.warn('[Context::Extension]', e);
throw new Error('Initalization failed');
}
};
| 4,439
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useExpandPopup.ts
|
import { useCallback } from 'react';
import browser from '@proton/pass/lib/globals/browser';
import { pixelParser } from '@proton/pass/utils/dom/computed-styles';
import noop from '@proton/utils/noop';
export const useExpandPopup = () =>
useCallback(() => {
const rootStyles = getComputedStyle(document.documentElement);
browser.windows
.create({
url: browser.runtime.getURL('popup.html'),
type: 'popup',
width: pixelParser(rootStyles.getPropertyValue('--popup-width')),
height: pixelParser(rootStyles.getPropertyValue('--popup-height')),
focused: true,
})
.catch(noop);
}, []);
| 4,440
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useExpanded.ts
|
import { useEffect, useState } from 'react';
import browser from '@proton/pass/lib/globals/browser';
import noop from '@proton/utils/noop';
export const useExpanded = () => {
const [expanded, setExpanded] = useState(false);
useEffect(() => {
browser.tabs
.getCurrent()
.then((tab) => setExpanded(tab !== undefined))
.catch(noop);
}, []);
useEffect(() => {
if (expanded) {
/* when pop-up is expanded: reset the dimension constraints */
document.documentElement.style.setProperty('--popup-width', '100%');
document.documentElement.style.setProperty('--popup-height', '100%');
}
}, [expanded]);
return expanded;
};
| 4,441
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useExtensionConnectContext.ts
|
import { useContext } from 'react';
import { ExtensionConnectContext } from '../components/Extension/ExtensionConnect';
export const useExtensionConnectContext = () => useContext(ExtensionConnectContext);
| 4,442
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useItems.ts
|
import { useContext } from 'react';
import { useSelector } from 'react-redux';
import { selectItemsSearchResult } from '@proton/pass/store/selectors';
import { ItemsFilteringContext } from '../components/Context/Items/ItemsFilteringContext';
export const useItems = (options?: { trashed: boolean }) => {
const filtering = useContext(ItemsFilteringContext);
const { search, sort, type, shareId } = filtering;
const matchedAndFilteredItems = useSelector(
selectItemsSearchResult(
options?.trashed
? { search, trashed: true }
: {
search,
shareId,
sort,
trashed: false,
type: type === '*' ? null : type,
}
)
);
return { filtering, ...matchedAndFilteredItems };
};
| 4,443
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useItemsFilteringContext.ts
|
import { useContext } from 'react';
import { ItemsFilteringContext } from '../components/Context/Items/ItemsFilteringContext';
export const useItemsFilteringContext = () => useContext(ItemsFilteringContext);
| 4,444
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useNavigationContext.ts
|
import { useContext } from 'react';
import { NavigationContext } from 'proton-pass-extension/lib/components/Context/Navigation/NavigationContext';
export const useNavigationContext = () => useContext(NavigationContext);
| 4,445
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useOpenSettingsTab.ts
|
import { useCallback } from 'react';
import browser from '@proton/pass/lib/globals/browser';
/* use PassCore::openSettings and remove this */
export const useOpenSettingsTab = () => {
return useCallback(async (page?: string) => {
try {
const settingsUrl = browser.runtime.getURL('/settings.html');
const url = `${settingsUrl}#/${page ?? ''}`;
const match = await browser.tabs.query({ url: settingsUrl });
await (match.length > 0 && match[0].id
? browser.tabs.update(match[0].id, { highlighted: true, url })
: browser.tabs.create({ url }));
window.close();
} catch (_) {}
}, []);
};
| 4,446
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/usePermissionsGranted.ts
|
import { useCallback, useEffect, useState } from 'react';
import { WorkerMessageType, type WorkerMessageWithSender } from '@proton/pass/types';
import { checkExtensionPermissions } from '../utils/permissions';
import { useExtensionConnectContext } from './useExtensionConnectContext';
/* On hook first run : we programatically check the permissions
* using the browser API. We then setup a listener for the worker
* `PERMISSIONS_UPDATE` message in order to gracefully handle changes
* while the clients are running */
export const usePermissionsGranted = (): boolean => {
const [valid, setValid] = useState<boolean>(false);
const { context: extensionContext } = useExtensionConnectContext();
const checkForPermissions = useCallback(async () => {
try {
const check = await checkExtensionPermissions();
setValid(check);
} catch (_) {}
}, []);
useEffect(() => {
const handleMessage = (message: WorkerMessageWithSender) => {
if (message.sender === 'background' && message.type === WorkerMessageType.PERMISSIONS_UPDATE) {
setValid(message.payload.check);
}
};
void checkForPermissions();
extensionContext?.port.onMessage.addListener(handleMessage);
return () => extensionContext?.port.onMessage.removeListener(handleMessage);
}, []);
return valid;
};
| 4,447
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/usePopupContext.ts
|
import { useContext } from 'react';
import { PopupContext } from 'proton-pass-extension/lib/components/Context/Popup/PopupContext';
export const usePopupContext = () => useContext(PopupContext);
| 4,448
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/usePopupSizeSurgery.ts
|
import { useEffect } from 'react';
import { pixelParser } from '@proton/pass/utils/dom/computed-styles';
import noop from '@proton/utils/noop';
import { isVivaldiBrowser } from '../utils/vivaldi';
/* Adjusts the size of the popup element to account for inconsistent sizing behavior
* when the user changes the default page zoom in their browser settings. */
export const usePopupSizeSurgery = () => {
useEffect(() => {
if (BUILD_TARGET === 'chrome') {
const rootStyles = getComputedStyle(document.documentElement);
const popupWidth = pixelParser(rootStyles.getPropertyValue('--popup-width'));
const onResize = () => {
const { clientWidth, clientHeight } = document.documentElement;
if (clientWidth !== popupWidth) {
document.documentElement.style.setProperty('--popup-width', `${clientWidth}px`);
document.documentElement.style.setProperty('--popup-height', `${clientHeight}px`);
}
};
isVivaldiBrowser()
.then((isVivaldi) => {
if (!isVivaldi) {
onResize();
window.addEventListener('resize', onResize);
}
})
.catch(noop);
return () => window.removeEventListener('resize', onResize);
}
}, []);
};
| 4,449
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useRequestFork.ts
|
import { c } from 'ttag';
import { useNotifications } from '@proton/components/hooks';
import { requestFork } from '@proton/pass/lib/auth/fork';
import browser from '@proton/pass/lib/globals/browser';
import type { FORK_TYPE } from '@proton/shared/lib/authentication/ForkInterface';
import { APPS, PASS_APP_NAME } from '@proton/shared/lib/constants';
import noop from '@proton/utils/noop';
import { SSO_URL } from '../../app/config';
import { promptForPermissions } from '../utils/permissions';
import { usePermissionsGranted } from './usePermissionsGranted';
/* depending on where we execute this : we may or may not
* have access to the tabs API - Firefox content-scripts have
* very limited support for the tabs API */
export const useRequestFork = () => async (type?: FORK_TYPE, replace?: boolean) => {
const { url } = requestFork({ host: SSO_URL, type, app: APPS.PROTONEXTENSION });
if (replace) return window.location.replace(url);
return browser.tabs ? browser.tabs.create({ url }).catch(noop) : window.open(url, '_BLANK');
};
/* before navigating to login we should prompt the
* user for any extension permissions required for PASS
* to work correctly. IE: on FF we absolutely need the user
* to do so for fallback account communication to work */
export const useRequestForkWithPermissions = (options?: { autoClose?: boolean; replace?: boolean }) => {
const { createNotification } = useNotifications();
const accountFork = useRequestFork();
const permissionsGranted = usePermissionsGranted();
return async (type?: FORK_TYPE) => {
if (permissionsGranted || (await promptForPermissions())) {
return accountFork(type, options?.replace).finally(async () => {
if (options?.autoClose) window.close();
});
}
createNotification({
type: 'error',
text: c('Error').t`Please grant ${PASS_APP_NAME} the necessary extension permissions in order to continue`,
expiration: -1,
});
};
};
| 4,450
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useSelectItemClick.ts
|
import { type MouseEvent, useCallback } from 'react';
import type { NavigationOptions } from 'proton-pass-extension/lib/components/Context/Navigation/NavigationContext';
import { popupMessage, sendMessage } from '@proton/pass/lib/extension/message';
import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event';
import { type ItemRevision, WorkerMessageType } from '@proton/pass/types';
import { TelemetryEventName } from '@proton/pass/types/data/telemetry';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { useItemsFilteringContext } from './useItemsFilteringContext';
import { useNavigationContext } from './useNavigationContext';
export const useSelectItemClick = () => {
const { selectItem } = useNavigationContext();
const { search } = useItemsFilteringContext();
return useCallback(
(item: ItemRevision, options?: NavigationOptions) => (evt: MouseEvent<HTMLElement>) => {
evt.preventDefault();
selectItem(item.shareId, item.itemId, options);
void sendMessage(
popupMessage({
type: WorkerMessageType.TELEMETRY_EVENT,
payload: {
event: createTelemetryEvent(TelemetryEventName.ItemRead, {}, { type: item.data.type }),
},
})
);
void (
!isEmptyString(search) &&
sendMessage(
popupMessage({
type: WorkerMessageType.TELEMETRY_EVENT,
payload: {
event: createTelemetryEvent(TelemetryEventName.SearchClick, {}, { type: item.data.type }),
},
})
)
);
},
[search]
);
};
| 4,451
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useShareEventEffect.ts
|
import { useEffect, useRef } from 'react';
import type { WorkerMessageWithSender } from '@proton/pass/types';
import { ShareEventType, WorkerMessageType } from '@proton/pass/types';
import { ExtensionContext } from '../context/extension-context';
type UseShareServerEventHookOptions = {
onShareDisabled: (shareId: string) => void;
onItemsDeleted?: (shareId: string, itemIds: string[]) => void;
};
export const useShareEventEffect = (options: UseShareServerEventHookOptions) => {
const optionsRef = useRef<UseShareServerEventHookOptions>(options);
useEffect(() => {
optionsRef.current = options;
}, [options]);
useEffect(() => {
const { port } = ExtensionContext.get();
const handleShareServerEvent = (message: WorkerMessageWithSender) => {
if (message.sender === 'background' && message.type === WorkerMessageType.SHARE_SERVER_EVENT) {
const { payload } = message;
switch (payload.type) {
case ShareEventType.SHARE_DISABLED:
return optionsRef.current.onShareDisabled(payload.shareId);
case ShareEventType.ITEMS_DELETED:
const { shareId, itemIds } = payload;
return optionsRef.current.onItemsDeleted?.(shareId, itemIds);
}
}
};
port.onMessage.addListener(handleShareServerEvent);
return () => port.onMessage.removeListener(handleShareServerEvent);
}, []);
};
| 4,452
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useSpotlightEffect.ts
|
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSelector } from 'react-redux';
import { c } from 'ttag';
import { getSimplePriceString } from '@proton/components/components/price/helper';
import { useInviteContext } from '@proton/pass/components/Invite/InviteContextProvider';
import type { SpotlightMessageDefinition } from '@proton/pass/components/Spotlight/SpotlightContent';
import { useSpotlightContext } from '@proton/pass/components/Spotlight/SpotlightContext';
import { FiveStarIcon, InviteIcon, ShieldIcon } from '@proton/pass/components/Spotlight/SpotlightIcon';
import { PASS_BF_MONTHLY_PRICE } from '@proton/pass/constants';
import { useFeatureFlag } from '@proton/pass/hooks/useFeatureFlag';
import { usePassConfig } from '@proton/pass/hooks/usePassConfig';
import { popupMessage, sendMessage } from '@proton/pass/lib/extension/message';
import { detectBrowser, getWebStoreUrl } from '@proton/pass/lib/extension/utils/browser';
import browser from '@proton/pass/lib/globals/browser';
import { selectUser } from '@proton/pass/store/selectors';
import { selectMostRecentInvite } from '@proton/pass/store/selectors/invites';
import type { Callback, MaybeNull, WorkerMessageWithSender } from '@proton/pass/types';
import { OnboardingMessage, WorkerMessageType } from '@proton/pass/types';
import { PassFeature } from '@proton/pass/types/api/features';
import { BRAND_NAME, PASS_APP_NAME, PASS_SHORT_APP_NAME } from '@proton/shared/lib/constants';
import { wait } from '@proton/shared/lib/helpers/promise';
import noop from '@proton/utils/noop';
import { promptForPermissions } from '../utils/permissions';
import { useExtensionConnectContext } from './useExtensionConnectContext';
import { useOpenSettingsTab } from './useOpenSettingsTab';
export const useSpotlightEffect = () => {
const { context: extensionContext } = useExtensionConnectContext();
const invite = useInviteContext();
const spotlight = useSpotlightContext();
const webStoreURL = getWebStoreUrl(detectBrowser());
const { SSO_URL } = usePassConfig();
const sharingEnabled = useFeatureFlag(PassFeature.PassSharingV1);
const latestInvite = useSelector(selectMostRecentInvite);
const [message, setMessage] = useState<MaybeNull<OnboardingMessage>>(null);
const user = useSelector(selectUser);
const openSettings = useOpenSettingsTab();
useEffect(() => {
/* If the latest invite was promoted from a new user invite,
* auto prompt the "respond to invite" modal */
if (latestInvite?.fromNewUser) invite.respondToInvite(latestInvite);
}, [latestInvite]);
const inviteMessage = useMemo<MaybeNull<SpotlightMessageDefinition>>(
() =>
sharingEnabled && latestInvite && !latestInvite.fromNewUser
? {
id: latestInvite.token,
weak: true,
dense: false,
title: c('Title').t`Vault shared with you`,
message: c('Info').t`You're invited to a vault.`,
icon: InviteIcon,
action: {
label: c('Label').t`View details`,
type: 'button',
onClick: () => invite.respondToInvite(latestInvite),
},
}
: null,
[latestInvite]
);
const withAcknowledgment = useCallback(
(cb: Callback = noop) =>
() => {
if (message) {
void sendMessage(
popupMessage({
type: WorkerMessageType.ONBOARDING_ACK,
payload: { message },
})
);
}
cb();
setMessage(null);
},
[message]
);
const definitions = useMemo<{ [K in OnboardingMessage]: SpotlightMessageDefinition }>(
() => ({
[OnboardingMessage.PENDING_SHARE_ACCESS]: {
id: 'welcome',
title: c('Title').t`Pending access to the shared data`,
message: c('Info').t`For security reasons, your access needs to be confirmed`,
weak: true,
onClose: withAcknowledgment(() => spotlight.setPendingShareAccess(false)),
},
[OnboardingMessage.WELCOME]: {
id: 'welcome',
title: c('Title').t`Why ${PASS_APP_NAME}?`,
message: c('Info').t`Privacy is a big concern for us. Learn why ${PASS_APP_NAME} is different.`,
className: 'ui-teal',
icon: ShieldIcon,
onClose: withAcknowledgment(noop),
action: {
label: c('Label').t`Learn more`,
type: 'link',
onClick: withAcknowledgment(() => browser.tabs.create({ url: 'https://proton.me/pass' })),
},
},
[OnboardingMessage.TRIAL]: {
id: 'trial',
title: c('Title').t`Our welcome gift to you`,
message: c('Info')
.t`7 days to try premium features for free. Only during your first week of ${BRAND_NAME}.`,
className: 'ui-orange',
onClose: withAcknowledgment(noop),
action: {
label: c('Label').t`Learn more`,
type: 'link',
onClick: () => spotlight.setUpselling('free-trial'),
},
},
[OnboardingMessage.SECURE_EXTENSION]: {
id: 'pin',
title: c('Title').t`Secure your data`,
message: c('Info').t`Set up a PIN code to easily lock your data`,
className: 'ui-violet',
icon: ShieldIcon,
onClose: withAcknowledgment(noop),
action: {
label: c('Label').t`Set PIN code`,
type: 'button',
onClick: withAcknowledgment(() => openSettings('security')),
},
},
[OnboardingMessage.UPDATE_AVAILABLE]: {
id: 'update',
title: c('Title').t`Update available`,
message: c('Info')
.t`A new version of ${PASS_APP_NAME} is available. Update it to enjoy the latest features and bug fixes.`,
className: 'ui-orange',
onClose: withAcknowledgment(noop),
action: {
label: c('Label').t`Update`,
type: 'button',
onClick: withAcknowledgment(() => browser.runtime.reload()),
},
},
[OnboardingMessage.PERMISSIONS_REQUIRED]: {
id: 'permissions',
title: c('Title').t`Grant permissions`,
message: c('Info')
.t`In order to get the best experience out of ${PASS_APP_NAME}, please grant the necessary extension permissions`,
className: 'ui-orange',
onClose: withAcknowledgment(noop),
action: {
label: c('Label').t`Grant`,
type: 'button',
onClick: withAcknowledgment(() => promptForPermissions()),
},
},
[OnboardingMessage.USER_RATING]: {
id: 'rating',
title: c('Title').t`Enjoying ${PASS_APP_NAME}?`,
message: c('Info').t`Please consider leaving a review.`,
className: 'ui-lime',
icon: FiveStarIcon,
onClose: withAcknowledgment(noop),
action: {
label: c('Label').t`Rate us`,
type: 'button',
onClick: withAcknowledgment(() => window.open(webStoreURL, '_blank')),
},
},
[OnboardingMessage.STORAGE_ISSUE]: {
id: 'storage',
title: c('Title').t`Low disk space`,
message: c('Info')
.t`We are having trouble syncing data to your local storage. Please make sure you have sufficient disk space for ${PASS_SHORT_APP_NAME} to work smoothly.`,
className: 'ui-red',
onClose: withAcknowledgment(noop),
action: {
label: c('Label').t`Need help ?`,
type: 'button',
onClick: withAcknowledgment(() => openSettings('support')),
},
},
[OnboardingMessage.BLACK_FRIDAY_OFFER]: {
id: 'black-friday',
title: c('bf2023: Title').t`Black Friday offer`,
message: (() => {
const relativePrice = getSimplePriceString(user!.Currency, PASS_BF_MONTHLY_PRICE, '');
return c('bf2023: Info')
.t`Save Smart. Get a year of Pass Plus for only ${relativePrice} per month.`;
})(),
className: 'ui-orange',
onClose: withAcknowledgment(noop),
action: {
label: c('bf2023: Label').t`Get the deal`,
type: 'button',
onClick: withAcknowledgment(() =>
window.open(`${SSO_URL}/pass/dashboard?plan=pass2023&coupon=BF2023&cycle=12`, '_blank')
),
},
},
}),
[message]
);
useEffect(() => {
const handleMessage = (message: WorkerMessageWithSender) => {
if (message.sender === 'background') {
switch (message.type) {
case WorkerMessageType.UPDATE_AVAILABLE:
setMessage(OnboardingMessage.UPDATE_AVAILABLE);
break;
case WorkerMessageType.PERMISSIONS_UPDATE:
setMessage(OnboardingMessage.PERMISSIONS_REQUIRED);
break;
}
}
};
void sendMessage.onSuccess(
popupMessage({ type: WorkerMessageType.ONBOARDING_REQUEST }),
async ({ message }) => {
await wait(200);
setMessage(message ?? null);
if (message === OnboardingMessage.PENDING_SHARE_ACCESS) spotlight.setPendingShareAccess(true);
}
);
extensionContext?.port.onMessage.addListener(handleMessage);
return () => extensionContext?.port.onMessage.removeListener(handleMessage);
}, [extensionContext]);
useEffect(() => {
const activeMessage = inviteMessage ?? (message !== null ? definitions[message] : null);
spotlight.setMessage(activeMessage);
}, [inviteMessage, message]);
};
| 4,453
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/hooks/useWorkerStateEvents.ts
|
import { useEffect } from 'react';
import { ExtensionContext } from 'proton-pass-extension/lib/context/extension-context';
import type { MessageWithSenderFactory } from '@proton/pass/lib/extension/message';
import { sendMessage } from '@proton/pass/lib/extension/message';
import type {
AppState,
ClientEndpoint,
TabId,
WorkerMessageResponse,
WorkerMessageWithSender,
} from '@proton/pass/types';
import { AppStatus, WorkerMessageType } from '@proton/pass/types';
import { logger } from '@proton/pass/utils/logger';
type WakeupOptions = { tabId: TabId; endpoint: ClientEndpoint; messageFactory: MessageWithSenderFactory };
type UseWorkerStateEventsOptions = WakeupOptions & { onWorkerStateChange: (state: AppState) => void };
const wakeup = (options: WakeupOptions): Promise<WorkerMessageResponse<WorkerMessageType.WORKER_WAKEUP>> =>
sendMessage.on(
options.messageFactory({
type: WorkerMessageType.WORKER_WAKEUP,
payload: { tabId: options.tabId },
}),
(response) => {
if (response.type === 'success') return response;
else {
logger.warn(`[Endpoint::${options.endpoint}] wakeup failed`, response.error);
throw new Error();
}
}
);
export const useWorkerStateEvents = ({ onWorkerStateChange, ...options }: UseWorkerStateEventsOptions) => {
useEffect(() => {
const onMessage = (message: WorkerMessageWithSender) => {
if (message.sender === 'background' && message.type === WorkerMessageType.WORKER_STATUS) {
onWorkerStateChange(message.payload.state);
}
};
ExtensionContext.get().port.onMessage.addListener(onMessage);
wakeup(options)
.then(({ UID, loggedIn, status }) => onWorkerStateChange({ UID, loggedIn, status }))
.catch(() => onWorkerStateChange({ UID: undefined, loggedIn: false, status: AppStatus.ERROR }));
return () => ExtensionContext.get().port.onMessage.removeListener(onMessage);
}, []);
};
| 4,454
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/store/client-store.ts
|
import { devToolsEnhancer } from '@redux-devtools/remote';
import { configureStore } from '@reduxjs/toolkit';
import { requestMiddleware } from '@proton/pass/store/middlewares/request-middleware';
import reducer from '@proton/pass/store/reducers';
import type { ClientEndpoint, TabId } from '@proton/pass/types';
import { proxyActionsMiddleware } from './proxy-actions.middleware';
export const createClientStore = (endpoint: ClientEndpoint, tabId: TabId) => {
const store = configureStore({
reducer,
middleware: [requestMiddleware, proxyActionsMiddleware({ endpoint, tabId })],
enhancers:
ENV === 'development'
? [
devToolsEnhancer({
name: `${endpoint}-${tabId}`,
realtime: true,
port: REDUX_DEVTOOLS_PORT,
}),
]
: [],
});
return store;
};
| 4,455
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/store/proxy-actions.middleware.ts
|
import { ExtensionContext } from 'proton-pass-extension/lib/context/extension-context';
import type { AnyAction, Middleware } from 'redux';
import { resolveMessageFactory, sendMessage } from '@proton/pass/lib/extension/message';
import { acceptActionWithReceiver, withSender } from '@proton/pass/store/actions/with-receiver';
import { isClientSynchronousAction } from '@proton/pass/store/actions/with-synchronous-client-action';
import type { ClientEndpoint, TabId, WorkerMessageWithSender } from '@proton/pass/types';
import { WorkerMessageType } from '@proton/pass/types';
import noop from '@proton/utils/noop';
/*
* This middleware eats all actions coming through on purpose and sends them
* to the worker for re-emission. This is to guarantee the same order of event
* occurrence throughout worker, popup and content.
*
* It also listens for actions being emitted by the worker to re-integrate into
* its local pipeline.
*/
type ProxyActionsMiddlewareOptions = {
endpoint: ClientEndpoint;
tabId: TabId;
};
export const proxyActionsMiddleware = ({ endpoint, tabId }: ProxyActionsMiddlewareOptions): Middleware => {
const messageFactory = resolveMessageFactory(endpoint);
return () => (next) => {
ExtensionContext.get().port.onMessage.addListener((message: WorkerMessageWithSender) => {
if (message.sender === 'background' && message.type === WorkerMessageType.STORE_ACTION) {
const unprocessedAction = !isClientSynchronousAction(message.payload.action);
const acceptAction = acceptActionWithReceiver(message.payload.action, endpoint, tabId);
if (unprocessedAction && acceptAction) next(message.payload.action);
}
});
return (action: AnyAction) => {
/* if action should be processed immediately on the client
* reducers, forward it before broadcasting to the worker */
if (isClientSynchronousAction(action)) next(action);
/* hydrate the action with the current client's sender data */
const message = messageFactory({ type: WorkerMessageType.STORE_ACTION, payload: { action } });
message.payload.action = withSender({ endpoint: message.sender, tabId })(message.payload.action);
sendMessage(message).catch(noop);
};
};
};
| 4,456
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/utils/dev-reload.ts
|
/**
* Allows triggering custom callback function when the
* ProtonPassExtensionReloader webpack plugin sends a
* "reload" message.
*/
export const createDevReloader = (cb: () => void, description: string) => {
if (RUNTIME_RELOAD) {
const socket = new WebSocket(`ws://localhost:${RUNTIME_RELOAD_PORT}`);
socket.addEventListener('message', ({ data }: MessageEvent) => {
const message = JSON.parse(data);
if (message.reload) {
console.info(`[ProtonPassExtensionReloader] - ${description}`);
cb();
}
});
socket.addEventListener('error', () =>
console.info('[ProtonPassExtensionReloader] - Error while communicating with WS server')
);
}
};
| 4,457
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/utils/disable-browser-trap.ts
|
import { disableBrowserProxyTrap } from '@proton/pass/lib/globals/browser';
/* Since content-scripts cannot be inspected, it is safe to disable the
* browser API trap in this context. Additionally, content-scripts have
* access to a dedicated execution context with a proxy to the window object,
* so even if this flag is set, it won't be inspectable in the console where
* this script is running. See `@pass/globals/browser.ts` */
disableBrowserProxyTrap();
| 4,458
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/utils/form-entry.ts
|
import type { FormEntryPrompt, WithAutoSavePromptOptions } from '@proton/pass/types';
import { type FormEntry, FormEntryStatus } from '@proton/pass/types';
export const isFormEntryCommitted = (submission: FormEntry): submission is FormEntry<FormEntryStatus.COMMITTED> =>
submission.status === FormEntryStatus.COMMITTED;
export const isFormEntryPromptable = (
submission: WithAutoSavePromptOptions<FormEntry>
): submission is FormEntryPrompt => isFormEntryCommitted(submission) && submission.autosave.shouldPrompt;
export const isFormEntryCommittable = (submission: FormEntry): submission is FormEntry<FormEntryStatus.COMMITTED> =>
submission.partial === false && isFormEntryCommitted(submission);
| 4,459
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/utils/permissions.ts
|
import type { Permissions } from 'webextension-polyfill';
import browser from '@proton/pass/lib/globals/browser';
const manifest = browser.runtime.getManifest();
export const PASS_PERMISSIONS: Permissions.Permissions = {
permissions: [],
origins: manifest.host_permissions ?? [],
};
export const checkExtensionPermissions = async (): Promise<boolean> =>
browser.permissions.contains(PASS_PERMISSIONS).catch(() => false);
export const promptForPermissions = async (): Promise<boolean> =>
browser.permissions.request(PASS_PERMISSIONS).catch(() => false);
| 4,460
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/utils/popup-icon.ts
|
import browser from '@proton/pass/lib/globals/browser';
import noop from '@proton/utils/noop';
export const setPopupIcon = (options: { disabled: boolean; locked: boolean }): Promise<void> => {
let suffix = '';
if (options.disabled) suffix = '-disabled';
if (options.locked) suffix = '-locked';
return browser.action.setIcon({
path: {
16: `./assets/protonpass-icon-16${suffix}.png`,
32: `./assets/protonpass-icon-32${suffix}.png`,
},
});
};
/* this function should gracefully fail if the tabId
* does not exist or has been discarded when calling it*/
export const setPopupIconBadge = (tabId: number, count: number): Promise<void> =>
browser.action.setBadgeText({ tabId, text: count === 0 ? '' : String(count) }).catch(noop);
| 4,461
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/utils/port.ts
|
import type { ClientEndpoint, TabId } from '@proton/pass/types';
import { uniqueId } from '@proton/pass/utils/string/unique-id';
export const generatePortName = (endpoint: ClientEndpoint, tabId: TabId) => `${endpoint}-${tabId}-${uniqueId(16)}`;
const isEndpointPort = (endpoint: ClientEndpoint) => (tabId?: TabId) => (portName: string) =>
portName.startsWith(`${endpoint}-${tabId ?? ''}`);
export const isPopupPort = isEndpointPort('popup');
export const isContentScriptPort = isEndpointPort('contentscript');
| 4,462
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/utils/version.ts
|
export const getExtensionVersion = () => VERSION;
| 4,463
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/utils/vivaldi.ts
|
import browser from '@proton/pass/lib/globals/browser';
export const isVivaldiBrowser = async (): Promise<boolean> => {
try {
const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
return 'vivExtData' in tab;
} catch {
return false;
}
};
| 4,464
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/src/lib/utils/web-accessible-resource.ts
|
import browser from '@proton/pass/lib/globals/browser';
import noop from '@proton/utils/noop';
/* `web_accessible_resources` will always have a valid tabId when
* accessed at their direct URL. If it is served as the top window
* (and not injected in an iframe), prevent direct access by auto-
* closing the tab */
if (BUILD_TARGET === 'chrome' && ENV === 'production') {
if (window.self === window.top) {
void browser.tabs
.getCurrent()
.then<any>(({ id }) => id !== undefined && browser.tabs.remove(id))
.catch(noop);
}
}
| 4,465
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/tools/build-all.sh
|
#!/usr/bin/env bash
set -euo pipefail
REPODIR="$(git rev-parse --show-toplevel)"
PASSDIR="$REPODIR/applications/pass-extension"
VERSION="$(jq -r .version < "$PASSDIR/manifest-chrome.json")${BETA:+-beta}"
ARTEFACTSDIR="$REPODIR/build"
OUTDIR="$(mktemp -d)"
COMMIT="$(git rev-parse --short HEAD)"
BUILD_ID="ProtonPass-${VERSION}-${COMMIT}"
echo "Building for all platforms... This may take a while."
printf "\tNode\t%s (%s)\n" "$(node --version)" "$(which node)"
printf "\tnpm\tv%s (%s)\n" "$(npm --version)" "$(which npm)"
printf "\tYarn\tv%s (%s)\n" "$(yarn --version)" "$(which yarn)"
for var in "REPODIR" "PASSDIR" "VERSION" "OUTDIR" "COMMIT" "BUILD_ID"; do
printf "\t%s = %s\n" "${var}" "${!var}"
done
# Validate dependencies
echo "Validating yarn.lock..."
if [ -z ${CI+n} ]; then
cd "$REPODIR"
yarn install --immutable --immutable-cache > /dev/null
printf "\t✅ %s\n" "OK"
else
printf "\t⚠️ Skipped, \$CI var is already set\n"
fi
cd "$PASSDIR"
# Chrome production release
echo "Building Chrome (Prod)..."
BUILD_TARGET=chrome yarn run build > /dev/null
cd dist
zip -rqX "$OUTDIR/$BUILD_ID-chrome.zip" "."
cd ..
printf "\t✅ %s\n" "$OUTDIR/$BUILD_ID-chrome.zip"
# Chrome development (Black) release
echo "Building Chrome (Black)..."
BUILD_TARGET=chrome yarn run build:dev > /dev/null
mv "./dist" "$OUTDIR/black-$BUILD_ID-chrome"
printf "\t✅ %s\n" "$OUTDIR/black-$BUILD_ID-chrome"
# Firefox production release
echo "Building Firefox (Sources)..."
# Firefox sources
BUILD_TARGET=firefox NODE_ENV=production yarn run config
# Preserve config.ts because the `yarn` postinstall script will overwrite it
cp src/app/config.ts src/app/config.ff-release.ts
cd ../../
zip -rqX "$OUTDIR/$BUILD_ID-FF-sources.zip" \
"applications/pass-extension" \
"packages" \
"utilities" \
"yarn.lock" \
".yarn/patches" \
".yarn/releases" \
".yarnrc.yml" \
./*.js \
./*.json \
./*.mjs \
-x "*/.DS_Store" \
-x "*/node_modules/*" \
-x "packages/config/*" \
-x "applications/pass-extension/dist/*" \
-x "applications/pass-extension/*.md"
cd "$PASSDIR"
zip -uqX "$OUTDIR/$BUILD_ID-FF-sources.zip" "FIREFOX_REVIEWERS.md"
printf "\t✅ %s\n" "$OUTDIR/$BUILD_ID-FF-sources.zip"
# Firefox build
echo "Building Firefox (Prod)..."
yarn run build:ff > /dev/null
cd dist
zip -rqX "$OUTDIR/$BUILD_ID-FF.zip" "."
cd ..
printf "\t✅ %s\n" "$OUTDIR/$BUILD_ID-FF.zip"
# Verify FF reproducibility
echo "Verifying Firefox reproducibility..."
# Extract build
mkdir -p "$OUTDIR/$BUILD_ID-FF"
cd "$OUTDIR/$BUILD_ID-FF"
unzip -q "$OUTDIR/$BUILD_ID-FF.zip"
# Extract sources
mkdir -p "$OUTDIR/$BUILD_ID-FF-sources"
cd "$OUTDIR/$BUILD_ID-FF-sources"
unzip -q "$OUTDIR/$BUILD_ID-FF-sources.zip"
# Build and diff
yarn install --no-immutable > /dev/null
cd applications/pass-extension
yarn run build:ff > /dev/null
diff -qr dist "$OUTDIR/$BUILD_ID-FF"
cd "$PASSDIR"
rm -rf "$OUTDIR/$BUILD_ID-FF-sources"
rm -rf "$OUTDIR/$BUILD_ID-FF"
printf "\t✅ %s\n" "OK"
# Firefox development (Black) release
echo "Building Firefox (Black)..."
BUILD_TARGET=firefox yarn run build:dev > /dev/null
cp -r "./dist" "$OUTDIR/black-$BUILD_ID-FF"
printf "\t✅ %s\n" "$OUTDIR/black-$BUILD_ID-FF"
# Move tmp files into place
echo "Moving files into place..."
rm -rf "${ARTEFACTSDIR:-}"
mv "$OUTDIR" "$ARTEFACTSDIR"
printf "\t✅ %s\n" "$ARTEFACTSDIR"
| 4,466
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/tools/dev-server.js
|
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
process.env.ASSET_PATH = '/';
const WebpackDevServer = require('webpack-dev-server');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
const createReloadRuntimeServer = require('./reload-runtime');
const createReduxDevTools = require('./redux-tools');
const config = require('../webpack.config');
const {
WEBPACK_DEV_PORT,
REDUX_DEVTOOLS_PORT,
HOT_MANIFEST_UPDATE,
RUNTIME_RELOAD,
RUNTIME_RELOAD_PORT,
} = require('./env');
const EXCLUDED_WEBPACK_ENTRIES = [
'account',
'background',
'client',
'dropdown',
'elements',
'notification',
'orchestrator',
];
const sanitizeWebpackConfig = (config) => {
/**
* Only allow hot reloading capabilities for the pop-up
* app while maintaining a "stale watch mode" for other
* parts of the extension.
*/
Object.keys(config.entry).forEach((entryName) => {
if (!EXCLUDED_WEBPACK_ENTRIES.includes(entryName)) {
const entries = [config.entry[entryName]].flat();
if (typeof config.entry[entryName] === 'string') {
config.entry[entryName] = [
/* runtime code for hotmodule replacement */
'webpack/hot/dev-server',
/* dev-server client for web socket transport */
`webpack-dev-server/client?hot=true&hostname=localhost&port=${WEBPACK_DEV_PORT}&protocol=ws:`,
...entries,
];
}
}
});
/**
* TODO: verify everything works correctly when
* activating the getPlugins() helper from the parent
* webpack.config.js
*/
config.plugins = [new ReactRefreshWebpackPlugin({ overlay: false }), ...config.plugins];
return config;
};
const compiler = webpack(sanitizeWebpackConfig(config));
const server = new WebpackDevServer(
{
hot: true,
client: false,
liveReload: false,
host: 'localhost',
port: WEBPACK_DEV_PORT,
static: { directory: path.join(__dirname, '../dist') },
headers: { 'Access-Control-Allow-Origin': '*' },
allowedHosts: 'all',
devMiddleware: {
publicPath: `http://localhost:${WEBPACK_DEV_PORT}`,
writeToDisk: true,
},
},
compiler
);
const main = async () => {
await server.start();
await createReduxDevTools({ port: REDUX_DEVTOOLS_PORT });
let devVersion = 0;
if (RUNTIME_RELOAD) {
const { reload } = createReloadRuntimeServer({ port: RUNTIME_RELOAD_PORT });
compiler.hooks.afterEmit.tap('ProtonPassExtensionReloader', reload);
}
if (HOT_MANIFEST_UPDATE) {
compiler.hooks.compilation.tap('ProtonPassUpdateManifest', (compilation) => {
console.info(`[ProtonPassUpdateManifest] - Updating manifest version..`);
compilation.hooks.processAssets.tap(
{
name: 'ProtonPassUpdateManifest',
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
() => {
devVersion += 1;
const buffer = compilation.assets[`manifest.json`].source();
const source = buffer.toString('utf8');
const manifest = JSON.parse(source);
const version = `${manifest.version}.${devVersion}`;
manifest.version = version;
const newBuffer = Buffer.from(JSON.stringify(manifest), 'utf8');
compilation.updateAsset(`manifest.json`, new webpack.sources.RawSource(newBuffer));
console.info(`[ProtonPassUpdateManifest] - Updated manifest version to ${version}`);
}
);
});
}
};
main().catch((err) => {
console.warn(err);
process.exit(0);
});
| 4,467
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/tools/env.js
|
/**
* This utility will get rid of most
* false positives when parsing env
* variables.
*/
const parseEnvVar = (envVar, fallback, mapTo = (x) => x) => {
try {
return mapTo(JSON.parse(JSON.stringify(process.env[envVar])));
} catch (e) {
return fallback;
}
};
const parseBool = (x) => x === 'true' || x === '1' || x === 1;
const RUNTIME_RELOAD = parseEnvVar('RUNTIME_RELOAD', false, parseBool);
const BUILD_TARGET = parseEnvVar('BUILD_TARGET', 'chrome', String);
const CLEAN_MANIFEST = parseEnvVar('CLEAN_MANIFEST', false, parseBool);
const ENV = parseEnvVar('NODE_ENV', 'development', String);
const HOT_MANIFEST_UPDATE = RUNTIME_RELOAD && parseEnvVar('HOT_MANIFEST_UPDATE', false, parseBool);
const REDUX_DEVTOOLS_PORT = parseEnvVar('REDUX_DEVTOOLS_PORT', 8000, parseInt);
const RESUME_FALLBACK = parseEnvVar('RESUME_FALLBACK', false, parseBool);
const RUNTIME_RELOAD_PORT = parseEnvVar('RUNTIME_RELOAD_PORT', 8089, parseInt);
const WEBPACK_DEV_PORT = parseEnvVar('WEBPACK_DEV_PORT', 8090, Number);
module.exports = {
BUILD_TARGET,
CLEAN_MANIFEST,
ENV,
HOT_MANIFEST_UPDATE,
REDUX_DEVTOOLS_PORT,
RESUME_FALLBACK,
RUNTIME_RELOAD_PORT,
RUNTIME_RELOAD,
WEBPACK_DEV_PORT,
};
| 4,468
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/tools/redux-tools.js
|
const exec = require('child_process');
/* Use global @redux-devtools/cli to avoid adding it as
* a dependency to the monorepo : it includes way too many
* useless dependencies slowing down installation phase and
* breaks CI runners (electron sub dependency) */
const createReduxDevTools = async ({ port }) => {
const cmd = exec.spawn(`redux-devtools`, ['--hostname=localhost', `--port=${port}`]);
cmd.stdout.on('data', (buff) => console.info(buff.toString()));
cmd.stderr.on('data', (buff) => console.error(buff.toString()));
cmd.on('error', (buff) => {
console.error(buff.toString());
console.warn('Run `yarn workspace @proton/pass install:additional-tools`');
process.exit(0);
});
return cmd;
};
module.exports = createReduxDevTools;
| 4,469
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/tools/reload-runtime.js
|
const http = require('http');
const ws = require('ws');
const noop = () => {};
/**
* this allows triggering runtime
* reloads when webpack's HMR server emits new data
*/
const createReloadRuntimeServer = ({ port }) => {
const httpServer = http.createServer({});
console.info('[ProtonPassExtensionReloader] - Setting runtime reloader server');
const server = new ws.Server({ server: httpServer, pingTimeout: 10000 });
server.on('pong', noop);
const reloadClients = () => {
console.info('[ProtonPassExtensionReloader] - Reloading clients..');
server.clients.forEach((client) => {
client.send(JSON.stringify({ reload: true }));
});
};
process.on('beforeExit', () => server.close());
httpServer.listen(port);
return { reload: reloadClients };
};
module.exports = createReloadRuntimeServer;
| 4,470
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension
|
petrpan-code/ProtonMail/WebClients/applications/pass-extension/tools/slack-notify.sh
|
# Warn that the script requires being merged into the main branch
# to work effectively since tags may become invalid if we keep
# rebasing on `main`
echo "This script may not work effectively until we are merged on the main branch."
echo "If we keep on rebasing on the main branch, our tags become invalid when trying to compute commit diffs."
# Determine the current state based on whether we are triggered
# from a tag, commit, or manually for testing purposes. If there
# is no CI_COMMIT_TAG, then use the latest commit in the pipeline.
CURRENT_STATE=${CI_COMMIT_TAG:-${CI_COMMIT_SHORT_SHA:-$(git rev-parse --short HEAD)}}
echo "[before] $CI_COMMIT_BEFORE_SHA"
# Determine the previous state based on whether the current state
# matches the latest merge commit or a commit tag in the current pipeline.
# If no commit tag is found, then we are dealing with a push commit,
# so select the `before` commit as the previous state.
if [[ ! -z "$CI_COMMIT_BEFORE_SHA" && "$CI_COMMIT_BEFORE_SHA" != "0000000000000000000000000000000000000000" ]]; then
PREVIOUS_STATE=$CI_COMMIT_BEFORE_SHA
echo "[previous commit] $PREVIOUS_STATE"
elif [[ ! -z "$CI_COMMIT_TAG" ]]; then
PREVIOUS_STATE=$(git tag -l "proton-pass-extension@*" --sort=-committerdate | sed -n '2p')
echo "[previous tag] $PREVIOUS_STATE"
else
PREVIOUS_STATE=$CURRENT_STATE
echo "[current commit] $PREVIOUS_STATE"
fi
# Display the states for which we will compute the diff
echo "Resolving diff from :"
echo "[ start ] $PREVIOUS_STATE"
echo " | ..."
echo " ˅"
echo "[ end ] $CURRENT_STATE"
# Compute the JIRA ticket IDs from the commit log between the
# current and previous states. Include the previous commit only
# if it matches the current commit.
if [[ "$PREVIOUS_STATE" && "$CURRENT_STATE" ]]; then
JIRA_TICKET_IDS=$(git log $PREVIOUS_STATE^..$CURRENT_STATE | grep -o "IDTEAM-[0-9]*")
else
JIRA_TICKET_IDS=$(git log $PREVIOUS_STATE..$CURRENT_STATE | grep -o "IDTEAM-[0-9]*")
fi
# Create a Slack message body containing JIRA ticket links
# for each unique ticket ID in the commit log
JIRA_KEYS=()
JIRA_SECTION=""
for ticket in $JIRA_TICKET_IDS; do
link="https://jira.protontech.ch/browse/$ticket"
key_exists=0
for key in "${JIRA_KEYS[@]}"; do
if [[ $key == $ticket ]]; then
key_exists=1
break
fi
done
if [[ $key_exists -eq 0 ]]; then
JIRA_KEYS+=($ticket)
JIRA_SECTION+=", {
\"type\": \"section\",
\"text\": {
\"type\": \"mrkdwn\",
\"text\": \":jira: $ticket <$link|[link]>\"
}
}"
fi
done
SLACK_POST_BODY=$(echo "{
\"channel\": \"$PASS_EXTENSION_BUILD_SLACK_CHANNEL_ID\",
\"blocks\": [
{
\"type\": \"header\",
\"text\": {
\"type\": \"plain_text\",
\"emoji\": true,
\"text\": \":protonpass: build $CURRENT_STATE\"
}
},
{
\"type\": \"section\",
\"text\": {
\"type\":\"mrkdwn\",
\"text\":\"Download all *_build artefacts_* <https://gitlab.protontech.ch/web/clients/-/jobs/$CI_JOB_ID/artifacts/download|here> (expires in 1 week)\"
}
}
$JIRA_SECTION
]
}" | jq -r '.')
curl \
-X POST https://slack.com/api/chat.postMessage \
-H "Content-type: application/json; charset=utf-8" \
-H "Authorization: Bearer ${SIMPLE_LOGIN_SLACK_BOT_TOKEN}" \
--data-raw "$SLACK_POST_BODY"
| 4,471
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui/.eslintrc.js
|
module.exports = {
extends: ['@proton/eslint-config-proton'],
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: __dirname,
project: './tsconfig.json',
},
ignorePatterns: ['.eslintrc.js'],
};
| 4,472
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui/index.html
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + TS</title>
</head>
<body>
<div style="height: 50px" class="app-bar">
<div>Recovery kit template editor</div>
<button onclick="saveTemplate()">Copy template</button>
</div>
<div id="container" style="height: calc(100vh - 50px)"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
| 4,473
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui/package.json
|
{
"name": "pdf-ui",
"version": "0.0.0",
"private": true,
"scripts": {
"build": "tsc && vite build",
"check-types": "tsc",
"lint": "eslint src --ext .js,.ts,.tsx --quiet --cache",
"preview": "vite preview",
"start": "vite"
},
"dependencies": {
"@pdfme/common": "^3.0.1",
"@pdfme/schemas": "^3.0.1",
"@pdfme/ui": "^3.0.1",
"eslint": "^8.54.0",
"toastify-js": "^1.12.0"
},
"devDependencies": {
"@types/toastify-js": "^1.12.3",
"typescript": "^5.3.2",
"vite": "^5.0.1"
}
}
| 4,474
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui/tsconfig.json
|
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "node",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"allowSyntheticDefaultImports": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
| 4,475
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui/src/main.ts
|
import { Designer } from '@pdfme/ui';
import Toastify from 'toastify-js';
import { getFont } from '@proton/recovery-kit';
import { getFilledTemplate } from '@proton/recovery-kit/filledTemplate';
import textToClipboard from './textToClipboard';
import './style.css';
import 'toastify-js/src/toastify.css';
async function main() {
const domContainer = document.getElementById('container');
if (!domContainer) {
throw new Error('Container element not found');
}
const designer = new Designer({
domContainer,
template: getFilledTemplate(),
options: { font: await getFont() },
});
designer.onSaveTemplate((template) => {
// @ts-ignore
delete template.basePdf;
const stringifiedTemplate = JSON.stringify(template, null, 4);
textToClipboard(stringifiedTemplate);
Toastify({
text: 'Template copied to clipboard',
duration: 3000,
gravity: 'bottom',
position: 'center',
stopOnFocus: true,
style: {
marginBottom: '24px',
padding: '8px 12px',
borderRadius: '12px',
background: 'black',
},
}).showToast();
});
function saveTemplate() {
designer.saveTemplate();
}
// @ts-ignore
window.saveTemplate = saveTemplate;
}
void main();
| 4,476
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui/src/style.css
|
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
}
button {
display: inline-block;
padding: 8px 16px;
border: 1px solid var(--button-default-border-color, transparent);
border-radius: 8px;
outline: none;
background-color: #6d4aff;
color: white;
text-align: center;
cursor: pointer;
transition: 0.15s cubic-bezier(0.22, 1, 0.36, 1), background-position 0s;
}
button:hover {
background-color: #6243e6;
}
button:active {
background-color: #573bcc;
}
.app-bar {
background-color: #1b1340;
color: white;
padding: 0px 12px;
display: flex;
align-items: center;
justify-content: space-between;
}
| 4,477
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui/src/textToClipboard.ts
|
export default function textToClipboard(text = '', target = document.body) {
const oldActiveElement = document.activeElement as HTMLElement;
if (navigator.clipboard) {
void navigator.clipboard.writeText(text);
} else {
const dummy = document.createElement('textarea');
target.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand('copy');
target.removeChild(dummy);
}
oldActiveElement?.focus?.();
}
| 4,478
|
0
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui
|
petrpan-code/ProtonMail/WebClients/applications/pdf-ui/src/vite-env.d.ts
|
/// <reference types="vite/client" />
| 4,479
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/.eslintrc.js
|
module.exports = {
extends: ['@proton/eslint-config-proton'],
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: __dirname,
project: './tsconfig.json',
},
ignorePatterns: ['.eslintrc.js'],
};
| 4,480
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/LICENSE
|
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
| 4,481
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/README.md
|
# preview-sandbox
This project encapsulates the previewer found in the Drive app, based on a [sandboxed iframe](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox).
## How it works
This project builds into a single-page HTML file. This file is loaded by the client through a blob URL, to ensure a separate origin. It communicates with `postMessage` to receive the data.
## Building
`yarn build` will build the project, and copy it to the apps that use it.
You can refer to [`bin/build.js`](./bin/build.js) to see what exactly is happening.
Make sure to copy the built file every time you change something here, until we can find a better way to handle the build.
We may also deploy to a dedicated subdomain in the future, depending on future constraints.
## `postMessage` interface
### Client to sandbox
```javascript
const message = {
type: 'data',
mimeType: 'application/x-mimetype',
data: UInt8Array,
};
```
### Sandbox to client
```javascript
const message = {
type: 'error',
error: Error,
};
```
| 4,482
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/package.json
|
{
"name": "proton-preview-sandbox",
"description": "Standalone isolated previewer for documents that runs in an iframe",
"license": "GPL-3.0",
"author": "Proton AG",
"main": "index.ts",
"scripts": {
"build": "cross-env NODE_ENV=production ./bin/build.js",
"check-types": "tsc",
"lint": "eslint src --ext .ts --cache",
"pretty": "prettier --write $(find src -type f -name '*.ts')",
"test": "echo No tests yet"
},
"dependencies": {
"docx-preview": "^0.1.20"
},
"devDependencies": {
"@proton/eslint-config-proton": "workspace:packages/eslint-config-proton",
"browserslist-to-esbuild": "^1.2.0",
"cross-env": "^7.0.3",
"esbuild": "^0.19.7",
"eslint": "^8.54.0",
"prettier": "^3.1.0",
"typescript": "^5.3.2"
}
}
| 4,483
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/tsconfig.json
|
{
"extends": "../../tsconfig.base.json"
}
| 4,484
|
0
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/bin/build.js
|
#!/usr/bin/env node
/* eslint-disable no-console */
const path = require('path');
const fs = require('fs');
const esbuild = require('esbuild');
const browserslistToEsbuild = require('browserslist-to-esbuild');
const isProd = process.env.NODE_ENV === 'production';
const distDir = path.join(__dirname, '../dist');
const srcDir = path.join(__dirname, '../src');
const fileName = 'sandbox.js';
const outFile = path.join(distDir, fileName);
// Step 1 - generate JS bundle
esbuild.buildSync({
bundle: true,
platform: 'browser',
target: browserslistToEsbuild('> 0.5%, not IE 11, Firefox ESR, Safari 11'),
entryPoints: [path.join(srcDir, 'index.ts')],
outfile: outFile,
sourcemap: false,
minify: isProd,
});
console.log(`✅ Built - ./dist/${fileName}`);
// Step 2 - copy to apps
const apps = ['drive', 'mail'];
const publicPath = 'public/assets';
apps.forEach((app) => {
fs.copyFileSync(outFile, path.join(__dirname, `../../${app}`, publicPath, fileName));
console.log(`✅ Copied - applications/${app}/${publicPath}`);
});
| 4,485
|
0
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/src/index.ts
|
import { handleMessage, postError } from './message';
window.addEventListener('load', () => {
window.addEventListener('message', (event) => {
// Our iframe can receive messages from multiple places,
// so we ensure we are getting messages from the correct origin
if (event.origin !== window.location.origin) {
// We don't log here as it can be spammy
return;
}
let message = event.data;
if (typeof message !== 'object' || !message.type) {
postError(new Error('Unexpected message format'));
return;
}
handleMessage(message);
});
});
| 4,486
|
0
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/src/message.ts
|
import { SafeErrorObject, getSafeErrorObject } from '@proton/utils/getSafeErrorObject';
import supportedPreviews from './previews';
export type OutgoingMessage = OutgoingErrorMessage;
export const postMessage = (message: OutgoingMessage) => {
window.parent.postMessage(message, window.location.origin);
};
type OutgoingErrorMessage = {
type: 'error';
error: SafeErrorObject;
};
export const postError = (error: Error) => {
// In case the client stops receiving messages for whatever reason,
// we trace it here so we can know it happened
// eslint-disable-next-line no-console
console.error(error);
postMessage({
type: 'error',
error: getSafeErrorObject(error),
});
};
type IncomingDataMessage = {
type: 'data';
mimeType: string;
data: Uint8Array;
};
const handleData = async (message: IncomingDataMessage) => {
const preview = supportedPreviews[message.mimeType];
try {
if (preview) {
await preview(message.data);
} else {
throw new Error(`Unsupported sandboxed preview mimetype: ${message.mimeType}`);
}
} catch (e) {
postError(e as Error);
}
};
export type IncomingMessage = IncomingDataMessage;
export const handleMessage = (message: IncomingMessage) => {
if (message.type === 'data') {
void handleData(message);
} else {
postError(new Error('Unexpected message type', { cause: { type: message.type } }));
}
};
| 4,487
|
0
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/src
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/src/previews/index.ts
|
import { SupportedMimeTypes } from '@proton/shared/lib/drive/constants';
import wordPreview from './word';
export const supportedPreviews: { [mimeType: string]: (content: Uint8Array) => Promise<void> } = {
[SupportedMimeTypes.docx]: wordPreview,
};
export default supportedPreviews;
| 4,488
|
0
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/src
|
petrpan-code/ProtonMail/WebClients/applications/preview-sandbox/src/previews/word.ts
|
import { renderAsync } from 'docx-preview';
export const wordPreview = async (content: Uint8Array) => {
const element = document.createElement('div');
await renderAsync(content, element, element, {
className: `docx`,
breakPages: true,
});
document.body.appendChild(element);
};
export default wordPreview;
| 4,489
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/storybook/.eslintrc.js
|
module.exports = {
extends: ['@proton/eslint-config-proton', 'plugin:storybook/recommended'],
parser: '@typescript-eslint/parser',
env: {
jasmine: true,
},
parserOptions: {
tsconfigRootDir: __dirname,
project: './tsconfig.json',
},
rules: {},
ignorePatterns: ['.eslintrc.js'],
};
| 4,490
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/storybook/.prettierignore
|
*.json
*.md
| 4,491
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/storybook/CHANGELOG.md
|
# Changelog
## 0.0.14 (29 March, 2021)
Added new icons (`pause`/`resume`/`stop`)
## 0.0.13 (5 March, 2021)
Added Card component, a lightweight wrapper component with a bit of styling adhering to a "card / well" concept
## 0.0.12 (5 March, 2021)
Added new icons Rebumped - for proper styling for new toggle
## 0.0.11 (1 March, 2021)
Commented/added new toggle design (icon case). Added new icons
## 0.0.10 (23 February, 2021)
Added [new Button API](/docs/components-button)
Opt into new Button API possible by using any of the three new props `shape`, `color` or `size`.
## 0.0.9 (17 February, 2021)
Added missing documentation for `position: sticky` helpers.
## 0.0.8 (15 February, 2021)
Added "variant" property to meter (default, thin). Enhanced documentation for [Meter](/docs/components-meter) with props table & additional examples for different meter variants.
## 0.0.7 (3 February, 2021)
Added [Dropzone](/story/components-dropdown--basic), a component for drag and drop uploading.
## 0.0.6 (29 January, 2021)
- Make changelog url generated by the slack bot point to the actual changelog which is now available inside the documentation
- Change ordering of stories logic so that the introduction page will be the first thing to show up when accessing the base url of the documentation
- Render CHANGELOG markdown file at the root of the project inside an mdx docs page
## 0.0.5 (28 January, 2021)
Add missing favicon!
## 0.0.4 (28 January, 2021)
Completed `README` and `MiddleEllipsis` doc
## 0.0.3 (28 January, 2021)
Not really a design system documentation changelog entry but still :)
Moved the documentation to the url https://design-system.protontech.ch/
Updated the changelog scripts to reflect the new url in the embedded url and made the message a little prettier
Updated the ci script to contain better human-readable output
Added dates to the changelog entries
## 0.0.2 (27 January, 2021)
Added `MiddleEllipsis` component
## 0.0.1 (27 January, 2021)
A new beginning
| 4,492
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/storybook/CONTRIBUTING.md
|
# Contributing
- [React component stories](#react-component-stories)
- [React component props](#react-component-props)
- [Storybook Canvas block](#storybook-canvas-block)
## React component stories
The main way we intend to convey documentation about React Components in this Storybook is via Storybook's [MDX Docs Suppport](https://storybook.js.org/docs/react/writing-docs/mdx).
For that we employ the pattern of writing a couple of stories in a `Component.stories.tsx` file and linking them to an mdx documentation page through the `<Story />` Storybook Block by referencing the story's id like so:
```jsx
import { Canvas, Story } from '@storybook/addon-docs/blocks';
<Story id="story-id" />;
```
The name you call your mdx file does not matter as it has to be linked manually to the respective component stories file like so (however `Component.mdx` seems like a convenient pattern for mdx pages that are directly linked to a stories file of the same component):
```jsx
import mdx from './Component.mdx';
import Component from './Component.tsx';
export default {
component: Component,
title: 'Component',
parameters: {
docs: {
page: mdx,
},
},
};
```
The easiest way to find a story-id is by going to a running storybook instance and checking the url when on a story in the canvas:
<img src="./src/assets/storybook-story-id.png" width="400" alt="" />
However the story-id is computed from your story's title and its name, soit is also possible to predict it.
This pattern is documented in the following storybook 'recipe': [CSF Stories with arbitrary MDX](https://github.com/storybookjs/storybook/blob/next/addons/docs/docs/recipes.md#csf-stories-with-arbitrary-mdx)
## React component props
To show the arguments (props) for a certain component in the documentation page use the ArgsTable Storybook Block
```jsx
import { Alert } from 'react-components';
import { ArgsTable } from '@storybook/addon-docs/blocks';
<ArgsTable of={Alert} />;
```
<img src="./src/assets/storybook-argstable.png" alt="" />
Note: If you comment your props this way in your component in `react-components`:
```
interface Props extends React.HTMLProps<HTMLSpanElement> {
text: string;
/**
* Here is a super useful comment.
*/
charsToDisplayEnd?: number;
```
This comment will be present in StoryBook:
<img src="./src/assets/storybook-props-comments.png" alt="Comment available" />
There have been issues with typescript-docgen not being able to correctly extract the args/props for the ArgsTable. The following scenarios cause problems with that.
Importing a component under a different name than it was exported as
```js
/* bar.js */
import Baz from './foo';
/* foo.js */
export default Foo;
```
Exporting the component as an anonymous value, for example when wrapped in higher order functions and directly exported.
```js
const A = () => {
/* ... */
};
export default forwardRef(A);
```
One option to deal with this is to wrap the component definition itself so that the wrapped component is named by a variable.
```js
const A = forwardRef(() => {
/* ... */
});
export default A;
```
## Storybook Canvas block
Usually you'll see a `<Story />` wrapped inside the `<Canvas />` Storybook Block. This is done to show the source code alongside the inline story:
```jsx
import { Canvas, Story } from '@storybook/addon-docs/blocks';
<Canvas>
<Story id="story-id" />
</Canvas>;
```
<img src="./src/assets/storybook-canvas-block.png" alt="" />
| 4,493
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/storybook/LICENSE
|
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
| 4,494
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/storybook/README.md
|
# Proton Design System Storybook 🤘
This project is a storybook instance documenting Proton's design system in the scope of Web. It serves as both an isolated development environment for React Components as well as a source of centralized documentation all things design philosophy & technical documentation.
## Installation & Running
Run docs-only in development mode
```shell
yarn workspace proton-storybook storybook
yarn storybook
```
The start script defaults to running in docs-only mode (`--docs` flag), however another script called "storybook-raw" has been left (original start script) to run storybook in the original configuration. The storybook docs mention storybook being unable to keep a proper cache in docs-only mode, so the raw command can be used if you're experiencing performance issues while developing locally or just if you'd like to run storybook with a canvas view / for viewing canvas specific addons.
```shell
yarn workspace proton-storybook storybook-raw
yarn storybook-raw
```
| 4,495
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/storybook/index.d.ts
|
declare module '*.mdx' {
const mdx: any;
export default mdx;
}
declare module '*.png' {
const img: string;
export default img;
}
| 4,496
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/storybook/package.json
|
{
"name": "proton-storybook",
"description": "",
"keywords": [],
"license": "GPL-3.0",
"author": "",
"main": "index.js",
"scripts": {
"build": "build-storybook --docs",
"check-types": "tsc",
"deploy": "netlify deploy --auth $NETLIFY_AUTH_TOKEN --site $NETLIFY_SITE_ID --dir storybook-static --alias $NETLIFY_ALIAS",
"deploy:prod": "netlify deploy --auth $NETLIFY_AUTH_TOKEN --site $NETLIFY_SITE_ID --prod --dir storybook-static",
"postinstall": "proton-pack config",
"lint": "eslint src --ext .js,.ts,.tsx --quiet --cache",
"pretty": "prettier --write $(find . -path ./node_modules -prune -o -path ./src -type f -name '*.js' -o -name '*.ts' -o -name '*.tsx')",
"start": "proton-pack config && start-storybook -p 6006",
"storybook": "start-storybook -p 6006 --docs --no-manager-cache",
"storybook-raw": "start-storybook -p 6006"
},
"dependencies": {
"@proton/components": "workspace:packages/components",
"@proton/eslint-config-proton": "workspace:packages/eslint-config-proton",
"@proton/pack": "workspace:packages/pack",
"@proton/shared": "workspace:packages/shared",
"@proton/styles": "workspace:packages/styles",
"@types/react": "^17.0.71",
"@types/react-dom": "^17.0.24",
"@types/react-router-dom": "^5.3.3",
"cross-env": "^7.0.3",
"eslint": "^8.54.0",
"lodash.startcase": "^4.4.0",
"prettier": "^3.1.0",
"prop-types": "15.8.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.3.4",
"ts-loader": "^9.5.1",
"typescript": "^5.3.2",
"webpack": "^5.89.0"
},
"devDependencies": {
"@babel/core": "^7.23.3",
"@storybook/addon-actions": "^6.5.16",
"@storybook/addon-essentials": "^6.5.16",
"@storybook/addon-links": "^6.5.16",
"@storybook/addon-storysource": "^6.5.16",
"@storybook/builder-webpack5": "^6.5.16",
"@storybook/manager-webpack5": "^6.5.16",
"@storybook/react": "^6.5.16",
"@storybook/source-loader": "^6.5.16",
"babel-loader": "^9.1.3",
"eslint-plugin-storybook": "^0.6.15",
"netlify-cli": "^17.5.3"
}
}
| 4,497
|
0
|
petrpan-code/ProtonMail/WebClients/applications
|
petrpan-code/ProtonMail/WebClients/applications/storybook/tsconfig.json
|
{
"extends": "../../tsconfig.base.json"
}
| 4,498
|
0
|
petrpan-code/ProtonMail/WebClients/applications/storybook
|
petrpan-code/ProtonMail/WebClients/applications/storybook/.storybook/main.js
|
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { getJsLoader } = require('@proton/pack/webpack/js.loader');
const getCssLoaders = require('@proton/pack/webpack/css.loader');
const getAssetsLoaders = require('@proton/pack/webpack/assets.loader');
module.exports = {
core: {
builder: 'webpack5',
},
stories: [
'../src/stories/**/*.stories.@(mdx|js|jsx|ts|tsx)',
'../../../packages/atoms/**/*.stories.@(js|jsx|ts|tsx)',
],
addons: ['@storybook/addon-links', '@storybook/addon-storysource', '@storybook/addon-essentials'],
staticDirs: ['../src/assets', '../src/assets/favicons'],
typescript: {
check: false,
checkOptions: {},
reactDocgen: 'react-docgen-typescript',
reactDocgenTypescriptOptions: {
shouldRemoveUndefinedFromOptional: true,
propFilter: (property) => {
if (property.parent) {
/**
* Only generate docs for properties which are not a part of the @types
* package. That way we don't get all the inherited dom attributes for
* example from "React.FC<React.HTMLAttributes<HTMLDivElement>>".
*
* Usually examples covered in Storybook docs as well as react-docgen-typescript
* itself show a different code-snippet to deal with this, one which ignores
* solely based on "node_modules".
*
* Since we're defining the components used in our storybook outside this codebase
* and importing it through node_modules, that won't do for us, we need to be
* more specific.
*/
return !property.parent.fileName.includes('/node_modules/@types/');
}
return true;
},
},
},
webpackFinal: async (config, { configType }) => {
const isProduction = configType === 'PRODUCTION';
const options = {
isProduction,
hasReactRefresh: false,
};
return {
...config,
resolve: {
...config.resolve,
fallback: {
...config.resolve.fallback,
// For some reason storybook brings in openpgp as a dependency and we need to
// explicitly disable these in the webpack config
stream: false,
crypto: false,
},
},
module: {
...config.module,
rules: [
...config.module.rules.filter((rule) => {
return rule.test.toString().includes('mdx');
}),
{
test: /\.stories\.(tsx|mdx)?$/,
use: [
{
loader: require.resolve('@storybook/source-loader'),
options: { parser: 'typescript' },
},
],
enforce: 'pre',
},
...[getJsLoader(options), ...getCssLoaders(options), ...getAssetsLoaders(options)],
],
},
plugins: [
...config.plugins,
new MiniCssExtractPlugin({
filename: isProduction ? '[name].[contenthash:8].css' : '[name].css',
chunkFilename: isProduction ? '[id].[contenthash:8].css' : '[id].css',
}),
],
node: {
...config.node,
__dirname: true,
__filename: true,
},
};
},
};
| 4,499
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.