index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
|---|---|---|---|---|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/auth/session-lock-enable.saga.ts
|
import { put, select, takeLeading } from 'redux-saga/effects';
import { deleteSessionLock } from '@proton/pass/lib/auth/session-lock';
import {
sessionLockEnableFailure,
sessionLockEnableIntent,
sessionLockEnableSuccess,
} from '@proton/pass/store/actions';
import type { WithSenderAction } from '@proton/pass/store/actions/with-receiver';
import { selectHasRegisteredLock } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
function* enableSessionLockWorker(
{ getAuthService }: WorkerRootSagaOptions,
{ meta, payload: { pin, ttl } }: WithSenderAction<ReturnType<typeof sessionLockEnableIntent>>
) {
try {
/* if we're creating a new lock over an existing one delete the
* previous one. This will happen during a lock TTL update. */
if ((yield select(selectHasRegisteredLock)) as boolean) yield deleteSessionLock(pin);
const sessionLockToken: string = yield getAuthService().createLock(pin, ttl);
yield put(sessionLockEnableSuccess(meta.request.id, { sessionLockToken, ttl }, meta.sender?.endpoint));
} catch (error) {
yield put(sessionLockEnableFailure(meta.request.id, error, meta.sender?.endpoint));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLeading(sessionLockEnableIntent.match, enableSessionLockWorker, options);
}
| 8,000
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/auth/session-lock-immediate.saga.ts
|
import { fork, put, takeLeading } from 'redux-saga/effects';
import { cacheRequest, sessionLockIntent } from '@proton/pass/store/actions';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import noop from '@proton/utils/noop';
/* If we the user has not registered a lock yet (ie: has
* a sessionLockToken saved) then this saga should have
* no effect */
function* lockSessionImmediateWorker({ getAuthService, getAuthStore: getAuth }: WorkerRootSagaOptions) {
if (getAuth().getLockToken() !== undefined) {
yield put(cacheRequest());
yield fork(function* () {
/* fork for non-blocking action -> immediate UI effect */
yield getAuthService().lock({ soft: false }).catch(noop);
});
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLeading(sessionLockIntent.match, lockSessionImmediateWorker, options);
}
| 8,001
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/auth/session-unlock.saga.ts
|
import { put, takeLeading } from 'redux-saga/effects';
import { c } from 'ttag';
import { sessionUnlockFailure, sessionUnlockIntent, sessionUnlockSuccess } from '@proton/pass/store/actions';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
function* unlockSessionWorker(
{ getAuthService }: WorkerRootSagaOptions,
{ payload, meta: { callback: onUnlockResult, request } }: ReturnType<typeof sessionUnlockIntent>
) {
try {
const sessionLockToken: string = yield getAuthService().unlock(payload.pin);
const successMessage = sessionUnlockSuccess(request.id, { sessionLockToken });
yield put(successMessage);
onUnlockResult?.(successMessage);
} catch (err: any) {
const inactiveSession = err.name === 'InactiveSession';
const failureMessage = sessionUnlockFailure(request.id, err, {
canRetry: !inactiveSession,
error: inactiveSession
? c('Error').t`Too many failed attempts. Please sign in again.`
: c('Error').t`Wrong PIN code. Try again.`,
});
yield put(failureMessage);
onUnlockResult?.(failureMessage);
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLeading(sessionUnlockIntent.match, unlockSessionWorker, options);
}
| 8,002
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/auth/signout.saga.ts
|
import { put, takeLeading } from 'redux-saga/effects';
import { signoutIntent, signoutSuccess } from '@proton/pass/store/actions';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
function* signoutIntentWorker({ getAuthService }: WorkerRootSagaOptions, action: ReturnType<typeof signoutIntent>) {
yield getAuthService().logout({ soft: action.payload.soft });
yield put(signoutSuccess(action.payload));
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLeading(signoutIntent.match, signoutIntentWorker, options);
}
| 8,003
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/boot.saga.ts
|
import { put, takeLeading } from 'redux-saga/effects';
import { isPassCryptoError } from '@proton/pass/lib/crypto/utils/errors';
import { bootFailure, bootIntent, bootSuccess, stopEventPolling, syncLocalSettings } from '@proton/pass/store/actions';
import { SyncType, synchronize } from '@proton/pass/store/sagas/client/sync';
import type { State, WorkerRootSagaOptions } from '@proton/pass/store/types';
import { logger } from '@proton/pass/utils/logger';
import { merge } from '@proton/pass/utils/object/merge';
import { hydrateFromCache } from './hydrate.saga';
function* bootWorker(options: WorkerRootSagaOptions) {
try {
yield put(stopEventPolling());
/* merge the existing cache to preserve any state that may have been
* mutated before the boot sequence (session lock data) */
const mergeCache = (existing: State, incoming: State) => merge(existing, incoming, { excludeEmpty: true });
const hydratedFromCache: boolean = yield hydrateFromCache(mergeCache, options);
/* Force sync the proxied settings from local storage */
if (options.endpoint !== 'web') yield put(syncLocalSettings(yield options.getLocalSettings()));
/* Allow failure during sync if we have a cached state,
* worst case scenario: sync will happen on next event-loop */
yield put(bootSuccess(yield synchronize({ type: SyncType.PARTIAL, allowFailure: hydratedFromCache }, options)));
options.onBoot?.({ ok: true });
} catch (error: unknown) {
logger.warn('[Saga::Boot]', error);
yield put(bootFailure(error));
options.onBoot?.({ ok: false, clearCache: isPassCryptoError(error) });
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLeading(bootIntent.match, bootWorker, options);
}
| 8,004
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/cache.saga.ts
|
import type { AnyAction } from 'redux';
import type { Task } from 'redux-saga';
import { cancel, fork, select, take, takeLatest } from 'redux-saga/effects';
import { PassCrypto } from '@proton/pass/lib/crypto/pass-crypto';
import { CACHE_SALT_LENGTH, getCacheEncryptionKey } from '@proton/pass/lib/crypto/utils/cache.encrypt';
import { encryptData } from '@proton/pass/lib/crypto/utils/crypto-helpers';
import { cacheCancel } from '@proton/pass/store/actions';
import { type WithCache, isCachingAction } from '@proton/pass/store/actions/with-cache';
import { asIfNotOptimistic } from '@proton/pass/store/optimistic/selectors/select-is-optimistic';
import { reducerMap } from '@proton/pass/store/reducers';
import type { State, WorkerRootSagaOptions } from '@proton/pass/store/types';
import { AppStatus, PassEncryptionTag } from '@proton/pass/types';
import { oneOf } from '@proton/pass/utils/fp/predicates';
import { logger } from '@proton/pass/utils/logger';
import { objectFilter } from '@proton/pass/utils/object/filter';
import { stringToUint8Array, uint8ArrayToString } from '@proton/shared/lib/helpers/encoding';
function* cacheWorker({ type }: WithCache<AnyAction>, { getAppState, getAuthStore, setCache }: WorkerRootSagaOptions) {
const loggedIn = getAuthStore().hasSession();
const booted = oneOf(AppStatus.READY, AppStatus.BOOTING)(getAppState().status);
if (loggedIn && booted) {
try {
const sessionLockToken = getAuthStore().getLockToken();
const cacheSalt = crypto.getRandomValues(new Uint8Array(CACHE_SALT_LENGTH));
const key: CryptoKey = yield getCacheEncryptionKey(cacheSalt, sessionLockToken);
const state = (yield select()) as State;
const whiteListedState = asIfNotOptimistic(state, reducerMap);
/* keep non-expired request metadata */
whiteListedState.request = objectFilter(
whiteListedState.request,
(_, request) => request.status === 'success' && request.expiresAt !== undefined
);
const encoder = new TextEncoder();
const stringifiedState = JSON.stringify(whiteListedState);
const encryptedData: Uint8Array = yield encryptData(
key,
encoder.encode(stringifiedState),
PassEncryptionTag.Cache
);
const workerSnapshot = PassCrypto.serialize();
const stringifiedSnapshot = JSON.stringify(workerSnapshot);
const encryptedWorkerSnapshot: Uint8Array = yield encryptData(
key,
stringToUint8Array(stringifiedSnapshot),
PassEncryptionTag.Cache
);
logger.info(`[Saga::Cache] Caching store and crypto state @ action["${type}"]`);
yield setCache({
salt: uint8ArrayToString(cacheSalt),
state: uint8ArrayToString(encryptedData),
snapshot: uint8ArrayToString(encryptedWorkerSnapshot),
});
} catch {}
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLatest(isCachingAction, function* (action) {
const cacheTask: Task = yield fork(cacheWorker, action, options);
yield take(cacheCancel.match);
yield cancel(cacheTask);
logger.info(`[Saga::Cache] Invalidated all caching tasks`);
});
}
| 8,005
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/hydrate.saga.ts
|
import { put, select, takeLeading } from 'redux-saga/effects';
import { PassCrypto } from '@proton/pass/lib/crypto/pass-crypto';
import { decryptCachedState } from '@proton/pass/lib/crypto/utils/cache.decrypt';
import { getUserState } from '@proton/pass/lib/user/user.requests';
import {
getUserAccessSuccess,
getUserFeaturesSuccess,
startEventPolling,
stateHydrate,
stateSync,
stopEventPolling,
} from '@proton/pass/store/actions';
import type { SafeUserState } from '@proton/pass/store/reducers';
import type { State, WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { Maybe } from '@proton/pass/types';
import type { EncryptedPassCache, PassCache } from '@proton/pass/types/worker/cache';
import { pick } from '@proton/shared/lib/helpers/object';
import { userAccessRequest, userFeaturesRequest } from '../../actions/requests';
/** Requests all user state from the API and updates the
* relevant request metadata for caching purposes */
function* resolveUserState(userId: string) {
const userState: SafeUserState = yield getUserState();
yield put(getUserAccessSuccess(userAccessRequest(userId), pick(userState, ['waitingNewUserInvites', 'plan'])));
yield put(getUserFeaturesSuccess(userFeaturesRequest(userId), userState.features));
return userState;
}
/** Will try to decrypt the store cache and hydrate the store accordingly. Returns a
* boolean flag indicating wether the cache was hydrated from cache or not. */
export function* hydrateFromCache(
/** define how we should merge the incoming state */
merge: (existing: State, incoming: State) => State,
{ getCache, getAuthStore }: WorkerRootSagaOptions
) {
const currentState: State = yield select();
const authStore = getAuthStore();
const keyPassword = authStore.getPassword();
const userID = authStore.getUserID()!;
const sessionLockToken = authStore.getLockToken();
const encryptedCache: Partial<EncryptedPassCache> = yield getCache();
const cache: Maybe<PassCache> = yield decryptCachedState(encryptedCache, sessionLockToken);
const userState: SafeUserState = cache?.state.user ?? (yield resolveUserState(userID));
const state: State = { ...(cache?.state ? merge(currentState, cache.state) : currentState), user: userState };
const user = userState.user;
const addresses = Object.values(userState.addresses);
PassCrypto.clear();
yield PassCrypto.hydrate({ user, keyPassword, addresses, snapshot: cache?.snapshot });
yield put(stateHydrate(state));
return cache?.state !== undefined;
}
function* hydrateWorker(options: WorkerRootSagaOptions) {
try {
yield put(stopEventPolling());
yield hydrateFromCache((_, incoming) => incoming, options);
yield put(startEventPolling());
} catch {}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLeading(stateSync.match, hydrateWorker, options);
}
| 8,006
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/notification.saga.ts
|
import type { AnyAction } from 'redux';
import { takeEvery } from 'redux-saga/effects';
import type { WithNotification } from '@proton/pass/store/actions/with-notification';
import { isActionWithNotification } from '@proton/pass/store/actions/with-notification';
import { isActionWithRequest } from '@proton/pass/store/actions/with-request';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
function* notificationWorker({ onNotification }: WorkerRootSagaOptions, action: WithNotification<AnyAction>) {
const { notification } = action.meta;
/* if the action has request metadata - use the
* request id as the notification key in order to
* correctly de-duplicate them */
if (isActionWithRequest(action)) {
notification.deduplicate = true;
notification.key = action.meta.request.id;
}
onNotification?.(notification);
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(isActionWithNotification, notificationWorker, options);
}
| 8,007
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/report-problem.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { api } from '@proton/pass/lib/api/api';
import { reportBugFailure, reportBugIntent, reportBugSuccess } from '@proton/pass/store/actions';
import type { WithSenderAction } from '@proton/pass/store/actions/with-receiver';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import { reportBug } from '@proton/shared/lib/api/reports';
function* reportProblem(
_: WorkerRootSagaOptions,
{ payload, meta }: WithSenderAction<ReturnType<typeof reportBugIntent>>
): Generator {
try {
yield api(reportBug(payload));
yield put(reportBugSuccess(meta.request.id, meta.sender?.endpoint));
} catch (error) {
yield put(reportBugFailure(meta.request.id, error, meta.sender?.endpoint));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(reportBugIntent.match, reportProblem, options);
}
| 8,008
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/request-saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { requestInvalidate } from '@proton/pass/store/actions';
import { isActionWithRequest } from '@proton/pass/store/actions/with-request';
import { wait } from '@proton/shared/lib/helpers/promise';
/**
* request data garbage collection : on a request success or failure,
* if it not persistent, dispatch an acknowledgment action in order to
* clear the request data for this particular request id.
*/
export default function* watcher() {
yield takeEvery(isActionWithRequest, function* ({ meta: { request } }) {
if (request.type !== 'start' && !request.maxAge) {
yield wait(500);
yield put(requestInvalidate(request.id));
}
});
}
| 8,009
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/settings.saga.ts
|
import { put, select, takeEvery } from 'redux-saga/effects';
import { settingsEditFailure, settingsEditIntent, settingsEditSuccess } from '@proton/pass/store/actions';
import type { WithSenderAction } from '@proton/pass/store/actions/with-receiver';
import type { ProxiedSettings } from '@proton/pass/store/reducers/settings';
import { selectProxiedSettings } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import { partialMerge } from '@proton/pass/utils/object/merge';
function* settingsEditWorker(
{ onSettingUpdate }: WorkerRootSagaOptions,
{ meta, payload }: WithSenderAction<ReturnType<typeof settingsEditIntent>>
) {
try {
const settings: ProxiedSettings = yield select(selectProxiedSettings);
/* `disallowedDomains` update should act as a setter */
if ('disallowedDomains' in payload) settings.disallowedDomains = {};
yield onSettingUpdate?.(partialMerge(settings, payload));
yield put(settingsEditSuccess(meta.request.id, payload, meta.sender?.endpoint));
} catch (e) {
yield put(settingsEditFailure(meta.request.id, e, meta.sender?.endpoint));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(settingsEditIntent.match, settingsEditWorker, options);
}
| 8,010
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/sync.saga.ts
|
import { call, put, race, select, take } from 'redux-saga/effects';
import {
getUserAccessIntent,
getUserFeaturesIntent,
startEventPolling,
stateDestroy,
stopEventPolling,
syncFailure,
syncIntent,
syncSuccess,
} from '@proton/pass/store/actions';
import { userAccessRequest, userFeaturesRequest } from '@proton/pass/store/actions/requests';
import { withRevalidate } from '@proton/pass/store/actions/with-request';
import { SyncType, synchronize } from '@proton/pass/store/sagas/client/sync';
import { selectUser } from '@proton/pass/store/selectors';
import type { State, WorkerRootSagaOptions } from '@proton/pass/store/types';
import { wait } from '@proton/shared/lib/helpers/promise';
function* syncWorker(options: WorkerRootSagaOptions) {
yield put(stopEventPolling());
const state = (yield select()) as State;
const user = selectUser(state);
if (!user) return;
try {
yield wait(1500);
yield put(withRevalidate(getUserAccessIntent(userAccessRequest(user.ID))));
yield put(withRevalidate(getUserFeaturesIntent(userFeaturesRequest(user.ID))));
yield put(syncSuccess(yield call(synchronize, { type: SyncType.FULL }, options)));
} catch (e: unknown) {
yield put(syncFailure(e));
} finally {
yield put(startEventPolling());
}
}
/* The `syncWorker` function can take a long time to complete. In order to avoid conflicts
* with any state resetting actions, we race the `sync` against such actions. */
export default function* watcher(options: WorkerRootSagaOptions): Generator {
while (true) {
yield call(function* () {
yield take(syncIntent.match);
yield race({
sync: syncWorker(options),
cancel: take(stateDestroy.match),
});
});
}
}
| 8,011
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/sync.ts
|
import { put, select } from 'redux-saga/effects';
import { PassCrypto } from '@proton/pass/lib/crypto/pass-crypto';
import { requestItemsForShareId } from '@proton/pass/lib/items/item.requests';
import { parseShareResponse } from '@proton/pass/lib/shares/share.parser';
import { requestShares } from '@proton/pass/lib/shares/share.requests';
import { isOwnVault, isWritableVault } from '@proton/pass/lib/vaults/vault.predicates';
import { createVault } from '@proton/pass/lib/vaults/vault.requests';
import { asIfNotOptimistic } from '@proton/pass/store//optimistic/selectors/select-is-optimistic';
import { notification } from '@proton/pass/store/actions';
import { type ItemsByShareId, type SharesState, reducerMap } from '@proton/pass/store/reducers';
import { selectAllShares, selectItems } from '@proton/pass/store/selectors';
import type { State, WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { Maybe } from '@proton/pass/types';
import { type Share, type ShareGetResponse, ShareType } from '@proton/pass/types';
import { NotificationKey } from '@proton/pass/types/worker/notification';
import { partition } from '@proton/pass/utils/array/partition';
import { prop } from '@proton/pass/utils/fp/lens';
import { pipe } from '@proton/pass/utils/fp/pipe';
import { and, invert, notIn } from '@proton/pass/utils/fp/predicates';
import { sortOn } from '@proton/pass/utils/fp/sort';
import { diadic } from '@proton/pass/utils/fp/variadics';
import { logger } from '@proton/pass/utils/logger';
import { objectFilter } from '@proton/pass/utils/object/filter';
import { fullMerge, merge } from '@proton/pass/utils/object/merge';
import { toMap } from '@proton/shared/lib/helpers/object';
export type SynchronizationOptions = { type: SyncType; allowFailure?: boolean };
export type SynchronizationResult = { shares: SharesState; items: ItemsByShareId };
export enum SyncType {
FULL = 'full' /* fetches all items */,
PARTIAL = 'partial' /* fetches only diff */,
}
const isActiveVault = <T extends Share>({ targetType, shareId }: T) =>
targetType === ShareType.Vault && PassCrypto.canOpenShare(shareId);
export function* synchronize(options: SynchronizationOptions, { onShareEventDisabled }: WorkerRootSagaOptions) {
try {
const state: State = asIfNotOptimistic((yield select()) as State, reducerMap);
const cachedShares = selectAllShares(state);
const remote = ((yield requestShares()) as ShareGetResponse[]).sort(sortOn('CreateTime', 'ASC'));
/* `cachedShareIds`: all shares currently in local cache
* `inactiveCachedShareIds` : cached shares which can no longer be opened
* `remoteShareIds` : all shares available server-side
* `deletedShareIds` : local shares which have been deleted
* `disabledShareIds` : `deletedShareIds` + `inactiveCachedShareIds` */
const cachedShareIds = cachedShares.map(prop('shareId'));
const inactiveCachedShareIds = cachedShareIds.filter(invert(PassCrypto.canOpenShare));
const remoteShareIds = remote.map(prop('ShareID'));
const deletedShareIds = cachedShareIds.filter(notIn(remoteShareIds));
const disabledShareIds = Array.from(new Set(deletedShareIds.concat(inactiveCachedShareIds)));
/* notify clients of any disabled shares */
disabledShareIds.forEach((shareId) => onShareEventDisabled?.(shareId));
/* only load shares that are not currently present
* in cache and have not been registered on PassCrypto.
* Share loading may fail if the userkey it was encrypted
* with is inactive */
const remoteShares = (yield Promise.all(
remote.filter(pipe(prop('ShareID'), notIn(cachedShareIds))).map(async (encryptedShare) => ({
shareId: encryptedShare.ShareID,
share: await parseShareResponse(encryptedShare),
}))
)) as { shareId: string; share: Maybe<Share> }[];
/* split active from inactive shares */
const [activeRemoteShares, inactiveRemoteShares] = partition(remoteShares, ({ share }) => Boolean(share));
const totalInactiveShares = inactiveRemoteShares.length + inactiveCachedShareIds.length;
/* update the disabled shareIds list with any inactive remote shares */
disabledShareIds.push(...inactiveRemoteShares.map(prop('shareId')));
if (totalInactiveShares > 0) {
yield put(
notification({
endpoint: 'popup',
type: 'error',
expiration: -1,
key: NotificationKey.INACTIVE_SHARES,
text: '',
})
);
}
/* when checking the presence of an active vault we must both
* check the active remote shares and the local cached shares */
const incomingShares = activeRemoteShares.map(prop('share')) as Share[];
const incomingShareIds = incomingShares.map(prop('shareId'));
const hasDefaultVault = incomingShares
.concat(cachedShares)
.some(and(isActiveVault, isWritableVault, isOwnVault));
/* When syncing, if no owned writable vault exists, create it. This
* accounts for first login, default vault being disabledl. */
if (!hasDefaultVault) {
logger.info(`[Saga::Sync] No default vault found, creating initial vault..`);
const defaultVault: Share<ShareType.Vault> = yield createVault({
content: {
name: 'Personal',
description: 'Personal vault',
display: {},
},
});
incomingShares.push(defaultVault);
}
logger.info(`[Saga::Sync] Discovered ${cachedShareIds.length} share(s) in cache`);
logger.info(`[Saga::Sync] User has ${remote.length} share(s) in database`);
logger.info(`[Saga::Sync] ${deletedShareIds.length} share(s) deleted`);
logger.info(`[Saga::Sync] User has ${totalInactiveShares} total inactive share(s)`);
logger.info(`[Saga::Sync] ${incomingShares.length} share(s) need to be synced`);
logger.info(`[Saga::Sync] Performing ${options.type} sync`);
/* On full sync : we want to request all items for each share
* On partial sync : only request items for new shares (event-loop
* will take care of updates) and remove items from deleted shares */
const fullSync = options.type === SyncType.FULL;
const itemShareIds = (fullSync ? remoteShareIds : incomingShareIds).filter(notIn(disabledShareIds));
const itemState = fullSync ? {} : objectFilter(selectItems(state), notIn(disabledShareIds));
const syncedItems = (yield Promise.all(
itemShareIds.map(
async (shareId): Promise<ItemsByShareId> => ({
[shareId]: toMap(await requestItemsForShareId(shareId), 'itemId'),
})
)
)) as ItemsByShareId[];
/* Exclude the deleted shares from the cached shares
* and merge with the new shares */
const shares = cachedShares.filter(({ shareId }) => !disabledShareIds.includes(shareId)).concat(incomingShares);
const result: SynchronizationResult = {
shares: toMap(shares, 'shareId'),
items: fullMerge(itemState, syncedItems.reduce(diadic(merge), {})),
};
return result;
} catch (err) {
if (!options.allowFailure) throw err;
}
}
| 8,012
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/client/wakeup.saga.ts
|
import { fork, put, select, takeEvery } from 'redux-saga/effects';
import { clientErrored } from '@proton/pass/lib/client';
import { filterDeletedTabIds } from '@proton/pass/lib/extension/utils/tabs';
import {
getUserAccessIntent,
getUserFeaturesIntent,
stateHydrate,
wakeupIntent,
wakeupSuccess,
} from '@proton/pass/store/actions';
import { popupTabStateGarbageCollect } from '@proton/pass/store/actions/creators/popup';
import { passwordHistoryGarbageCollect } from '@proton/pass/store/actions/creators/pw-history';
import { userAccessRequest, userFeaturesRequest } from '@proton/pass/store/actions/requests';
import type { WithReceiverAction } from '@proton/pass/store/actions/with-receiver';
import { withRevalidate } from '@proton/pass/store/actions/with-request';
import { selectPopupStateTabIds } from '@proton/pass/store/selectors';
import type { State, WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { TabId } from '@proton/pass/types';
import identity from '@proton/utils/identity';
function* wakeupWorker(
{ getAuthStore: getAuth }: WorkerRootSagaOptions,
{ payload: { status }, meta }: WithReceiverAction<ReturnType<typeof wakeupIntent>>
) {
const { tabId, endpoint } = meta.receiver;
const loggedIn = getAuth().hasSession();
const userId = getAuth().getUserID();
/* synchronise the target client app state */
yield put(stateHydrate((yield select()) as State, { endpoint, tabId }));
if (loggedIn && userId && !clientErrored(status)) {
const maybeRevalidate = endpoint === 'popup' ? withRevalidate : identity;
yield put(maybeRevalidate(getUserAccessIntent(userAccessRequest(userId))));
yield put(getUserFeaturesIntent(userFeaturesRequest(userId)));
/* garbage collect any stale popup tab
* state on each popup wakeup call */
if (endpoint === 'popup') {
yield put(passwordHistoryGarbageCollect());
yield fork(function* () {
const tabIds: TabId[] = yield select(selectPopupStateTabIds);
const deletedTabIds: TabId[] = yield filterDeletedTabIds(tabIds);
yield put(popupTabStateGarbageCollect({ tabIds: deletedTabIds }));
});
}
}
yield put(wakeupSuccess(meta.request.id, { endpoint, tabId }));
}
export default function* watcher(options: WorkerRootSagaOptions): Generator {
yield takeEvery(wakeupIntent.match, wakeupWorker, options);
}
| 8,013
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/events/channel.factory.ts
|
import { eventChannel } from 'redux-saga';
import { type EventManagerEvent, eventManager } from '@proton/pass/lib/events/manager';
import { merge } from '@proton/pass/utils/object/merge';
import type { EventChannel, EventChannelOnError, EventChannelOptions } from './types';
const channelErrorHandler = <T extends {}>(onError?: EventChannelOnError<T>) => {
const wrappedOnError: EventChannelOnError<T> = function* (error, eventsChannel, options) {
yield onError?.(error, eventsChannel, options);
if (error instanceof Error && ['LockedSession', 'InactiveSession'].includes(error.name)) {
eventsChannel.channel.close();
}
};
return wrappedOnError;
};
export const eventChannelFactory = <T extends {}>(config: EventChannelOptions<T>) => {
const { onClose, onError } = config;
const manager = eventManager<T>(config);
return merge(config, {
onError: channelErrorHandler<T>(onError),
manager,
channel: eventChannel<EventManagerEvent<T>>((emitter) => {
const unsubscribe = manager.subscribe(emitter);
return () => {
onClose?.();
unsubscribe();
manager.stop();
manager.reset();
};
}),
}) as EventChannel<T>;
};
| 8,014
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/events/channel.invites.ts
|
/* eslint-disable @typescript-eslint/no-throw-literal, curly */
import { all, fork, put, select } from 'redux-saga/effects';
import { getPublicKeysForEmail } from '@proton/pass/lib/auth/address';
import { PassCrypto } from '@proton/pass/lib/crypto/pass-crypto';
import { ACTIVE_POLLING_TIMEOUT } from '@proton/pass/lib/events/constants';
import { type EventManagerEvent, NOOP_EVENT } from '@proton/pass/lib/events/manager';
import { decodeVaultContent } from '@proton/pass/lib/vaults/vault-proto.transformer';
import { syncInvites } from '@proton/pass/store/actions';
import type { InviteState } from '@proton/pass/store/reducers';
import { selectFeatureFlag } from '@proton/pass/store/selectors';
import { selectInvites } from '@proton/pass/store/selectors/invites';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { InvitesGetResponse, MaybeNull } from '@proton/pass/types';
import { type Api } from '@proton/pass/types';
import { PassFeature } from '@proton/pass/types/api/features';
import type { Invite } from '@proton/pass/types/data/invites';
import { truthy } from '@proton/pass/utils/fp/predicates';
import { logId, logger } from '@proton/pass/utils/logger';
import { toMap } from '@proton/shared/lib/helpers/object';
import { eventChannelFactory } from './channel.factory';
import { channelEventsWorker, channelWakeupWorker } from './channel.worker';
const NAMESPACE = 'Saga::InvitesChannel';
function* onInvitesEvent(event: EventManagerEvent<InvitesGetResponse>) {
if ('error' in event) throw event.error;
const cachedInvites: InviteState = yield select(selectInvites);
const cachedInviteTokens = Object.keys(cachedInvites);
const noop =
event.Invites.length === cachedInviteTokens.length &&
event.Invites.every(({ InviteToken }) => cachedInviteTokens.includes(InviteToken));
if (noop) return;
const invites: MaybeNull<Invite>[] = yield Promise.all(
event.Invites.map<Promise<MaybeNull<Invite>>>(async (invite) => {
/* if invite already decrypted early return */
const cachedInvite = cachedInvites[invite.InviteToken];
if (cachedInvite) return cachedInvite;
/* FIXME: support item invites */
const encryptedVault = invite.VaultData;
if (!encryptedVault) return null;
const inviteKey = invite.Keys.find((key) => key.KeyRotation === encryptedVault.ContentKeyRotation);
if (!inviteKey) return null;
try {
const encodedVault = await PassCrypto.readVaultInvite({
encryptedVaultContent: encryptedVault.Content,
invitedAddressId: invite.InvitedAddressID!,
inviteKey: inviteKey,
inviterPublicKeys: await getPublicKeysForEmail(invite.InviterEmail),
});
return {
createTime: invite.CreateTime,
invitedAddressId: invite.InvitedAddressID!,
invitedEmail: invite.InvitedEmail,
inviterEmail: invite.InviterEmail,
fromNewUser: invite.FromNewUser,
keys: invite.Keys,
remindersSent: invite.RemindersSent,
targetId: invite.TargetID,
targetType: invite.TargetType,
token: invite.InviteToken,
vault: {
content: decodeVaultContent(encodedVault),
memberCount: encryptedVault.MemberCount!,
itemCount: encryptedVault.ItemCount!,
},
};
} catch (err) {
logger.info(`[${NAMESPACE}] Could not decrypt invite "${logId(invite.InviteToken)}"`);
return null;
}
})
);
yield put(syncInvites(toMap(invites.filter(truthy), 'token')));
}
export const createInvitesChannel = (api: Api) =>
eventChannelFactory<InvitesGetResponse>({
api,
interval: ACTIVE_POLLING_TIMEOUT,
initialEventID: NOOP_EVENT,
getCursor: () => ({ EventID: NOOP_EVENT, More: false }),
query: () => ({ url: `pass/v1/invite`, method: 'get' }),
onEvent: onInvitesEvent,
onClose: () => logger.info(`[${NAMESPACE}] closing channel`),
});
export function* invitesChannel(api: Api, options: WorkerRootSagaOptions) {
const sharingEnabled: boolean = yield select(selectFeatureFlag(PassFeature.PassSharingV1));
if (!sharingEnabled) return;
logger.info(`[${NAMESPACE}] start polling for invites`);
const eventsChannel = createInvitesChannel(api);
const events = fork(channelEventsWorker<InvitesGetResponse>, eventsChannel, options);
const wakeup = fork(channelWakeupWorker<InvitesGetResponse>, eventsChannel);
yield all([events, wakeup]);
}
| 8,015
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/events/channel.share.ts
|
/* eslint-disable @typescript-eslint/no-throw-literal, curly */
import type { AnyAction } from 'redux';
import { all, call, fork, put, select, take } from 'redux-saga/effects';
import { ACTIVE_POLLING_TIMEOUT } from '@proton/pass/lib/events/constants';
import type { EventManagerEvent } from '@proton/pass/lib/events/manager';
import { parseItemRevision } from '@proton/pass/lib/items/item.parser';
import { parseShareResponse } from '@proton/pass/lib/shares/share.parser';
import { getShareLatestEventId } from '@proton/pass/lib/shares/share.requests';
import {
itemDeleteSync,
itemEditSync,
itemUsedSync,
shareDeleteSync,
shareEditSync,
shareEvent,
vaultDeleteSuccess,
} from '@proton/pass/store/actions';
import type { ShareItem } from '@proton/pass/store/reducers/shares';
import { selectAllShares, selectShare } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { Api, ItemRevision, Maybe, PassEventListResponse, Share } from '@proton/pass/types';
import { ShareType } from '@proton/pass/types';
import { logId, logger } from '@proton/pass/utils/logger';
import { getApiError } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { eventChannelFactory } from './channel.factory';
import { channelEventsWorker, channelWakeupWorker } from './channel.worker';
import type { EventChannel } from './types';
export type ShareEventResponse = { Events: PassEventListResponse };
/* It is important to call onShareEventItemsDeleted before
* actually dispatching the resulting action : we may be dealing
* with a share or an item being selected in the pop-up and need
* to run the side-effect before clearing the data from the store
* FIXME: support ItemShares */
const onShareEvent = (shareId: string) =>
function* (
event: EventManagerEvent<ShareEventResponse>,
_: EventChannel<ShareEventResponse>,
{ onItemsChange, onShareEventItemsDeleted }: WorkerRootSagaOptions
) {
if ('error' in event) throw event.error;
const { Events } = event;
const { LatestEventID: eventId, DeletedItemIDs, UpdatedItems, UpdatedShare, LastUseItems } = Events;
const currentEventId = ((yield select(selectShare(shareId))) as Maybe<ShareItem>)?.eventId;
logger.info(`[Saga::ShareChannel] event ${logId(eventId)} for share ${logId(shareId)}`);
/* dispatch only if there was a change */
if (currentEventId !== eventId) yield put(shareEvent({ ...event, shareId }));
if (UpdatedShare && UpdatedShare.TargetType === ShareType.Vault) {
const share: Maybe<Share<ShareType.Vault>> = yield parseShareResponse(UpdatedShare, { eventId });
if (share) yield put(shareEditSync({ id: share.shareId, share }));
}
if (DeletedItemIDs.length > 0) {
onShareEventItemsDeleted?.(shareId, DeletedItemIDs);
}
yield all([
...DeletedItemIDs.map((itemId) => put(itemDeleteSync({ itemId, shareId }))),
...UpdatedItems.map((encryptedItem) =>
call(function* () {
try {
const item: ItemRevision = yield parseItemRevision(shareId, encryptedItem);
yield put(itemEditSync({ shareId: item.shareId, itemId: item.itemId, item }));
} catch (_) {}
})
),
...(LastUseItems ?? []).map(({ ItemID, LastUseTime }) =>
put(itemUsedSync({ shareId, itemId: ItemID, lastUseTime: LastUseTime }))
),
]);
const itemsMutated = DeletedItemIDs.length > 0 || UpdatedItems.length > 0;
if (itemsMutated) onItemsChange?.();
};
const onShareEventError = (shareId: string) =>
function* (
error: unknown,
{ channel }: EventChannel<ShareEventResponse>,
{ onShareEventDisabled, onItemsChange }: WorkerRootSagaOptions
) {
const { code } = getApiError(error);
/* share was deleted or user lost access */
if (code === 300004) {
logger.info(`[Saga::SharesChannel] share ${logId(shareId)} disabled`);
channel.close();
const share: Maybe<Share> = yield select(selectShare(shareId));
if (share) {
onShareEventDisabled?.(shareId);
onItemsChange?.();
yield put(shareDeleteSync(share));
}
}
};
const onShareDeleted = (shareId: string) =>
function* ({ channel }: EventChannel<ShareEventResponse>): Generator {
yield take((action: AnyAction) => vaultDeleteSuccess.match(action) && action.payload.shareId === shareId);
logger.info(`[Saga::ShareChannel] share ${logId(shareId)} deleted`);
channel.close();
};
/* We need to lift the response to the correct data
* structure by leveraging ApiOptions::mapResponse
* (see type definition and create-api.ts for specs) */
export const createShareChannel = (api: Api, { shareId, eventId }: Share) =>
eventChannelFactory<ShareEventResponse>({
api,
interval: ACTIVE_POLLING_TIMEOUT,
initialEventID: eventId,
query: (eventId) => ({ url: `pass/v1/share/${shareId}/event/${eventId}`, method: 'get' }),
getCursor: ({ Events }) => ({ EventID: Events.LatestEventID, More: Events.EventsPending }),
getLatestEventID: () => getShareLatestEventId(shareId),
onClose: () => logger.info(`[Saga::ShareChannel] closing channel for ${logId(shareId)}`),
onEvent: onShareEvent(shareId),
onError: onShareEventError(shareId),
});
export const getShareChannelForks = (api: Api, options: WorkerRootSagaOptions) => (share: Share) => {
logger.info(`[Saga::ShareChannel] start polling for share ${logId(share.shareId)}`);
const eventsChannel = createShareChannel(api, share);
const events = fork(channelEventsWorker<ShareEventResponse>, eventsChannel, options);
const wakeup = fork(channelWakeupWorker<ShareEventResponse>, eventsChannel);
const onDelete = fork(onShareDeleted(share.shareId), eventsChannel);
return [events, wakeup, onDelete];
};
export function* shareChannels(api: Api, options: WorkerRootSagaOptions) {
const shares = (yield select(selectAllShares)) as Share[];
yield all(shares.map(getShareChannelForks(api, options)).flat());
}
| 8,016
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/events/channel.shares.ts
|
/* eslint-disable @typescript-eslint/no-throw-literal, curly */
import { all, fork, put, select, takeEvery } from 'redux-saga/effects';
import { ACTIVE_POLLING_TIMEOUT } from '@proton/pass/lib/events/constants';
import { type EventManagerEvent, NOOP_EVENT } from '@proton/pass/lib/events/manager';
import { requestItemsForShareId } from '@proton/pass/lib/items/item.requests';
import { parseShareResponse } from '@proton/pass/lib/shares/share.parser';
import { hasShareAccessChanged } from '@proton/pass/lib/shares/share.predicates';
import { shareAccessChange, sharesSync, vaultCreationSuccess } from '@proton/pass/store/actions';
import type { ItemsByShareId } from '@proton/pass/store/reducers';
import { selectAllShares } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { Api, Maybe, Share, ShareRole, SharesGetResponse } from '@proton/pass/types';
import { ShareType } from '@proton/pass/types';
import { truthy } from '@proton/pass/utils/fp/predicates';
import { diadic } from '@proton/pass/utils/fp/variadics';
import { logger } from '@proton/pass/utils/logger';
import { merge } from '@proton/pass/utils/object/merge';
import { toMap } from '@proton/shared/lib/helpers/object';
import { eventChannelFactory } from './channel.factory';
import { getShareChannelForks } from './channel.share';
import { channelEventsWorker, channelWakeupWorker } from './channel.worker';
import type { EventChannel } from './types';
/* We're only interested in new shares in this effect :
* deleted shares will be handled by the share's EventChannel
* error handling. see `channel.share.ts` code `300004`
* FIXME: handle ItemShares */
function* onSharesEvent(
event: EventManagerEvent<SharesGetResponse>,
{ api }: EventChannel<any>,
options: WorkerRootSagaOptions
) {
if ('error' in event) throw event.error;
const localShares: Share[] = yield select(selectAllShares);
const localShareIds = localShares.map(({ shareId }) => shareId);
const remoteShares = event.Shares;
const newShares = remoteShares.filter((share) => !localShareIds.includes(share.ShareID));
logger.info(`[Saga::SharesChannel]`, `${newShares.length} remote share(s) not in cache`);
if (newShares.length) {
const activeNewShares = (
(yield Promise.all(
newShares
.filter((share) => share.TargetType === ShareType.Vault)
.map((encryptedShare) => parseShareResponse(encryptedShare))
)) as Maybe<Share>[]
).filter(truthy);
if (activeNewShares.length > 0) {
const items = (
(yield Promise.all(
activeNewShares.map(async ({ shareId }) => ({
[shareId]: toMap(await requestItemsForShareId(shareId), 'itemId'),
}))
)) as ItemsByShareId[]
).reduce(diadic(merge));
yield put(sharesSync({ shares: toMap(activeNewShares, 'shareId'), items }));
yield all(activeNewShares.map(getShareChannelForks(api, options)).flat());
}
}
yield fork(function* () {
for (const share of remoteShares) {
const shareId = share.ShareID;
const localShare = localShares.find((localShare) => localShare.shareId === shareId);
if (localShare && hasShareAccessChanged(localShare, share)) {
yield put(
shareAccessChange({
newUserInvitesReady: share.NewUserInvitesReady,
owner: share.Owner,
shared: share.Shared,
shareId,
shareRoleId: share.ShareRoleID as ShareRole,
targetMaxMembers: share.TargetMaxMembers,
targetMembers: share.TargetMembers,
})
);
}
}
});
}
/* The event-manager can be used to implement
* a polling mechanism if we conform to the data
* structure it is expecting. In order to poll for
* new shares, set the query accordingly & use a
* non-existing eventID */
export const createSharesChannel = (api: Api) =>
eventChannelFactory<SharesGetResponse>({
api,
interval: ACTIVE_POLLING_TIMEOUT,
initialEventID: NOOP_EVENT,
getCursor: () => ({ EventID: NOOP_EVENT, More: false }),
onClose: () => logger.info(`[Saga::SharesChannel] closing channel`),
onEvent: onSharesEvent,
query: () => ({ url: 'pass/v1/share', method: 'get' }),
});
/* when a vault is created : recreate all the necessary
* channels to start polling for this new share's events */
function* onNewShare(api: Api, options: WorkerRootSagaOptions) {
yield takeEvery(vaultCreationSuccess.match, function* ({ payload: { share } }) {
yield all(getShareChannelForks(api, options)(share));
});
}
export function* sharesChannel(api: Api, options: WorkerRootSagaOptions) {
logger.info(`[Saga::SharesChannel] start polling for new shares`);
const eventsChannel = createSharesChannel(api);
const events = fork(channelEventsWorker<SharesGetResponse>, eventsChannel, options);
const wakeup = fork(channelWakeupWorker<SharesGetResponse>, eventsChannel);
const newVault = fork(onNewShare, api, options);
yield all([events, wakeup, newVault]);
}
| 8,017
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/events/channel.user.ts
|
/* eslint-disable @typescript-eslint/no-throw-literal, curly */
import { all, fork, put, select } from 'redux-saga/effects';
import { PassCrypto } from '@proton/pass/lib/crypto/pass-crypto';
import { ACTIVE_POLLING_TIMEOUT } from '@proton/pass/lib/events/constants';
import type { EventCursor, EventManagerEvent } from '@proton/pass/lib/events/manager';
import { getUserAccessIntent, syncIntent, userEvent } from '@proton/pass/store/actions';
import { userAccessRequest } from '@proton/pass/store/actions/requests';
import { withRevalidate } from '@proton/pass/store/actions/with-request';
import { selectAllAddresses, selectLatestEventId, selectUserSettings } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { MaybeNull, UserEvent } from '@proton/pass/types';
import { type Api } from '@proton/pass/types';
import { prop } from '@proton/pass/utils/fp/lens';
import { notIn } from '@proton/pass/utils/fp/predicates';
import { logId, logger } from '@proton/pass/utils/logger';
import { getEvents, getLatestID } from '@proton/shared/lib/api/events';
import type { Address, UserSettings } from '@proton/shared/lib/interfaces';
import { eventChannelFactory } from './channel.factory';
import { channelEventsWorker, channelWakeupWorker } from './channel.worker';
import type { EventChannel } from './types';
function* onUserEvent(
event: EventManagerEvent<UserEvent>,
_: EventChannel<UserEvent>,
{ getAuthStore, getTelemetry }: WorkerRootSagaOptions
) {
const telemetry = getTelemetry();
if ('error' in event) throw event.error;
const currentEventId = (yield select(selectLatestEventId)) as MaybeNull<string>;
/* dispatch only if there was a change */
if (currentEventId !== event.EventID) yield put(userEvent(event));
logger.info(`[ServerEvents::User] event ${logId(event.EventID!)}`);
const { User: user } = event;
if (event.UserSettings && telemetry) {
const { Telemetry } = event.UserSettings;
const userSettings: MaybeNull<UserSettings> = yield select(selectUserSettings);
if (Telemetry !== userSettings?.Telemetry) telemetry[Telemetry === 1 ? 'start' : 'stop']();
}
/* if the subscription/invoice changes, refetch the user Plan */
if (event.Subscription || event.Invoices) {
const getPlanAction = withRevalidate(getUserAccessIntent(userAccessRequest(getAuthStore().getUserID()!)));
yield put(getPlanAction);
}
/* if we get the user model from the event, check if
* any new active user keys are available. We might be
* dealing with a user re-activating a disabled user key
* in which case we want to trigger a full data sync in
* order to access any previously inactive shares */
if (user) {
const localUserKeyIds = (PassCrypto.getContext().userKeys ?? []).map(prop('ID'));
const activeUserKeys = user.Keys.filter(({ Active }) => Active === 1);
const keysUpdated =
activeUserKeys.length !== localUserKeyIds.length ||
activeUserKeys.some(({ ID }) => notIn(localUserKeyIds)(ID));
if (keysUpdated) {
logger.info(`[Saga::Events] Detected user keys update`);
const keyPassword = getAuthStore().getPassword();
const addresses = (yield select(selectAllAddresses)) as Address[];
yield PassCrypto.hydrate({ user, keyPassword, addresses });
yield put(syncIntent()); /* trigger a full data sync */
}
}
}
export const createUserChannel = (api: Api, eventID: string) =>
eventChannelFactory<UserEvent>({
api,
interval: ACTIVE_POLLING_TIMEOUT,
initialEventID: eventID,
query: getEvents,
getCursor: ({ EventID, More }) => ({ EventID, More: Boolean(More) }),
getLatestEventID: () => api<EventCursor>(getLatestID()).then(({ EventID }) => EventID),
onEvent: onUserEvent,
onClose: () => logger.info(`[Saga::UserChannel] closing channel`),
});
export function* userChannel(api: Api, options: WorkerRootSagaOptions) {
logger.info(`[Saga::UserChannel] start polling for user events`);
const eventID: string = ((yield select(selectLatestEventId)) as ReturnType<typeof selectLatestEventId>) ?? '';
const eventsChannel = createUserChannel(api, eventID);
const events = fork(channelEventsWorker<UserEvent>, eventsChannel, options);
const wakeup = fork(channelWakeupWorker<UserEvent>, eventsChannel);
yield all([events, wakeup]);
}
| 8,018
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/events/channel.worker.ts
|
import type { AnyAction } from 'redux';
import { call, cancelled, take, takeLeading } from 'redux-saga/effects';
import { ACTIVE_POLLING_TIMEOUT } from '@proton/pass/lib/events/constants';
import type { EventManagerEvent } from '@proton/pass/lib/events/manager';
import { wakeupSuccess } from '@proton/pass/store/actions';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import { logger } from '@proton/pass/utils/logger';
import { wait } from '@proton/shared/lib/helpers/promise';
import noop from '@proton/utils/noop';
import type { EventChannel } from './types';
/* generic worker over an EventChannel : responsible for polling
* the underlying redux-saga event channel and triggering the
* appropriate callback generators. Closes the channel if the
* parent task is canceled */
export function* channelEventsWorker<T extends {}>(
eventChannel: EventChannel<T>,
options: WorkerRootSagaOptions
): Generator {
const { channel, onEvent, onError, manager } = eventChannel;
try {
while (true) {
try {
manager.setInterval(options.getEventInterval());
const event = (yield take(channel)) as EventManagerEvent<T>;
yield call(onEvent, event, eventChannel, options);
} catch (error: unknown) {
logger.warn(`[Saga::Events] received an event error`, error);
if (onError) yield call(onError, error, eventChannel, options);
}
}
} finally {
if (yield cancelled()) channel.close();
}
}
/* This worker will call the event manager immediately and
* on every wakeupSuccess action coming from the pop-up in
* in order to sync as quickly as possible. Take the leading
* wakeup call in order to avoid unnecessary parallel calls */
export function* channelWakeupWorker<T extends {}>({ manager }: EventChannel<T>): Generator {
yield manager.call().catch(noop);
yield takeLeading(
(action: AnyAction) => wakeupSuccess.match(action) && action.meta.receiver.endpoint === 'popup',
function* () {
yield manager.call().catch(noop);
/* wait the channel's interval to process
* the next wakeupSuccess in case user is
* repeatedly opening the pop-up */
yield wait(ACTIVE_POLLING_TIMEOUT);
}
);
}
| 8,019
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/events/events.saga.ts
|
/* eslint-disable curly, @typescript-eslint/no-throw-literal */
import type { AnyAction } from 'redux';
import type { Task } from 'redux-saga';
import { all, cancel, fork, take } from 'redux-saga/effects';
import { api } from '@proton/pass/lib/api/api';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import { logger } from '@proton/pass/utils/logger';
import { startEventPolling, stopEventPolling } from '../../actions';
import { invitesChannel } from './channel.invites';
import { shareChannels } from './channel.share';
import { sharesChannel } from './channel.shares';
import { userChannel } from './channel.user';
function* eventsWorker(options: WorkerRootSagaOptions): Generator {
yield all([userChannel, shareChannels, sharesChannel, invitesChannel].map((effect) => fork(effect, api, options)));
}
export default function* watcher(options: WorkerRootSagaOptions): Generator {
while (yield take(startEventPolling.match)) {
logger.info(`[Saga::Events] start polling all event channels`);
const events = (yield fork(eventsWorker, options)) as Task;
const action = (yield take(stopEventPolling.match)) as AnyAction;
logger.info(`[Saga::Events] cancelling all event channels [${action.type}]`);
yield cancel(events);
}
}
| 8,020
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/events/types.ts
|
import type { EventChannel as ReduxSagaChannel } from 'redux-saga';
import type { EventManager, EventManagerConfig, EventManagerEvent } from '@proton/pass/lib/events/manager';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
export type EventChannelOnEvent<T extends {}> = (
event: EventManagerEvent<T>,
self: EventChannel<T>,
options: WorkerRootSagaOptions
) => Generator;
export type EventChannelOnError<T extends {}> = (
error: unknown,
self: EventChannel<T>,
options: WorkerRootSagaOptions
) => Generator;
export type EventChannelOptions<T extends {}> = EventManagerConfig<T> & {
onClose?: () => void;
onEvent: EventChannelOnEvent<T>;
onError?: EventChannelOnError<T>;
};
export type EventChannel<T extends {}> = EventChannelOptions<T> & {
manager: EventManager<T>;
channel: ReduxSagaChannel<EventManagerEvent<T>>;
};
| 8,021
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/import/import.saga.ts
|
import { call, put, takeLeading } from 'redux-saga/effects';
import { c } from 'ttag';
import { MAX_BATCH_ITEMS_PER_REQUEST } from '@proton/pass/constants';
import { type ImportVault } from '@proton/pass/lib/import/types';
import { parseItemRevision } from '@proton/pass/lib/items/item.parser';
import { importItemsBatch } from '@proton/pass/lib/items/item.requests';
import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event';
import {
importItemsBatchSuccess,
importItemsFailure,
importItemsIntent,
importItemsSuccess,
notification,
requestProgress,
startEventPolling,
stopEventPolling,
vaultCreationIntent,
vaultCreationSuccess,
} from '@proton/pass/store/actions';
import type { WithSenderAction } from '@proton/pass/store/actions/with-receiver';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { ItemRevision, ItemRevisionContentsResponse, Maybe } from '@proton/pass/types';
import { TelemetryEventName } from '@proton/pass/types/data/telemetry';
import { groupByKey } from '@proton/pass/utils/array/group-by-key';
import { prop } from '@proton/pass/utils/fp/lens';
import { logger } from '@proton/pass/utils/logger';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import { getApiErrorMessage } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import capitalize from '@proton/utils/capitalize';
import chunk from '@proton/utils/chunk';
/**
* When creating vaults from the import saga
* we want to internally trigger any saga that
* may result from vaultCreationSuccess (notably
* the event-loop channel updates) : leverage
* the withCallback vaultCreationIntent to await
* the vault creation result
*/
function* createVaultForImport(vaultName: string) {
const date = new Date().toLocaleDateString();
let resolver: (shareId: Maybe<string>) => void;
const creationResult = new Promise<Maybe<string>>((res) => (resolver = res));
yield put(
vaultCreationIntent(
{ content: { name: vaultName, description: c('Info').t`Imported on ${date}`, display: {} } },
(action) => resolver(vaultCreationSuccess.match(action) ? action.payload.share.shareId : undefined)
)
);
const shareId: Maybe<string> = yield creationResult;
if (shareId === undefined) throw new Error(c('Warning').t`Could not create vault "${vaultName}"`);
return shareId;
}
function* importWorker(
{ onItemsChange, getTelemetry }: WorkerRootSagaOptions,
{ payload: { data, provider }, meta }: WithSenderAction<ReturnType<typeof importItemsIntent>>
) {
const telemetry = getTelemetry();
yield put(stopEventPolling());
let totalItems: number = 0;
const ignored: string[] = data.ignored;
const importVaults = groupByKey(data.vaults, 'shareId', { splitEmpty: true }).map(
([vault, ...vaults]): ImportVault => ({
...vault,
items: vault.items.concat(...vaults.map(prop('items'))),
})
);
try {
/* we want to apply these request sequentially to avoid
* swarming the network with too many parallel requests */
for (const vaultData of importVaults) {
try {
const shareId: string = vaultData.shareId ?? (yield call(createVaultForImport, vaultData.name));
for (const batch of chunk(vaultData.items, MAX_BATCH_ITEMS_PER_REQUEST)) {
try {
const revisions: ItemRevisionContentsResponse[] = yield importItemsBatch({
shareId,
importIntents: batch,
onSkippedItem: ({ type, metadata }) =>
ignored.push(`[${capitalize(type)}] ${metadata.name}`),
});
const items: ItemRevision[] = yield Promise.all(
revisions.map((revision) => parseItemRevision(shareId, revision))
);
totalItems += revisions.length;
yield put(requestProgress(meta.request.id, totalItems));
yield put(importItemsBatchSuccess({ shareId, items }));
} catch (e) {
const description = e instanceof Error ? getApiErrorMessage(e) ?? e?.message : '';
ignored.push(...batch.map((item) => `[${capitalize(item.type)}] ${item.metadata.name}`));
yield put(
notification({
endpoint: meta.sender?.endpoint,
key: meta.request.id,
type: 'error',
text: c('Error').t`Import failed for vault "${vaultData.name}" : ${description}`,
})
);
}
}
} catch (e) {
logger.warn('[Saga::Import]', e);
yield put(
notification({
key: meta.request.id,
endpoint: meta.sender?.endpoint,
type: 'error',
text: c('Error').t`Vault "${vaultData.name}" could not be created`,
})
);
}
}
void telemetry?.pushEvent(
createTelemetryEvent(
TelemetryEventName.ImportCompletion,
{ item_count: totalItems, vaults: importVaults.length },
{ source: provider }
)
);
yield put(
importItemsSuccess(
meta.request.id,
{
provider,
ignored,
total: totalItems,
importedAt: getEpoch(),
warnings: data.warnings,
},
meta.sender?.endpoint
)
);
onItemsChange?.();
} catch (error: any) {
yield put(importItemsFailure(meta.request.id, error, meta.sender?.endpoint));
} finally {
yield put(startEventPolling());
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLeading(importItemsIntent.match, importWorker, options);
}
| 8,022
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/invites/invite-accept.saga.ts
|
import { END, eventChannel } from 'redux-saga';
import { put, select, take, takeEvery } from 'redux-saga/effects';
import { c } from 'ttag';
import { acceptInvite } from '@proton/pass/lib/invites/invite.requests';
import { requestItemsForShareId } from '@proton/pass/lib/items/item.requests';
import { parseShareResponse } from '@proton/pass/lib/shares/share.parser';
import {
inviteAcceptFailure,
inviteAcceptIntent,
inviteAcceptSuccess,
requestProgress,
startEventPolling,
stopEventPolling,
} from '@proton/pass/store/actions';
import type { RequestProgress } from '@proton/pass/store/actions/with-request';
import { selectInviteByToken } from '@proton/pass/store/selectors/invites';
import type { Invite, ItemRevision, Maybe, Share, ShareGetResponse, ShareType } from '@proton/pass/types';
import noop from '@proton/utils/noop';
function* acceptInviteWorker({ payload, meta: { request } }: ReturnType<typeof inviteAcceptIntent>) {
try {
yield put(stopEventPolling());
const invite: Maybe<Invite> = yield select(selectInviteByToken(payload.inviteToken));
if (!invite) throw new Error(c('Error').t`Unknown invite`);
const encryptedShare: ShareGetResponse = yield acceptInvite({ ...payload, inviteKeys: invite.keys });
const share: Maybe<Share<ShareType.Vault>> = yield parseShareResponse(encryptedShare);
if (!share) throw new Error(c('Error').t`Could not open invited vault`);
const progressChannel = eventChannel<RequestProgress<ItemRevision[]>>((emitter) => {
requestItemsForShareId(share.shareId, (value) => emitter({ type: 'progress', value }))
.then((result) => emitter({ type: 'done', result }))
.catch((error) => emitter({ type: 'error', error }))
.finally(() => emitter(END));
return noop;
});
while (true) {
const action: RequestProgress<ItemRevision[]> = yield take(progressChannel);
switch (action.type) {
case 'progress':
if (invite.vault.itemCount === 0) break;
yield put(requestProgress(request.id, action.value));
break;
case 'done':
yield put(inviteAcceptSuccess(request.id, payload.inviteToken, share, action.result));
break;
case 'error':
throw action.error;
}
}
} catch (err) {
yield put(inviteAcceptFailure(request.id, err));
} finally {
yield put(startEventPolling());
}
}
export default function* watcher() {
yield takeEvery(inviteAcceptIntent.match, acceptInviteWorker);
}
| 8,023
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/invites/invite-create.saga.ts
|
import { put, select, takeEvery } from 'redux-saga/effects';
import { getPrimaryPublicKeyForEmail } from '@proton/pass/lib/auth/address';
import { createInvite, createNewUserInvite } from '@proton/pass/lib/invites/invite.requests';
import { moveItem } from '@proton/pass/lib/items/item.requests';
import { createVault } from '@proton/pass/lib/vaults/vault.requests';
import { inviteCreationFailure, inviteCreationIntent, inviteCreationSuccess } from '@proton/pass/store/actions';
import { selectFeatureFlag, selectItemByShareIdAndId } from '@proton/pass/store/selectors';
import type { ItemRevision, Maybe, Share, ShareType } from '@proton/pass/types';
import { PassFeature } from '@proton/pass/types/api/features';
/* Depending on the result of the public key for the invited email,
* adapt the invite creation process */
function* createInviteWorker({ payload, meta: { request } }: ReturnType<typeof inviteCreationIntent>) {
try {
const allowNewUser: boolean = yield select(selectFeatureFlag(PassFeature.PassSharingNewUsers));
const invitedPublicKey: Maybe<string> = yield getPrimaryPublicKeyForEmail(payload.email);
if (!invitedPublicKey && !allowNewUser) throw new Error();
if (payload.withVaultCreation) {
const { name, description, icon, color, item, ...inviteCreate } = payload;
const itemToMove: Maybe<ItemRevision> = yield select(selectItemByShareIdAndId(item.shareId, item.itemId));
if (itemToMove === undefined) throw new Error();
const vaultContent = { name, description, display: { icon, color } };
const createdShare: Share<ShareType.Vault> = yield createVault({ content: vaultContent });
const movedItem: ItemRevision = yield moveItem(itemToMove, item.shareId, createdShare.shareId);
yield invitedPublicKey
? createInvite({ ...inviteCreate, shareId: createdShare.shareId, invitedPublicKey })
: createNewUserInvite({ ...inviteCreate, shareId: createdShare.shareId });
yield put(
inviteCreationSuccess(request.id, {
item,
movedItem,
share: createdShare,
shareId: createdShare.shareId,
withVaultCreation: true,
})
);
return;
}
yield invitedPublicKey ? createInvite({ ...payload, invitedPublicKey }) : createNewUserInvite(payload);
yield put(inviteCreationSuccess(request.id, { withVaultCreation: false, shareId: payload.shareId }));
} catch (err) {
yield put(inviteCreationFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(inviteCreationIntent.match, createInviteWorker);
}
| 8,024
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/invites/invite-reject.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { rejectInvite } from '@proton/pass/lib/invites/invite.requests';
import { inviteRejectFailure, inviteRejectIntent, inviteRejectSuccess } from '@proton/pass/store/actions';
function* rejectInviteWorker({ payload, meta: { request } }: ReturnType<typeof inviteRejectIntent>) {
try {
yield rejectInvite(payload);
yield put(inviteRejectSuccess(request.id, payload.inviteToken));
} catch (err) {
yield put(inviteRejectFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(inviteRejectIntent.match, rejectInviteWorker);
}
| 8,025
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/invites/invite-remove.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { removeInvite } from '@proton/pass/lib/invites/invite.requests';
import { inviteRemoveFailure, inviteRemoveIntent, inviteRemoveSuccess } from '@proton/pass/store/actions';
function* removeInviteWorker({ payload, meta: { request } }: ReturnType<typeof inviteRemoveIntent>) {
try {
yield removeInvite(payload);
yield put(inviteRemoveSuccess(request.id, payload.shareId, payload.inviteId));
} catch (err) {
yield put(inviteRemoveFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(inviteRemoveIntent.match, removeInviteWorker);
}
| 8,026
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/invites/invite-resend.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { resendInvite } from '@proton/pass/lib/invites/invite.requests';
import { inviteResendFailure, inviteResendIntent, inviteResendSuccess } from '@proton/pass/store/actions';
function* resendInviteWorker({ payload, meta: { request } }: ReturnType<typeof inviteResendIntent>) {
try {
yield resendInvite(payload);
yield put(inviteResendSuccess(request.id, payload.shareId, payload.inviteId));
} catch (err) {
yield put(inviteResendFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(inviteResendIntent.match, resendInviteWorker);
}
| 8,027
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/invites/new-user-invite-promote.saga.ts
|
import { put, select, takeEvery } from 'redux-saga/effects';
import { getPrimaryPublicKeyForEmail } from '@proton/pass/lib/auth/address';
import type { InviteData } from '@proton/pass/lib/invites/invite.requests';
import { loadInvites, promoteInvite } from '@proton/pass/lib/invites/invite.requests';
import {
newUserInvitePromoteFailure,
newUserInvitePromoteIntent,
newUserInvitePromoteSuccess,
} from '@proton/pass/store/actions';
import type { ShareItem } from '@proton/pass/store/reducers';
import { selectShareOrThrow } from '@proton/pass/store/selectors';
import type { ShareType } from '@proton/pass/types';
import { type Maybe } from '@proton/pass/types';
function* promoteInviteWorker({ payload, meta: { request } }: ReturnType<typeof newUserInvitePromoteIntent>) {
try {
const { newUserInviteId, shareId } = payload;
const share: ShareItem<ShareType.Vault> = yield select(selectShareOrThrow(shareId));
const newUserInvite = (share.newUserInvites ?? []).find((invite) => newUserInviteId === invite.newUserInviteId);
if (!newUserInvite) throw new Error();
const invitedPublicKey: Maybe<string> = yield getPrimaryPublicKeyForEmail(newUserInvite.invitedEmail);
if (!invitedPublicKey) throw new Error();
yield promoteInvite({ invitedPublicKey, newUserInviteId, shareId });
const invites: InviteData = yield loadInvites(shareId);
yield put(newUserInvitePromoteSuccess(request.id, shareId, invites));
} catch (err) {
yield put(newUserInvitePromoteFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(newUserInvitePromoteIntent.match, promoteInviteWorker);
}
| 8,028
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/invites/new-user-invite-remove.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { removeNewUserInvite } from '@proton/pass/lib/invites/invite.requests';
import {
newUserInviteRemoveFailure,
newUserInviteRemoveIntent,
newUserInviteRemoveSuccess,
} from '@proton/pass/store/actions';
function* removeInviteWorker({ payload, meta: { request } }: ReturnType<typeof newUserInviteRemoveIntent>) {
try {
yield removeNewUserInvite(payload);
yield put(newUserInviteRemoveSuccess(request.id, payload.shareId, payload.newUserInviteId));
} catch (err) {
yield put(newUserInviteRemoveFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(newUserInviteRemoveIntent.match, removeInviteWorker);
}
| 8,029
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/items/item-autofill.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { parseItemRevision } from '@proton/pass/lib/items/item.parser';
import { updateItemLastUseTime } from '@proton/pass/lib/items/item.requests';
import { itemAutofilled, itemEditSync } from '@proton/pass/store/actions';
import type { ItemRevision, ItemRevisionContentsResponse } from '@proton/pass/types';
import { logId, logger } from '@proton/pass/utils/logger';
function* itemAutofilledWorker({ payload: { shareId, itemId } }: ReturnType<typeof itemAutofilled>) {
try {
logger.info(`[Saga::Item] used item ${logId(itemId)} on share ${logId(shareId)}`);
const encryptedItem: ItemRevisionContentsResponse = yield updateItemLastUseTime(shareId, itemId);
const item: ItemRevision = yield parseItemRevision(shareId, encryptedItem);
yield put(itemEditSync({ shareId, itemId, item }));
} catch (e) {
logger.warn(`[Saga::Item] lastUseTime update failed for item ${logId(itemId)} on share ${logId(shareId)}`, e);
}
}
export default function* watcher() {
yield takeEvery(itemAutofilled.match, itemAutofilledWorker);
}
| 8,030
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/items/item-creation.saga.ts
|
import type { AnyAction } from 'redux';
import { all, put, takeEvery } from 'redux-saga/effects';
import { parseItemRevision } from '@proton/pass/lib/items/item.parser';
import { createAlias, createItem, createItemWithAlias } from '@proton/pass/lib/items/item.requests';
import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event';
import {
itemCreationFailure,
itemCreationIntent,
itemCreationSuccess,
requestInvalidate,
} from '@proton/pass/store/actions';
import { aliasOptionsRequest } from '@proton/pass/store/actions/requests';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { ItemRevision, ItemRevisionContentsResponse } from '@proton/pass/types';
import { TelemetryEventName } from '@proton/pass/types/data/telemetry';
type ItemCreationAction = ReturnType<typeof itemCreationIntent>;
type ItemWithAliasCreationAction = ItemCreationAction & { payload: { type: 'login'; extraData: { withAlias: true } } };
const singleItemCreation = (action: AnyAction): action is ItemCreationAction =>
itemCreationIntent.match(action) && (action.payload.type === 'login' ? !action.payload.extraData.withAlias : true);
const withAliasItemCreation = (action: AnyAction): action is ItemWithAliasCreationAction =>
itemCreationIntent.match(action) && action.payload.type === 'login' && action.payload.extraData.withAlias;
function* singleItemCreationWorker({ onItemsChange, getTelemetry }: WorkerRootSagaOptions, action: ItemCreationAction) {
const {
payload: createIntent,
meta: { callback: onItemCreationIntentProcessed },
} = action;
const { shareId, optimisticId } = createIntent;
const isAlias = createIntent.type === 'alias';
const telemetry = getTelemetry();
try {
const encryptedItem: ItemRevisionContentsResponse = yield isAlias
? createAlias(createIntent)
: createItem(createIntent);
const item: ItemRevision = yield parseItemRevision(shareId, encryptedItem);
const itemCreationSuccessAction = itemCreationSuccess({ optimisticId, shareId, item });
yield put(itemCreationSuccessAction);
yield isAlias && put(requestInvalidate(aliasOptionsRequest(shareId))); /* reset alias options */
void telemetry?.pushEvent(createTelemetryEvent(TelemetryEventName.ItemCreation, {}, { type: item.data.type }));
if (item.data.type === 'login' && item.data.content.totpUri) {
void telemetry?.pushEvent(createTelemetryEvent(TelemetryEventName.TwoFACreation, {}, {}));
}
onItemCreationIntentProcessed?.(itemCreationSuccessAction);
onItemsChange?.();
} catch (e) {
const itemCreationfailureAction = itemCreationFailure({ optimisticId, shareId }, e);
yield put(itemCreationfailureAction);
onItemCreationIntentProcessed?.(itemCreationfailureAction);
}
}
function* withAliasCreationWorker(
{ onItemsChange, getTelemetry }: WorkerRootSagaOptions,
{ payload: createIntent }: ItemWithAliasCreationAction
) {
const { shareId, optimisticId } = createIntent;
const telemetry = getTelemetry();
try {
const [encryptedLoginItem, encryptedAliasItem]: ItemRevisionContentsResponse[] =
yield createItemWithAlias(createIntent);
const loginItem: ItemRevision = yield parseItemRevision(shareId, encryptedLoginItem);
const aliasItem: ItemRevision = yield parseItemRevision(shareId, encryptedAliasItem);
yield put(itemCreationSuccess({ optimisticId, shareId, item: loginItem, alias: aliasItem }));
yield put(requestInvalidate(aliasOptionsRequest(shareId))); /* reset alias options */
void telemetry?.pushEvent(
createTelemetryEvent(TelemetryEventName.ItemCreation, {}, { type: loginItem.data.type })
);
void telemetry?.pushEvent(
createTelemetryEvent(TelemetryEventName.ItemCreation, {}, { type: aliasItem.data.type })
);
if (loginItem.data.type === 'login' && loginItem.data.content.totpUri) {
void telemetry?.pushEvent(createTelemetryEvent(TelemetryEventName.TwoFACreation, {}, {}));
}
onItemsChange?.();
} catch (e) {
const itemCreationfailureAction = itemCreationFailure({ optimisticId, shareId }, e);
yield put(itemCreationfailureAction);
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield all([
takeEvery(singleItemCreation, singleItemCreationWorker, options),
takeEvery(withAliasItemCreation, withAliasCreationWorker, options),
]);
}
| 8,031
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/items/item-delete.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { api } from '@proton/pass/lib/api/api';
import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event';
import { itemDeleteFailure, itemDeleteIntent, itemDeleteSuccess } from '@proton/pass/store/actions';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import { TelemetryEventName } from '@proton/pass/types/data/telemetry';
function* deleteItem(
{ onItemsChange, getTelemetry }: WorkerRootSagaOptions,
{ payload }: ReturnType<typeof itemDeleteIntent>
) {
const telemetry = getTelemetry();
const { item, shareId } = payload;
try {
yield api({
url: `pass/v1/share/${payload.shareId}/item`,
method: 'delete',
data: {
Items: [
{
ItemID: item.itemId,
Revision: item.revision,
},
],
},
});
void telemetry?.pushEvent(createTelemetryEvent(TelemetryEventName.ItemDeletion, {}, { type: item.data.type }));
yield put(itemDeleteSuccess({ itemId: item.itemId, shareId }));
onItemsChange?.();
} catch (e) {
yield put(itemDeleteFailure({ itemId: item.itemId, shareId }, e));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(itemDeleteIntent.match, deleteItem, options);
}
| 8,032
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/items/item-edit.saga.ts
|
import { call, put, select, takeEvery } from 'redux-saga/effects';
import { api } from '@proton/pass/lib/api/api';
import { parseItemRevision } from '@proton/pass/lib/items/item.parser';
import { editItem } from '@proton/pass/lib/items/item.requests';
import { createTelemetryEvent } from '@proton/pass/lib/telemetry/event';
import { aliasDetailsSync, itemEditFailure, itemEditIntent, itemEditSuccess } from '@proton/pass/store/actions';
import type { AliasState } from '@proton/pass/store/reducers';
import { selectAliasDetails, selectAliasOptions, selectItemByShareIdAndId } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { ItemEditIntent, ItemRevision, ItemRevisionContentsResponse } from '@proton/pass/types';
import { TelemetryEventName } from '@proton/pass/types/data/telemetry';
import { isEqual } from '@proton/pass/utils/set/is-equal';
function* editMailboxesWorker(aliasEditIntent: ItemEditIntent<'alias'>) {
const { itemId, shareId } = aliasEditIntent;
const item: ItemRevision<'alias'> = yield select(selectItemByShareIdAndId(shareId, itemId));
const mailboxesForAlias: string[] = yield select(selectAliasDetails(item.aliasEmail!));
const aliasOptions: AliasState['aliasOptions'] = yield select(selectAliasOptions);
const currentMailboxIds = new Set(
mailboxesForAlias
.map((mailbox) => aliasOptions?.mailboxes.find(({ email }) => email === mailbox)?.id)
.filter(Boolean) as number[]
);
const nextMailboxIds = new Set(aliasEditIntent.extraData.mailboxes.map(({ id }) => id));
/* only update the mailboxes if there is a change */
if (!isEqual(currentMailboxIds, nextMailboxIds)) {
yield api({
url: `pass/v1/share/${shareId}/alias/${itemId}/mailbox`,
method: 'post',
data: {
MailboxIDs: Array.from(nextMailboxIds.values()),
},
});
yield put(
aliasDetailsSync({
aliasEmail: item.aliasEmail!,
mailboxes: aliasEditIntent.extraData.mailboxes,
})
);
}
}
function* itemEditWorker(
{ onItemsChange, getTelemetry }: WorkerRootSagaOptions,
{ payload: editIntent, meta: { callback: onItemEditIntentProcessed } }: ReturnType<typeof itemEditIntent>
) {
const { itemId, shareId, lastRevision } = editIntent;
const telemetry = getTelemetry();
try {
if (editIntent.type === 'alias' && editIntent.extraData.aliasOwner) yield call(editMailboxesWorker, editIntent);
const encryptedItem: ItemRevisionContentsResponse = yield editItem(editIntent, lastRevision);
const item: ItemRevision = yield parseItemRevision(shareId, encryptedItem);
const itemEditSuccessAction = itemEditSuccess({ item, itemId, shareId });
yield put(itemEditSuccessAction);
void telemetry?.pushEvent(createTelemetryEvent(TelemetryEventName.ItemUpdate, {}, { type: item.data.type }));
if (item.data.type === 'login' && editIntent.type === 'login') {
const prevTotp = editIntent.content.totpUri;
const nextTotp = item.data.content.totpUri;
if (nextTotp && prevTotp !== nextTotp) {
void telemetry?.pushEvent(createTelemetryEvent(TelemetryEventName.TwoFAUpdate, {}, {}));
}
}
onItemEditIntentProcessed?.(itemEditSuccessAction);
onItemsChange?.();
} catch (e) {
const itemEditFailureAction = itemEditFailure({ itemId, shareId }, e);
yield put(itemEditFailureAction);
onItemEditIntentProcessed?.(itemEditFailureAction);
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(itemEditIntent.match, itemEditWorker, options);
}
| 8,033
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/items/item-move.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { moveItem } from '@proton/pass/lib/items/item.requests';
import { itemMoveFailure, itemMoveIntent, itemMoveSuccess } from '@proton/pass/store/actions';
import type { ItemRevision } from '@proton/pass/types';
function* itemCreationWorker({ payload }: ReturnType<typeof itemMoveIntent>) {
const { item: itemToMove, optimisticId, shareId } = payload;
try {
const item: ItemRevision = yield moveItem(itemToMove, itemToMove.shareId, shareId);
yield put(itemMoveSuccess({ item, optimisticId, shareId }));
} catch (e: unknown) {
yield put(itemMoveFailure({ optimisticId, shareId, item: itemToMove }, e));
}
}
export default function* watcher() {
yield takeEvery(itemMoveIntent.match, itemCreationWorker);
}
| 8,034
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/items/item-restore.saga.ts
|
import { put, takeLatest } from 'redux-saga/effects';
import { restoreItems } from '@proton/pass/lib/items/item.requests';
import { itemRestoreFailure, itemRestoreIntent, itemRestoreSuccess } from '@proton/pass/store/actions';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
function* restoreItem(
{ onItemsChange }: WorkerRootSagaOptions,
{ payload, meta }: ReturnType<typeof itemRestoreIntent>
) {
const { item, shareId } = payload;
const { itemId } = item;
const { callback: onItemRestoreProcessed } = meta;
try {
yield restoreItems([item]);
const itemRestoreSuccessAction = itemRestoreSuccess({ itemId, shareId });
yield put(itemRestoreSuccessAction);
onItemRestoreProcessed?.(itemRestoreSuccessAction);
onItemsChange?.();
} catch (e) {
const itemRestoreFailureAction = itemRestoreFailure({ itemId, shareId }, e);
yield put(itemRestoreFailureAction);
onItemRestoreProcessed?.(itemRestoreFailureAction);
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLatest(itemRestoreIntent, restoreItem, options);
}
| 8,035
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/items/item-trash.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { c } from 'ttag';
import { trashItems } from '@proton/pass/lib/items/item.requests';
import { getItemActionId } from '@proton/pass/lib/items/item.utils';
import { itemTrashFailure, itemTrashIntent, itemTrashSuccess, notification } from '@proton/pass/store/actions';
import type { WithSenderAction } from '@proton/pass/store/actions/with-receiver';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
function* trashItemWorker(
{ onItemsChange }: WorkerRootSagaOptions,
{ payload, meta }: WithSenderAction<ReturnType<typeof itemTrashIntent>>
) {
const { item, shareId } = payload;
const { callback: onItemTrashProcessed } = meta;
try {
yield trashItems([item]);
const itemTrashSuccessAction = itemTrashSuccess({ itemId: item.itemId, shareId });
yield put(itemTrashSuccessAction);
/* alias specific notification on trash :
* this will override the default trash success
* notification by deduplicating a new notification
* with the same key */
yield item.data.type === 'alias' &&
put(
notification({
type: 'info',
key: getItemActionId(payload),
endpoint: meta.sender?.endpoint,
text: c('Info')
.t`Alias "${item.aliasEmail}" moved to trash - it will stop forwarding emails to your mailbox`,
})
);
onItemTrashProcessed?.(itemTrashSuccessAction);
onItemsChange?.();
} catch (e) {
const itemTrashFailureAction = itemTrashFailure({ itemId: item.itemId, shareId }, e);
yield put(itemTrashFailureAction);
onItemTrashProcessed?.(itemTrashFailureAction);
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(itemTrashIntent.match, trashItemWorker, options);
}
| 8,036
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/shares/share-access-options.saga.ts
|
import { put, select, takeEvery } from 'redux-saga/effects';
import { loadInvites } from '@proton/pass/lib/invites/invite.requests';
import { isShareManageable } from '@proton/pass/lib/shares/share.predicates';
import { loadShareMembers } from '@proton/pass/lib/shares/share.requests';
import {
getShareAccessOptionsFailure,
getShareAccessOptionsIntent,
getShareAccessOptionsSuccess,
} from '@proton/pass/store/actions';
import type { ShareItem } from '@proton/pass/store/reducers';
import { selectShareOrThrow } from '@proton/pass/store/selectors';
import type { ShareAccessOptions } from '@proton/pass/types/data/shares.dto';
/**
* Only the owner or the manager of a share can manage the invites.
* Only request the members if the share is actually shared.
*/
function* shareAccessOptionsWorker({ payload, meta: { request } }: ReturnType<typeof getShareAccessOptionsIntent>) {
try {
const { shareId } = payload;
const share: ShareItem = yield select(selectShareOrThrow(shareId));
const accessOptions: ShareAccessOptions = {
shareId,
members: share.shared ? yield loadShareMembers(shareId) : [],
...(isShareManageable(share) ? yield loadInvites(shareId) : {}),
};
yield put(getShareAccessOptionsSuccess(request.id, accessOptions));
} catch (err) {
yield put(getShareAccessOptionsFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(getShareAccessOptionsIntent.match, shareAccessOptionsWorker);
}
| 8,037
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/shares/share-edit-role.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { editMemberAccess } from '@proton/pass/lib/shares/share.requests';
import {
shareEditMemberAccessFailure,
shareEditMemberAccessIntent,
shareEditMemberAccessSuccess,
} from '@proton/pass/store/actions';
function* resendInviteWorker({ payload, meta: { request } }: ReturnType<typeof shareEditMemberAccessIntent>) {
try {
yield editMemberAccess(payload);
yield put(shareEditMemberAccessSuccess(request.id, payload.shareId, payload.userShareId, payload.shareRoleId));
} catch (err) {
yield put(shareEditMemberAccessFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(shareEditMemberAccessIntent.match, resendInviteWorker);
}
| 8,038
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/shares/share-leave.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { PassCrypto } from '@proton/pass/lib/crypto/pass-crypto';
import { deleteShare } from '@proton/pass/lib/shares/share.requests';
import { shareLeaveFailure, shareLeaveIntent, shareLeaveSuccess } from '@proton/pass/store/actions';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
function* shareLeaveWorker(
{ onShareEventDisabled, onItemsChange }: WorkerRootSagaOptions,
{ payload, meta: { request } }: ReturnType<typeof shareLeaveIntent>
) {
try {
const { shareId } = payload;
yield deleteShare(shareId);
PassCrypto.removeShare(shareId);
onShareEventDisabled?.(shareId);
onItemsChange?.();
yield put(shareLeaveSuccess(request.id, payload.shareId));
} catch (err) {
yield put(shareLeaveFailure(request.id, err));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(shareLeaveIntent.match, shareLeaveWorker, options);
}
| 8,039
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/shares/share-remove-member.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { removeUserAccess } from '@proton/pass/lib/shares/share.requests';
import {
shareRemoveMemberAccessFailure,
shareRemoveMemberAccessIntent,
shareRemoveMemberAccessSuccess,
} from '@proton/pass/store/actions';
function* removeUserAccessWorker({ payload, meta: { request } }: ReturnType<typeof shareRemoveMemberAccessIntent>) {
try {
yield removeUserAccess(payload);
yield put(shareRemoveMemberAccessSuccess(request.id, payload.shareId, payload.userShareId));
} catch (err) {
yield put(shareRemoveMemberAccessFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(shareRemoveMemberAccessIntent.match, removeUserAccessWorker);
}
| 8,040
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/user/feature-flags.saga.ts
|
import { put, select, takeEvery } from 'redux-saga/effects';
import { getFeatureFlags } from '@proton/pass/lib/user/user.requests';
import { getUserFeaturesFailure, getUserFeaturesIntent, getUserFeaturesSuccess } from '@proton/pass/store/actions';
import type { FeatureFlagState } from '@proton/pass/store/reducers';
import { selectFeatureFlags } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import { SessionLockStatus } from '@proton/pass/types';
import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual';
/* Try to sync the user feature flags on each wakeup success :
/* `getUserFeatures` will only request pass feature flags from the api
* if the `requestedAt` timestamp is more than a day old */
function* syncFeatures(
{ getAuthStore, onFeatureFlagsUpdate }: WorkerRootSagaOptions,
{ meta }: ReturnType<typeof getUserFeaturesIntent>
) {
try {
const loggedIn = getAuthStore().hasSession();
const locked = getAuthStore().getLockStatus() === SessionLockStatus.LOCKED;
if (!loggedIn || locked) throw new Error('Cannot fetch user features');
const current: FeatureFlagState = yield select(selectFeatureFlags);
const incoming: FeatureFlagState = yield getFeatureFlags();
yield put(getUserFeaturesSuccess(meta.request.id, incoming));
if (!isDeepEqual(current, incoming)) onFeatureFlagsUpdate?.(incoming);
} catch (error: unknown) {
yield put(getUserFeaturesFailure(meta.request.id, error));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(getUserFeaturesIntent.match, syncFeatures, options);
}
| 8,041
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/user/user-access.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { getUserAccess } from '@proton/pass/lib/user/user.requests';
import { getUserAccessFailure, getUserAccessIntent, getUserAccessSuccess } from '@proton/pass/store/actions';
import type { SafeUserAccessState } from '@proton/pass/store/reducers';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import { SessionLockStatus } from '@proton/pass/types';
function* syncPlan({ getAuthStore }: WorkerRootSagaOptions, { meta }: ReturnType<typeof getUserAccessIntent>) {
try {
const loggedIn = getAuthStore().hasSession();
const locked = getAuthStore().getLockStatus() === SessionLockStatus.LOCKED;
if (!loggedIn || locked) throw new Error('Cannot fetch user plan');
const access: SafeUserAccessState = yield getUserAccess();
yield put(getUserAccessSuccess(meta.request.id, access));
} catch (error) {
yield put(getUserAccessFailure(meta.request.id, error));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(getUserAccessIntent.match, syncPlan, options);
}
| 8,042
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/vaults/trash-empty.saga.ts
|
import { put, select, takeLeading } from 'redux-saga/effects';
import { deleteItems } from '@proton/pass/lib/items/item.requests';
import { emptyTrashFailure, emptyTrashIntent, emptyTrashSuccess } from '@proton/pass/store/actions';
import { selectAllTrashedItems } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { ItemRevision } from '@proton/pass/types';
function* emptyTrashWorker({ onItemsChange }: WorkerRootSagaOptions, { meta }: ReturnType<typeof emptyTrashIntent>) {
try {
const trashedItems: ItemRevision[] = yield select(selectAllTrashedItems);
yield deleteItems(trashedItems);
yield put(emptyTrashSuccess(meta.request.id));
onItemsChange?.();
} catch (error: unknown) {
yield put(emptyTrashFailure(meta.request.id, error));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLeading(emptyTrashIntent.match, emptyTrashWorker, options);
}
| 8,043
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/vaults/trash-restore.saga.ts
|
import { put, select, takeLeading } from 'redux-saga/effects';
import { restoreItems } from '@proton/pass/lib/items/item.requests';
import { restoreTrashFailure, restoreTrashIntent, restoreTrashSuccess } from '@proton/pass/store/actions';
import { selectAllTrashedItems } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { ItemRevision } from '@proton/pass/types';
function* restoreTrash({ onItemsChange }: WorkerRootSagaOptions, { meta }: ReturnType<typeof restoreTrashIntent>) {
try {
const trashedItems: ItemRevision[] = yield select(selectAllTrashedItems);
yield restoreItems(trashedItems);
yield put(restoreTrashSuccess(meta.request.id));
onItemsChange?.();
} catch (e) {
yield put(restoreTrashFailure(meta.request.id, e));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeLeading(restoreTrashIntent.match, restoreTrash, options);
}
| 8,044
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/vaults/vault-creation.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { createVault } from '@proton/pass/lib/vaults/vault.requests';
import { vaultCreationFailure, vaultCreationIntent, vaultCreationSuccess } from '@proton/pass/store/actions';
import type { ShareType } from '@proton/pass/types';
import { type Share } from '@proton/pass/types';
function* createVaultWorker({ payload, meta }: ReturnType<typeof vaultCreationIntent>) {
const { callback: onCreateVaultProcessed } = meta;
try {
const share: Share<ShareType.Vault> = yield createVault({ content: payload.content });
const vaultCreationSuccessAction = vaultCreationSuccess(meta.request.id, { share });
yield put(vaultCreationSuccessAction);
onCreateVaultProcessed?.(vaultCreationSuccessAction);
} catch (e) {
const vaultCreationFailureAction = vaultCreationFailure(meta.request.id, payload, e);
yield put(vaultCreationFailureAction);
onCreateVaultProcessed?.(vaultCreationFailureAction);
}
}
export default function* watcher() {
yield takeEvery(vaultCreationIntent.match, createVaultWorker);
}
| 8,045
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/vaults/vault-delete.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { PassCrypto } from '@proton/pass/lib/crypto/pass-crypto';
import { deleteVault } from '@proton/pass/lib/vaults/vault.requests';
import { vaultDeleteFailure, vaultDeleteIntent, vaultDeleteSuccess } from '@proton/pass/store/actions';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
function* deleteVaultWorker(
{ onItemsChange }: WorkerRootSagaOptions,
{ payload: { shareId, content }, meta }: ReturnType<typeof vaultDeleteIntent>
): Generator {
try {
yield deleteVault(shareId);
PassCrypto.removeShare(shareId);
yield put(vaultDeleteSuccess(meta.request.id, { shareId, content }));
onItemsChange?.();
} catch (e) {
yield put(vaultDeleteFailure(meta.request.id, { shareId, content }, e));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(vaultDeleteIntent.match, deleteVaultWorker, options);
}
| 8,046
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/vaults/vault-edit.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { editVault } from '@proton/pass/lib/vaults/vault.requests';
import { vaultEditFailure, vaultEditIntent, vaultEditSuccess } from '@proton/pass/store/actions';
import type { ShareType } from '@proton/pass/types';
import { type Share } from '@proton/pass/types';
function* editVaultWorker({ payload, meta }: ReturnType<typeof vaultEditIntent>) {
try {
const share: Share<ShareType.Vault> = yield editVault(payload.shareId, payload.content);
yield put(vaultEditSuccess(meta.request.id, { share }));
} catch (e) {
yield put(vaultEditFailure(meta.request.id, payload, e));
}
}
export default function* watcher() {
yield takeEvery(vaultEditIntent.match, editVaultWorker);
}
| 8,047
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/vaults/vault-move-all-items.saga.ts
|
import { put, select, takeEvery } from 'redux-saga/effects';
import { moveItems } from '@proton/pass/lib/items/item.requests';
import {
vaultMoveAllItemsFailure,
vaultMoveAllItemsIntent,
vaultMoveAllItemsSuccess,
} from '@proton/pass/store/actions';
import { selectItemsByShareId } from '@proton/pass/store/selectors';
import type { WorkerRootSagaOptions } from '@proton/pass/store/types';
import type { ItemRevision } from '@proton/pass/types';
function* moveAllItemsWorker(
{ onItemsChange }: WorkerRootSagaOptions,
{ payload: { shareId, content, destinationShareId }, meta }: ReturnType<typeof vaultMoveAllItemsIntent>
) {
try {
const items: ItemRevision[] = yield select(selectItemsByShareId(shareId));
const movedItems = (yield moveItems(items, destinationShareId)) as ItemRevision[];
yield put(vaultMoveAllItemsSuccess(meta.request.id, { shareId, destinationShareId, content, movedItems }));
onItemsChange?.();
} catch (e) {
yield put(vaultMoveAllItemsFailure(meta.request.id, { shareId, content }, e));
}
}
export default function* watcher(options: WorkerRootSagaOptions) {
yield takeEvery(vaultMoveAllItemsIntent.match, moveAllItemsWorker, options);
}
| 8,048
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/sagas/vaults/vault-transfer-owner.saga.ts
|
import { put, takeEvery } from 'redux-saga/effects';
import { vaultTransferOwner } from '@proton/pass/lib/vaults/vault.requests';
import {
vaultTransferOwnerIntent,
vaultTransferOwnershipFailure,
vaultTransferOwnershipSuccess,
} from '@proton/pass/store/actions';
function* resendInviteWorker({ payload, meta: { request } }: ReturnType<typeof vaultTransferOwnerIntent>) {
try {
yield vaultTransferOwner(payload);
yield put(vaultTransferOwnershipSuccess(request.id, payload.shareId, payload.userShareId));
} catch (err) {
yield put(vaultTransferOwnershipFailure(request.id, err));
}
}
export default function* watcher() {
yield takeEvery(vaultTransferOwnerIntent.match, resendInviteWorker);
}
| 8,049
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/alias.ts
|
import { createSelector } from '@reduxjs/toolkit';
import type { AliasState } from '@proton/pass/store/reducers';
import type { State } from '@proton/pass/store/types';
import type { Maybe } from '@proton/pass/types';
import type { AliasMailbox } from '@proton/pass/types/data/alias';
import { selectItemsByType } from './items';
export const selectAliasOptions = ({ alias }: State): AliasState['aliasOptions'] => alias.aliasOptions;
export const selectAliasDetails = (aliasEmail: string) =>
createSelector([({ alias }: State) => alias], (alias): Maybe<AliasMailbox[]> => alias.aliasDetails?.[aliasEmail]);
export const selectAliasByAliasEmail = (aliasEmail: string) =>
createSelector([selectItemsByType('alias'), () => aliasEmail], (aliasItems, aliasEmail) =>
aliasItems.find((item) => item.aliasEmail! === aliasEmail)
);
| 8,050
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/errors.ts
|
export class SelectorError extends Error {}
| 8,051
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/import.ts
|
import type { ImportState } from '@proton/pass/store/reducers';
import type { State } from '@proton/pass/store/types';
export const selectLatestImport = (state: State): ImportState => state.import;
| 8,052
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/index.ts
|
export * from './alias';
export * from './import';
export * from './items';
export * from './limits';
export * from './popup';
export * from './pw-history';
export * from './request';
export * from './settings';
export * from './shares';
export * from './user';
| 8,053
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/invites.ts
|
import { createSelector } from '@reduxjs/toolkit';
import type { InviteState } from '@proton/pass/store/reducers';
import type { State } from '@proton/pass/store/types';
import type { Invite, Maybe } from '@proton/pass/types';
import { first } from '@proton/pass/utils/array/first';
import { sortOn } from '@proton/pass/utils/fp/sort';
export const selectInvites = (state: State): InviteState => state.invites;
export const selectInviteByToken =
(token: string) =>
(state: State): Maybe<Invite> =>
state.invites[token];
export const selectMostRecentInvite = createSelector([selectInvites], (invites) =>
first(Object.values(invites).sort(sortOn('createTime', 'DESC')))
);
| 8,054
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/items.spec.ts
|
import type { State } from '@proton/pass/store/types';
import { ItemState } from '@proton/pass/types';
import { parseUrl } from '@proton/pass/utils/url/parser';
import { selectAutofillCandidates, selectItemsByDomain } from './items';
const withOptimistics = (item: {}) => ({ ...item, failed: expect.any(Boolean), optimistic: expect.any(Boolean) });
const stateMock = {
items: {
byShareId: {
share1: {
item1: {
/* item with secure protocol */
itemId: 'share1-item1',
state: ItemState.Active,
shareId: 'share1',
data: {
type: 'login',
content: { urls: ['https://proton.me', 'https://subdomain.proton.me'] },
},
},
item2: {
/* item with unsecure protocol */
itemId: 'share1-item2',
state: ItemState.Active,
shareId: 'share1',
data: {
type: 'login',
content: { urls: ['http://proton.me'] },
},
},
item3: {
/* item with private domain */
itemId: 'share1-item3',
state: ItemState.Active,
shareId: 'share1',
data: {
type: 'login',
content: { urls: ['https://github.io'] },
},
},
item4: {
/* item with private sub-domain */
itemId: 'share1-item4',
state: ItemState.Active,
shareId: 'share1',
data: {
type: 'login',
content: { urls: ['https://private.subdomain.github.io'] },
},
},
item5: {
/* item with another private sub-domain */
itemId: 'share1-item5',
state: ItemState.Active,
shareId: 'share1',
data: {
type: 'login',
content: { urls: ['https://othersubdomain.github.io'] },
},
},
},
share2: {
item1: {
/* trashed item with secure protocol */
itemId: 'share2-item1',
state: ItemState.Trashed,
shareId: 'share2',
data: {
type: 'login',
content: { urls: ['https://proton.me'] },
},
},
item2: {
/* active item with unsecure protocol */
itemId: 'share2-item2',
state: ItemState.Active,
shareId: 'share2',
data: {
type: 'login',
content: { urls: ['http://proton.me'] },
},
},
},
share3: {
item1: {
/* non http protocols & invalid urls */
itemId: 'share3-item1',
state: ItemState.Active,
shareId: 'share3',
data: {
type: 'login',
content: { urls: ['ftp://proton.me', 'htp::://invalid'] },
},
},
item2: {
/* type note */
itemId: 'share3-item2',
state: ItemState.Active,
shareId: 'share3',
data: {
type: 'note',
},
},
item3: {
/* type alias */
itemId: 'share3-item3',
state: ItemState.Active,
shareId: 'share3',
data: {
type: 'alias',
},
},
item4: {
/* active item with nested subdomain */
itemId: 'share3-item4',
state: ItemState.Active,
shareId: 'share3',
data: {
type: 'login',
content: { urls: ['https://sub.domain.google.com'] },
},
},
item5: {
/* active item with nested subdomain */
itemId: 'share3-item5',
state: ItemState.Active,
shareId: 'share3',
data: {
type: 'login',
content: { urls: ['https://my.sub.domain.google.com'] },
},
},
item6: {
/* active item with unsecure nested subdomain */
state: ItemState.Active,
itemId: 'share3-item6',
shareId: 'share3',
data: {
type: 'login',
content: { urls: ['http://google.com'] },
},
},
},
share4: {
/* empty share */
},
optimistic: { history: [], checkpoint: undefined },
},
},
} as unknown as State;
describe('item selectors', () => {
describe('selectItemsByURL', () => {
test('should return nothing if url is not valid or no match', () => {
expect(
selectItemsByDomain(null, {
protocolFilter: [],
isPrivate: false,
})(stateMock)
).toEqual([]);
expect(
selectItemsByDomain('', {
protocolFilter: [],
isPrivate: false,
})(stateMock)
).toEqual([]);
expect(
selectItemsByDomain('http::://invalid.com', {
protocolFilter: [],
isPrivate: false,
})(stateMock)
).toEqual([]);
});
test('should return nothing if no items match url', () => {
expect(
selectItemsByDomain('proton.ch', {
protocolFilter: [],
isPrivate: false,
})(stateMock)
).toEqual([]);
expect(
selectItemsByDomain('unknown.proton.me', {
protocolFilter: [],
isPrivate: false,
})(stateMock)
).toEqual([]);
expect(
selectItemsByDomain('proton.me/secret/path', {
protocolFilter: [],
isPrivate: false,
})(stateMock)
).toEqual([]);
});
test('should return only active items on direct match', () => {
const items = selectItemsByDomain('proton.me', {
protocolFilter: [],
isPrivate: false,
})(stateMock);
expect(items.length).toEqual(4);
expect(items[0]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item1));
expect(items[1]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item2));
expect(items[2]).toEqual(withOptimistics(stateMock.items.byShareId.share2.item2));
expect(items[3]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item1));
});
test('should return only active items on direct match', () => {
const items = selectItemsByDomain('proton.me', {
protocolFilter: [],
isPrivate: false,
})(stateMock);
expect(items.length).toEqual(4);
expect(items[0]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item1));
expect(items[1]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item2));
expect(items[2]).toEqual(withOptimistics(stateMock.items.byShareId.share2.item2));
expect(items[3]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item1));
});
test('should return only share matches if shareId filter', () => {
const itemsShare1 = selectItemsByDomain('proton.me', {
protocolFilter: [],
isPrivate: false,
shareIds: ['share1'],
})(stateMock);
expect(itemsShare1.length).toEqual(2);
expect(itemsShare1[0]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item1));
expect(itemsShare1[1]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item2));
const itemsShare2 = selectItemsByDomain('proton.me', {
protocolFilter: [],
isPrivate: false,
shareIds: ['share2'],
})(stateMock);
expect(itemsShare2.length).toEqual(1);
expect(itemsShare2[0]).toEqual(withOptimistics(stateMock.items.byShareId.share2.item2));
const itemsShare3 = selectItemsByDomain('proton.me', {
protocolFilter: [],
isPrivate: false,
shareIds: ['share3'],
})(stateMock);
expect(itemsShare3.length).toEqual(1);
expect(itemsShare3[0]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item1));
const itemsShare4 = selectItemsByDomain('proton.me', {
protocolFilter: [],
isPrivate: false,
shareIds: ['share4'],
})(stateMock);
expect(itemsShare4.length).toEqual(0);
});
test('should use protocol filter if any', () => {
const itemsHTTPS = selectItemsByDomain('proton.me', {
protocolFilter: ['https:'],
isPrivate: false,
})(stateMock);
expect(itemsHTTPS.length).toEqual(1);
expect(itemsHTTPS[0]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item1));
const itemsHTTP = selectItemsByDomain('proton.me', {
protocolFilter: ['http:'],
isPrivate: false,
})(stateMock);
expect(itemsHTTP.length).toEqual(2);
expect(itemsHTTP[0]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item2));
expect(itemsHTTP[1]).toEqual(withOptimistics(stateMock.items.byShareId.share2.item2));
const itemsAny = selectItemsByDomain('proton.me', {
protocolFilter: [],
isPrivate: false,
})(stateMock);
expect(itemsAny.length).toEqual(4);
expect(itemsAny[0]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item1));
expect(itemsAny[1]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item2));
expect(itemsAny[2]).toEqual(withOptimistics(stateMock.items.byShareId.share2.item2));
expect(itemsAny[3]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item1));
const itemsFTP = selectItemsByDomain('proton.me', {
protocolFilter: ['ftp:'],
isPrivate: false,
})(stateMock);
expect(itemsFTP.length).toEqual(1);
expect(itemsFTP[0]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item1));
});
});
describe('selectAutofillCandidates', () => {
test('should return nothing if invalid url', () => {
expect(selectAutofillCandidates(parseUrl(''))(stateMock)).toEqual([]);
expect(selectAutofillCandidates({ ...parseUrl('https://a.b.c'), protocol: null })(stateMock)).toEqual([]);
});
test('should not pass a protocol filter if url is secure', () => {
const candidates = selectAutofillCandidates(parseUrl('https://google.com'))(stateMock);
expect(candidates.length).toEqual(3);
expect(candidates[0]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item6));
expect(candidates[1]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item4));
expect(candidates[2]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item5));
});
test('should pass a protocol filter if url is not secure `https:`', () => {
const candidates = selectAutofillCandidates(parseUrl('http://google.com'))(stateMock);
expect(candidates.length).toEqual(1);
expect(candidates[0]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item6));
});
test('should pass a protocol filter if url is not secure `https:`', () => {
const candidates = selectAutofillCandidates(parseUrl('http://google.com'))(stateMock);
expect(candidates.length).toEqual(1);
expect(candidates[0]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item6));
});
test('should return only matching protocols', () => {
const candidates = selectAutofillCandidates(parseUrl('ftp://proton.me'))(stateMock);
expect(candidates.length).toEqual(1);
expect(candidates[0]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item1));
});
test('if no direct public subdomain match, should sort top-level domains and other subdomain matches', () => {
const candidates = selectAutofillCandidates(parseUrl('https://account.google.com'))(stateMock);
expect(candidates.length).toEqual(3);
expect(candidates[0]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item6));
expect(candidates[1]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item4));
expect(candidates[2]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item5));
});
test('if public subdomain match, should push subdomain matches on top, then top-level domain, then other subdomains', () => {
const candidates = selectAutofillCandidates(parseUrl('https://my.sub.domain.google.com'))(stateMock);
expect(candidates.length).toEqual(3);
expect(candidates[0]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item5));
expect(candidates[1]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item6));
expect(candidates[2]).toEqual(withOptimistics(stateMock.items.byShareId.share3.item4));
});
test('if private top level domain, should match only top level domain', () => {
const candidates = selectAutofillCandidates(parseUrl('https://github.io'))(stateMock);
expect(candidates.length).toEqual(1);
expect(candidates[0]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item3));
});
test('if private sub domain, should match only specific subdomain', () => {
const candidates = selectAutofillCandidates(parseUrl('https://subdomain.github.io'))(stateMock);
expect(candidates.length).toEqual(1);
expect(candidates[0]).toEqual(withOptimistics(stateMock.items.byShareId.share1.item4));
});
});
});
| 8,055
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/items.ts
|
import { createSelector } from '@reduxjs/toolkit';
import { isLoginItem, isTrashed } from '@proton/pass/lib/items/item.predicates';
import {
filterItemsByShareId,
filterItemsByType,
flattenItemsByShareId,
sortItems,
} from '@proton/pass/lib/items/item.utils';
import { matchAny } from '@proton/pass/lib/search/match-any';
import { searchItems } from '@proton/pass/lib/search/match-items';
import { ItemUrlMatch, getItemPriorityForUrl } from '@proton/pass/lib/search/match-url';
import type {
SelectAutofillCandidatesOptions,
SelectAutosaveCandidatesOptions,
SelectItemsByDomainOptions,
SelectItemsOptions,
} from '@proton/pass/lib/search/types';
import type {
ItemRevision,
ItemRevisionWithOptimistic,
ItemType,
Maybe,
MaybeNull,
UniqueItem,
} from '@proton/pass/types';
import { prop } from '@proton/pass/utils/fp/lens';
import { pipe } from '@proton/pass/utils/fp/pipe';
import { invert } from '@proton/pass/utils/fp/predicates';
import { deobfuscate } from '@proton/pass/utils/obfuscate/xor';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { unwrapOptimisticState } from '../optimistic/utils/transformers';
import { withOptimisticItemsByShareId } from '../reducers/items';
import type { State } from '../types';
const { asIfNotFailed, asIfNotOptimistic } = withOptimisticItemsByShareId.selectors;
export const selectByShareId = (state: State) => state.items.byShareId;
export const selectByOptimisticIds = (state: State) => state.items.byOptimistcId;
export const selectItemDraft = (state: State) => state.popup.draft;
/** Give an itemId, returns wether it is optimistic by checking for
* presence in the `byOptimisticId` dictionary state */
export const selectResolvedOptimisticId = (optimisticId: string) =>
createSelector(selectByOptimisticIds, (optimisticIds) => optimisticId in optimisticIds);
export const selectByShareIdAsIfNotFailed = createSelector(selectByShareId, asIfNotFailed);
export const selectByShareIdAsIfNotOptimistic = createSelector(selectByShareId, asIfNotOptimistic);
export const selectItems = createSelector([selectByShareId], unwrapOptimisticState);
export const selectAllItems = createSelector(selectItems, flattenItemsByShareId);
export const selectAllTrashedItems = createSelector([selectAllItems], (items) => items.filter(isTrashed));
export const selectItemsByShareId = (shareId?: string) =>
createSelector([selectItems, () => shareId], (items, shareId): ItemRevision[] =>
flattenItemsByShareId(shareId && items[shareId] ? { shareId: items[shareId] } : items).filter(invert(isTrashed))
);
export const selectItemIdByOptimisticId =
(optimisticItemId?: string) =>
(state: State): Maybe<UniqueItem> =>
optimisticItemId ? selectByOptimisticIds(state)?.[optimisticItemId] : undefined;
export const selectItemByShareIdAndId = (shareId: string, itemId: string) =>
createSelector([selectItems, selectByOptimisticIds], (items, byOptimisticId): Maybe<ItemRevision> => {
const idFromOptimisticId = byOptimisticId[itemId]?.itemId;
const byItemId = items[shareId];
return idFromOptimisticId ? byItemId?.[idFromOptimisticId] : byItemId?.[itemId];
});
/** Unwraps the optimistic item state and hydrates the `failed` and
* `optimistic` properties of the returned `ItemRevisionWithOptimistic` */
const selectItemsWithOptimistic = createSelector(
[selectAllItems, selectByShareIdAsIfNotFailed, selectByShareIdAsIfNotOptimistic],
(items, withoutFailed, withoutOptimistic) =>
items.map(
(item): ItemRevisionWithOptimistic => ({
...item,
failed: withoutFailed[item.shareId]?.[item.itemId]?.revision !== item.revision,
optimistic: withoutOptimistic[item.shareId]?.[item.itemId]?.revision !== item.revision,
})
)
);
const selectSortedItemsByType = createSelector(
[
selectItemsWithOptimistic,
(_: State, { trashed }: SelectItemsOptions) => trashed ?? false,
(_: State, { shareId }: SelectItemsOptions) => shareId,
(_: State, { sort }: SelectItemsOptions) => sort,
],
(items, trashed, shareId, sort) =>
pipe(
filterItemsByShareId(shareId),
sortItems(sort)
)(items.filter((item) => (trashed ? isTrashed(item) : !isTrashed(item))))
);
/** Search result selector is organized to separate sort from search, as sorting can
* be computationally expensive when the number of items is high. The `search` is expected
* to change more frequently than the shareId / sortOption */
const itemsSearchResultSelector = createSelector(
[
selectSortedItemsByType,
(_state: State, { search }: SelectItemsOptions) => search,
(_state: State, { type }: SelectItemsOptions) => type,
],
(byShareId, search, type) => {
const searched = searchItems(byShareId, search);
const filtered = filterItemsByType(type)(searched);
return { filtered, searched, totalCount: byShareId.length };
}
);
export const selectItemsSearchResult = (options: SelectItemsOptions) => (state: State) =>
itemsSearchResultSelector(state, options);
export const selectItemWithOptimistic = (shareId: string, itemId: string) =>
createSelector(
[selectItemByShareIdAndId(shareId, itemId), selectByShareIdAsIfNotFailed, selectByShareIdAsIfNotOptimistic],
(item, withoutFailed, withoutOptimistic): Maybe<ItemRevisionWithOptimistic> =>
item
? {
...item,
failed: withoutFailed[item.shareId]?.[item.itemId]?.revision !== item.revision,
optimistic: withoutOptimistic[item.shareId]?.[item.itemId]?.revision !== item.revision,
}
: undefined
);
const selectItemsByTypeSelector = createSelector([selectAllItems, (_: State, type: ItemType) => type], (items, type) =>
items.filter((item) => item.data.type === type)
);
export const selectItemsByType =
<T extends ItemType>(type: T) =>
(state: State) =>
selectItemsByTypeSelector(state, type) as ItemRevision<T>[];
const loginItemByUsernameSelector = createSelector(
[selectItemsByType('login'), (_: State, username?: MaybeNull<string>) => username],
(loginItems, _username) => loginItems.find((item) => deobfuscate(item.data.content.username) === _username)
);
export const selectLoginItemByUsername = (username?: MaybeNull<string>) => (state: State) =>
loginItemByUsernameSelector(state, username);
const itemsByDomainSelector = createSelector(
[
selectItemsWithOptimistic,
(_state: State, domain: MaybeNull<string>) => domain,
(_state: State, _: MaybeNull<string>, { protocolFilter }: SelectItemsByDomainOptions) => protocolFilter,
(_state: State, _: MaybeNull<string>, { isPrivate }: SelectItemsByDomainOptions) => isPrivate,
(_state: State, _: MaybeNull<string>, { shareIds }: SelectItemsByDomainOptions) => shareIds,
(_state: State, _: MaybeNull<string>, { sortOn }: SelectItemsByDomainOptions) => sortOn ?? 'lastUseTime',
],
(items, domain, protocolFilter, isPrivate, shareIds, sortOn) =>
(typeof domain === 'string' && !isEmptyString(domain)
? items
.filter(invert(isTrashed))
.reduce<{ item: ItemRevisionWithOptimistic; priority: ItemUrlMatch }[]>((matches, item) => {
const validShareIds = !shareIds || shareIds.includes(item.shareId);
const validItem = !item.optimistic;
const validUrls = isLoginItem(item.data) && matchAny(item.data.content.urls)(domain);
/* If the item does not pass this initial "fuzzy" test, then we
* should not even consider it as an autofill candidate.
* This avoids unnecessarily parsing items' URLs with 'tldts' */
if (!(validShareIds && validItem && validUrls)) return matches;
/* `getItemPriorityForUrl` will apply strict domain matching */
const { data } = item as ItemRevisionWithOptimistic<'login'>;
const priority = getItemPriorityForUrl(data)(domain, { protocolFilter, isPrivate });
/* if negative priority : this item does not match the criteria */
if (priority === ItemUrlMatch.NO_MATCH) return matches;
matches.push({ item, priority });
return matches;
}, [])
.sort((a, b) => {
const aPrio = a.priority;
const bPrio = b.priority;
const aTime = a.item.lastUseTime ?? a.item.revisionTime;
const bTime = b.item.lastUseTime ?? b.item.revisionTime;
/* if we have a priority tie
* fallback to time comparison */
switch (sortOn) {
case 'priority':
return aPrio > 0 && aPrio === bPrio ? bTime - aTime : bPrio - aPrio;
case 'lastUseTime':
return bTime - aTime;
}
})
.map(prop('item'))
: []) as ItemRevisionWithOptimistic<'login'>[]
);
export const selectItemsByDomain = (domain: MaybeNull<string>, options: SelectItemsByDomainOptions) => (state: State) =>
itemsByDomainSelector(state, domain, options);
/* Autofill candidates resolution strategy :
*
* If we have a match on the subdomain : return
* the subdomain matches first, then the top-level
* domain matches and finally the other sub-domain
* matches excluding any previously matched direct
* subdomain matches.
*
* If we have no subdomain : return all matches (top
* level and other possible subdomain matches) with
* top-level domain matches first */
const autofillCandidatesSelector = createSelector(
[
(state: State, { domain, isSecure, isPrivate, shareIds, protocol }: SelectAutofillCandidatesOptions) =>
selectItemsByDomain(domain, {
protocolFilter: !isSecure && protocol ? [protocol] : [],
isPrivate,
shareIds,
sortOn: 'priority',
})(state),
(state: State, { subdomain, isSecure, isPrivate, shareIds, protocol }: SelectAutofillCandidatesOptions) =>
selectItemsByDomain(subdomain, {
protocolFilter: !isSecure && protocol ? [protocol] : [],
isPrivate,
shareIds,
sortOn: 'lastUseTime',
})(state),
],
(domainMatches, subdomainMatches) => [
...subdomainMatches /* push subdomain matches on top */,
...domainMatches.filter(({ itemId }) => !subdomainMatches.some((item) => item.itemId === itemId)),
]
);
export const selectAutofillCandidates = (options: SelectAutofillCandidatesOptions) => (state: State) => {
/* if the protocol is null : it likely means the
* URL validation failed - do not return any candidates */
if (options.protocol === null || options.domain === null) return [];
return autofillCandidatesSelector(state, options);
};
const autosaveCandidateSelector = createSelector(
[
(state: State, { subdomain }: SelectAutosaveCandidatesOptions) =>
selectItemsByDomain(subdomain, {
protocolFilter: [],
isPrivate: false,
})(state),
(state: State, { domain }: SelectAutosaveCandidatesOptions) =>
selectItemsByDomain(domain, {
protocolFilter: [],
isPrivate: false,
})(state),
(_: State, { username }: SelectAutosaveCandidatesOptions) => username,
],
(subdomainItems, domainItems, username) =>
[...subdomainItems, ...domainItems].filter(({ data }) => deobfuscate(data.content.username) === username)
);
export const selectAutosaveCandidate = (options: SelectAutosaveCandidatesOptions) => (state: State) =>
autosaveCandidateSelector(state, options);
| 8,056
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/limits.ts
|
import { createSelector } from '@reduxjs/toolkit';
import { sortItems } from '@proton/pass/lib/items/item.utils';
import { PlanType } from '@proton/pass/types';
import { selectItemsByType } from './items';
import { selectAllVaults } from './shares';
import { selectUserPlan } from './user';
export const selectVaultLimits = createSelector([selectAllVaults, selectUserPlan], (vaults, plan) => {
const vaultLimit = plan?.VaultLimit ?? Number.MAX_SAFE_INTEGER;
return {
vaultLimit,
vaultTotalCount: vaults.length,
vaultLimitReached: vaults.length >= vaultLimit,
didDowngrade: vaults.length > vaultLimit && plan?.Type === PlanType.free,
};
});
export const selectAliasLimits = createSelector([selectItemsByType('alias'), selectUserPlan], (alias, plan) => {
const aliasLimit = plan?.AliasLimit ?? Number.MAX_SAFE_INTEGER;
return {
aliasLimit,
aliasLimited: typeof plan?.AliasLimit === 'number',
aliasTotalCount: alias.length,
needsUpgrade: alias.length >= aliasLimit,
didDowngrade: alias.length > aliasLimit,
};
});
export const selectTOTPLimits = createSelector([selectItemsByType('login'), selectUserPlan], (loginItems, plan) => {
const totpLimit = plan?.TotpLimit;
let needsUpgrade = false;
let didDowngrade = false;
let totpAllowed: (itemId: string) => boolean = () => true;
if (typeof totpLimit === 'number') {
const totpItems = loginItems.filter((item) => Boolean(item.data.content.totpUri.v));
const totpTotalCount = totpItems.length;
needsUpgrade = totpTotalCount >= totpLimit;
didDowngrade = totpTotalCount > totpLimit;
totpAllowed = (itemId: string) =>
sortItems('createTimeASC')(totpItems)
.slice(0, totpLimit)
.some((item) => item.itemId === itemId);
}
return {
totpLimit,
needsUpgrade,
didDowngrade,
totpAllowed,
};
});
export const selectExtraFieldLimits = createSelector([selectUserPlan], (plan) => {
return {
needsUpgrade: plan?.Type === PlanType.free,
};
});
| 8,057
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/popup.ts
|
import type { Maybe, TabId } from '@proton/pass/types';
import type { PopupTabState } from '../reducers';
import type { State } from '../types';
export const selectPopupStateTabIds = (state: State): TabId[] =>
Object.keys(state.popup.tabs).map((val) => parseInt(val, 10));
export const selectPopupTabState =
(tabId: TabId) =>
(state: State): Maybe<PopupTabState> =>
state.popup.tabs?.[tabId];
export const selectPopupFilters = (state: State) => state.popup.filters;
export const selectPopupPasswordOptions = (state: State) => state.popup.passwordOptions;
| 8,058
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/pw-history.ts
|
import type { State } from '../types';
export const selectPasswordHistory = (state: State) => state.pwHistory;
| 8,059
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/request.ts
|
import type { Maybe } from '@proton/pass/types';
import type { RequestType } from '../actions/with-request';
import type { RequestEntry, RequestState } from '../reducers/request';
export const selectRequest =
(namespaceOrId: string) =>
({ request }: { request: RequestState }): Maybe<RequestEntry> =>
request?.[namespaceOrId];
export const selectRequestStatus =
(namespaceOrId: string) =>
({ request }: { request: RequestState }): Maybe<RequestType> =>
request?.[namespaceOrId]?.status;
export const selectRequestInFlight =
(namespaceOrId: string) =>
(state: { request: RequestState }): boolean =>
selectRequestStatus(namespaceOrId)(state) === 'start';
| 8,060
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/settings.ts
|
import { createSelector } from '@reduxjs/toolkit';
import { omit } from '@proton/shared/lib/helpers/object';
import type { Maybe } from '../../types';
import type { DomainCriterias } from '../../types/worker/settings';
import type { State } from '../types';
import { selectState } from './utils';
export const selectProxiedSettings = createSelector(selectState, ({ settings }: State) =>
omit(settings, ['sessionLockTTL', 'sessionLockRegistered'])
);
export const selectCanLoadDomainImages = ({ settings }: State) => settings.loadDomainImages;
export const selectSessionLockSettings = createSelector(selectState, ({ settings }: State) => ({
sessionLockRegistered: settings.sessionLockRegistered,
sessionLockTTL: settings.sessionLockTTL,
}));
export const selectHasRegisteredLock = (state: State) => state.settings.sessionLockRegistered;
export const selectSessionLockTTL = ({ settings }: State): Maybe<number> => settings.sessionLockTTL;
export const selectDisallowedDomains = ({ settings }: State): DomainCriterias => settings.disallowedDomains;
export const selectLocale = ({ settings }: State) => settings.locale;
| 8,061
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/shares.ts
|
import type { Selector } from '@reduxjs/toolkit';
import { createSelector } from '@reduxjs/toolkit';
import { isTrashed } from '@proton/pass/lib/items/item.predicates';
import { isVaultShare } from '@proton/pass/lib/shares/share.predicates';
import { isOwnVault, isSharedVault, isWritableVault } from '@proton/pass/lib/vaults/vault.predicates';
import { type Maybe, type MaybeNull, type ShareType } from '@proton/pass/types';
import { and, invert } from '@proton/pass/utils/fp/predicates';
import { sortOn } from '@proton/pass/utils/fp/sort';
import type { ShareItem, VaultShareItem } from '../reducers';
import type { State } from '../types';
import { SelectorError } from './errors';
import { selectItems } from './items';
import { selectProxiedSettings } from './settings';
export const selectShares = ({ shares }: State) => shares;
export const selectAllShares = createSelector(selectShares, (shares) => Object.values(shares));
/* vaults returned from this selector are always
* sorted alphabetically by ascending vault name */
export const selectAllVaults = createSelector([selectAllShares], (shares) =>
shares.filter(isVaultShare).sort((a, b) => a.content.name.localeCompare(b.content.name))
);
export const selectWritableVaults = createSelector([selectAllVaults], (vaults) => vaults.filter(isWritableVault));
export const selectOwnVaults = createSelector([selectAllVaults], (vaults) => vaults.filter(isOwnVault));
export const selectOwnWritableVaults = createSelector([selectAllVaults], (vaults) =>
vaults.filter(and(isWritableVault, isOwnVault))
);
export const selectOwnReadOnlyVaults = createSelector([selectAllVaults], (vaults) =>
vaults.filter(and(invert(isWritableVault), isOwnVault))
);
export const selectWritableSharedVaults = createSelector([selectAllVaults], (vaults) =>
vaults.filter(and(isWritableVault, isSharedVault))
);
const createVaultsWithItemsCountSelector = (vaultSelector: Selector<State, VaultShareItem[]>) =>
createSelector([vaultSelector, selectItems], (shares, itemsByShareId) =>
shares.map((share) => ({
...share,
count: Object.values(itemsByShareId?.[share.shareId] ?? {}).filter(invert(isTrashed)).length,
}))
);
export const selectVaultsWithItemsCount = createVaultsWithItemsCountSelector(selectAllVaults);
export const selectWritableVaultsWithItemsCount = createVaultsWithItemsCountSelector(selectWritableVaults);
export const selectWritableSharedVaultsWithItemsCount = createVaultsWithItemsCountSelector(selectWritableSharedVaults);
/* The default vault should be the oldest vault I own and can write to */
export const selectDefaultVault = createSelector(
[selectOwnWritableVaults],
(ownWritableVaults) => ownWritableVaults.filter((share) => share.owner).sort(sortOn('createTime', 'ASC'))[0]
);
/* If autosave vault is not set, fallback to default vault */
export const selectAutosaveVault = createSelector(
[selectShares, selectProxiedSettings, selectDefaultVault],
(shares, settings, defaultVault): ShareItem<ShareType.Vault> => {
const autosaveVaultId = settings.autosave.shareId;
if (autosaveVaultId) {
const share = shares[autosaveVaultId];
if (share && isVaultShare(share)) return share;
}
return defaultVault;
}
);
export const selectShare =
<T extends ShareType = ShareType>(shareId?: MaybeNull<string>) =>
({ shares }: State) =>
(shareId ? shares?.[shareId] : undefined) as Maybe<ShareItem<T>>;
export const selectShareOrThrow =
<T extends ShareType = ShareType>(shareId: string) =>
(state: State): ShareItem<T> => {
const share = selectShare<T>(shareId)(state);
if (!share) throw new SelectorError(`Share ${shareId} not found`);
return share;
};
export const selectVaultItemsCount = (shareId: MaybeNull<string>) =>
createSelector(
selectShare<ShareType.Vault>(shareId),
selectItems,
(share, itemsByShareId): MaybeNull<number> =>
share ? Object.values(itemsByShareId?.[share?.shareId] ?? {}).filter(invert(isTrashed)).length : null
);
| 8,062
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/user.ts
|
import { createSelector } from '@reduxjs/toolkit';
import { c } from 'ttag';
import type { Maybe, MaybeNull } from '@proton/pass/types';
import { PlanType } from '@proton/pass/types';
import type { PassFeature } from '@proton/pass/types/api/features';
import { UserPassPlan } from '@proton/pass/types/api/plan';
import { UNIX_DAY } from '@proton/pass/utils/time/constants';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import { type Address, SETTINGS_STATUS, UserType } from '@proton/shared/lib/interfaces';
import type { State } from '../types';
export const selectUserState = ({ user }: State) => user;
export const selectUser = ({ user: { user } }: State) => user;
export const selectUserPlan = ({ user: { plan } }: State) => plan;
export const selectUserSettings = ({ user: { userSettings } }: State) => userSettings;
export const selectTelemetryEnabled = ({ user }: State) => user.userSettings?.Telemetry === 1;
export const selectUserVerified = ({ user }: State) =>
user.user?.Type !== UserType.EXTERNAL || user.userSettings?.Email?.Status === SETTINGS_STATUS.VERIFIED;
/* Specification for pass specific plans in `/user/access` response :
* `paid` -> Plan: Plus | Trial: null | Limits: none
* `trial` -> Plan: Free | Trial: unix timestamp end | Limits
* `free` -> Plan: Free | Trial: null | Limits */
export const selectPassPlan = ({ user: { plan } }: State): UserPassPlan => {
switch (plan?.Type) {
case PlanType.plus:
return plan.TrialEnd && getEpoch() < plan.TrialEnd ? UserPassPlan.TRIAL : UserPassPlan.PLUS;
default: {
return UserPassPlan.FREE;
}
}
};
export const selectPlanDisplayName = createSelector([selectUserPlan, selectPassPlan], (userPlan, passPlan) => {
switch (passPlan) {
case UserPassPlan.TRIAL:
return c('Info').t`Pass Plus trial`;
case UserPassPlan.FREE:
case UserPassPlan.PLUS:
return userPlan?.DisplayName;
}
});
export const selectTrialDaysRemaining = ({ user: { plan } }: State): MaybeNull<number> => {
if (!plan?.TrialEnd) return null;
return Math.ceil(Math.max((plan.TrialEnd - getEpoch()) / UNIX_DAY, 0));
};
/* user tier is only used for telemetry */
export const selectUserTier = ({ user: { user, plan } }: State) =>
user?.Type === UserType.MANAGED ? 'subuser' : plan?.InternalName;
export const selectAllAddresses = ({ user: { addresses } }: State): Address[] => Object.values(addresses);
export const selectAddress =
(addressId: string) =>
({ user: { addresses } }: State): Maybe<Address> =>
addresses[addressId];
export const selectLatestEventId = ({ user: { eventId } }: State) => eventId;
export const selectFeatureFlags = ({ user: { features } }: State) => features;
export const selectFeatureFlag =
(feature: PassFeature) =>
({ user: { features } }: State): boolean =>
features?.[feature] ?? false;
| 8,063
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/store
|
petrpan-code/ProtonMail/WebClients/packages/pass/store/selectors/utils.ts
|
import type { State } from '../types';
export const selectState = (state: State) => state;
const EMPTY_LIST: any[] = [];
export const NOOP_LIST_SELECTOR = <T>() => EMPTY_LIST as T[];
| 8,064
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/_animation.scss
|
@import '~@proton/styles/scss/lib/config';
.anime-fade-in,
.anime-fade-in > * {
animation: anime-fade-in var(--anime-duration, 0.25s) easing(ease-out-sine) var(--anime-delay, 0.1s) both;
}
@keyframes anime-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
| 8,065
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/_button.scss
|
a {
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.button {
padding-block: 0.5rem;
padding-inline: 0.75rem;
&.button-small {
padding-block: 0.375rem;
padding-inline: 0.5rem;
}
}
.button-solid-norm,
.button-solid-weak {
align-items: center;
display: flex;
justify-content: center;
block-size: 2.25rem;
&.button-for-icon {
inline-size: 2.25rem;
}
&.button-small {
block-size: 2rem;
&.button-for-icon {
inline-size: 2rem;
}
}
&.button-xs {
block-size: 1.5rem;
&.button-for-icon {
inline-size: 1.5rem;
}
}
}
.button-for-icon {
padding: 0.5rem;
&.button-small {
padding: 0.375rem;
}
}
| 8,066
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/_dropdown.scss
|
@import '~@proton/styles/scss/lib/config';
.dropdown {
background-color: var(--background-weak);
border: 1px solid var(--border-norm);
.dropdown-content {
background-color: var(--background-weak);
}
.dropdown-content::before,
.dropdown-content::after {
background-color: var(--background-weak);
block-size: 0.5rem;
}
.dropdown-item--is-selected,
.dropdown-item--is-selected:active,
.dropdown-item--is-selected:focus,
.dropdown-item--is-selected:hover {
background-color: var(--field-norm);
color: var(--text-norm);
}
}
| 8,067
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/_fields.scss
|
@import '~@proton/styles/scss/lib/config';
.placeholder-danger::placeholder {
color: var(--signal-danger);
}
// _input.scss override
.input {
border-color: var(--border-weak);
}
.field,
.field-icon-container {
border-color: var(--border-weak);
}
.field-two-container:has(input:placeholder-shown, textarea:placeholder-shown) {
label,
label > span {
color: var(--text-norm);
}
}
// _checkbox.scss override
.checkbox-fakecheck,
.radio-fakeradio {
border-color: var(--border-weak);
&:hover {
background-color: var(--background-weak);
}
}
.checkbox-input[disabled] + .checkbox-fakecheck,
.checkbox-input[disabled] + .radio-fakeradio {
background-color: var(--background-weak);
}
textarea {
margin: 0;
outline: none;
padding: 0;
resize: none;
}
// Toggle component
.toggle-label {
.toggle-container {
background-color: var(--interaction-norm-minor-1);
transition: background-color 0.2s;
&::before {
background-color: var(--interaction-weak-major-3);
}
&:hover::before {
background-color: white;
}
&.toggle-container--checked {
background-color: var(--interaction-norm);
&::before {
background-color: var(--interaction-weak-contrast);
}
&:hover {
&::before {
background-color: white;
}
}
}
}
.toggle-container-text {
svg {
display: none;
}
}
}
// Slider component
.slider {
&.slider-small {
block-size: rem(4);
}
.slider-rail {
background-color: var(--interaction-norm-minor-1);
}
span.slider-thumb {
block-size: rem(24);
inline-size: rem(24);
border-radius: rem(12);
background-color: white;
color: white;
}
}
// Slider.scss override
// Something fishy happening here with the order of the css loading into the dom.
// It's only in pass (or maybe only in the extension) for some reason, maybe something
// to do with the webpack config. In any case, this gets overwritten by the word-break
// defined in the tooltip.
.slider-thumb-tooltip {
word-break: initial !important;
}
| 8,068
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/_lobby.scss
|
.pass-lobby {
block-size: 100%;
inline-size: 100%;
background: radial-gradient(61.86% 61.86% at 50% 0%, rgb(255 255 255 / 0.16) 0%, rgb(255 255 255 / 0) 100%), #191927;
}
| 8,069
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/_overrides.scss
|
@import '~@proton/styles/scss/lib/config';
:root {
--border-radius-xl: 0.88rem;
}
// Force the default font-size to the standard 16px value
// for all pass extension components in order to avoid
// inconsistencies when user overrides browser settings
html {
font-size: 16px;
}
// Pill outline buttons
.button.button-outline-norm.button-pill {
--button-default-text-color: var(--interaction-norm-major-1);
--button-hover-text-color: var(--interaction-norm-major-2);
--button-active-text-color: var(--interaction-norm-major-3);
}
pre {
// override default monospaced font applied to pre tag
font-family: var(--optional-font-family, 'Inter', #{$fallback-fonts});
margin: 0;
}
| 8,070
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/_scroll.scss
|
@import '~@proton/styles/scss/lib/config';
.overflow-overlay {
overflow: overlay;
}
// Scroll.scss override
// Allow overlay scrollbar in scrollable
// containers in extension : this css feature
// has limited support but we're targetting modern
// browsers. TODO: double check when supporting Firefox
.scroll-outer-vertical .scroll-inner {
overflow-y: overlay;
}
.scroll-outer-vertical .scroll-start-shadow,
.scroll-outer-vertical .scroll-end-shadow {
block-size: 1.5rem;
background: linear-gradient(180deg, rgb(14 14 14 / 0.35), transparent);
}
.scroll-outer-vertical .scroll-end-shadow {
background: linear-gradient(0deg, rgb(14 14 14 / 0.35), transparent);
}
| 8,071
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/_skeletons.scss
|
@import '~@proton/styles/scss/lib/config';
@import '~@proton/styles/scss/lib/easing';
@import '~@proton/styles/scss/specifics/placeholder-loading';
.pass {
&-skeleton {
&::before {
@extend %item-loading-pseudo;
@extend %placeholder-loading;
}
&--select {
&::before {
inline-size: 80%;
}
}
&--item-heading {
&::before {
inline-size: 90%;
}
}
&--item-subheading {
&::before {
inline-size: 65%;
}
}
&--item-icon {
&::before {
inline-size: em(16);
block-size: em(16);
}
}
&--alias-preview,
&--value {
&::before {
inline-size: 80%;
}
}
&--alias-mailbox {
&::before {
inline-size: 50%;
}
}
}
}
| 8,072
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/_text.scss
|
@import '~@proton/styles/scss/lib/config';
pre {
// override default monospaced font applied to pre tag
font-family: var(--optional-font-family, 'Inter', #{$fallback-fonts});
margin: 0;
}
.line-height-1 {
line-height: 1;
}
/*
* FIXME
* handle line-height within core spacing-two?
*/
.text-sm {
line-height: 1rem;
}
.text-lg {
line-height: 1.25rem;
}
.text-2xl {
line-height: 1.5rem;
}
| 8,073
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/styles/common.scss
|
@import '~@proton/styles/scss/proton-pass';
@import 'overrides';
@import 'animation';
@import 'button';
@import 'fields';
@import 'lobby';
@import 'scroll';
@import 'skeletons';
@import 'text';
| 8,074
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/index.ts
|
export * from './api';
export * from './crypto';
export * from './data';
export * from './forms';
export * from './protobuf';
export * from './utils';
export * from './worker';
| 8,075
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/api/api.ts
|
import type { Subscriber } from '@proton/pass/utils/pubsub/factory';
import type { RefreshSessionResponse } from '@proton/shared/lib/authentication/interface';
import type { Maybe } from '../utils';
import type { ApiResponse } from './pass';
export type ApiCallFn = (options: ApiOptions) => Promise<Response>;
export type ApiAuth = {
UID: string;
AccessToken: string;
RefreshToken: string;
RefreshTime?: number;
};
export type ApiState = {
appVersionBad: boolean;
offline: boolean;
pendingCount: number;
serverTime?: Date;
sessionInactive: boolean;
sessionLocked: boolean;
unreachable: boolean;
};
/**
* This generic Api type lets us :
* - Infer the Api response type from the auto-generated swagger
* types by only looking at the options's method and url
* - Hard-cast the response type when dealing with API urls
* that have not been auto-generated (legacy support)
*/
export type Api = {
<T extends any = void, U extends string = string, M extends string = string>(
config: ApiOptions<U, M>
): Promise<ApiResult<T, U, M>>;
getState: () => ApiState;
reset: () => Promise<void>;
subscribe: (subscribe: Subscriber<ApiSubscribtionEvent>) => () => void;
unsubscribe: () => void;
};
export type ApiOptions<U extends string = string, M extends string = string> = {
[option: string]: any;
} & {
headers?: { [key: string]: string };
method?: M;
output?: 'json' | 'raw' | 'stream';
params?: { [key: string]: any };
silent?: boolean;
url?: U;
};
export type ApiResult<T extends any = void, U extends string = string, M extends string = string> = T extends void
? ApiResponse<`${U}`, `${M}`>
: T;
export type ApiResponseMapper<T extends any = void, U extends string = string, M extends string = string> = Maybe<
(response: T extends void ? ApiResponse<`${U}`, `${M}`> : T) => any
>;
export type ApiSubscribtionEvent =
| { type: 'session'; status: 'inactive' | 'locked' }
| { type: 'refresh'; data: RefreshSessionResponse & { RefreshTime: number } }
| { type: 'error'; error: string };
| 8,076
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/api/events.ts
|
/* TODO: add all server events
* in this type definition - it only
* specifies the keys we're consuming
* in the extension sagas for now */
import type { Invoice } from '@proton/components/containers/invoices/interface';
import type { Address, Subscription, User, UserSettings } from '@proton/shared/lib/interfaces';
export enum ChannelType {
USER = 'user',
SHARE = 'share',
SHARES = 'shares',
}
export enum ShareEventType {
SHARE_DISABLED = 'SHARE_DISABLED',
ITEMS_DELETED = 'ITEMS_DELETED',
}
export enum EventActions {
DELETE,
CREATE,
UPDATE,
}
export type UserEvent = {
More: 0 | 1;
EventID: string;
Refresh?: number;
User?: User;
UserSettings?: UserSettings;
Addresses?: AddressEvent[];
Subscription?: Subscription;
Invoices?: Invoice;
};
export type AddressEvent = {
ID: string;
Action: EventActions;
Address: Address;
};
export type ShareEventPayload =
| { type: ShareEventType.SHARE_DISABLED; shareId: string }
| { type: ShareEventType.ITEMS_DELETED; shareId: string; itemIds: string[] };
| 8,077
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/api/features.ts
|
import type { MaybeNull } from '../utils';
export enum PassFeature {
PassSharingV1 = 'PassSharingV1',
PassRemovePrimaryVault = 'PassRemovePrimaryVault',
PassSharingNewUsers = 'PassSharingNewUsers',
}
export const PassFeaturesValues = Object.values(PassFeature);
/* Unleash response types */
export type FeatureFlagPayload = {
type: string;
value: string;
};
export type FeatureFlagVariant = {
name: string;
enabled: boolean;
payload: MaybeNull<FeatureFlagPayload>;
};
export type FeatureFlagToggle = {
name: string;
variant: FeatureFlagVariant;
};
export type FeatureFlagsResponse = {
Code: number;
toggles: FeatureFlagToggle[];
};
| 8,078
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/api/fork.ts
|
export type ForkPayload = {
selector: string;
keyPassword: string;
persistent: boolean;
trusted: boolean;
state: string;
};
| 8,079
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/api/index.ts
|
export * from './api';
export * from './events';
export * from './keys';
export * from './pass';
export * from './session-lock';
| 8,080
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/api/keys.ts
|
import type { KEY_FLAG } from '@proton/shared/lib/constants';
export type Key = {
Flags: KEY_FLAG;
PublicKey: string;
Source: string;
};
export type SignedKeyList = {
MinEpochID: number;
MaxEpochID: number;
ExpectedMinEpochID: number;
Data: string;
ObsolescenceToken: string;
Signature: string;
Revision: number;
};
export type GetAllPublicKeysResponse = { Address: { Keys: Key[] } };
| 8,081
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/api/pass.ts
|
/**
* ⚠️ Do not edit this file - it is autogenerated using
* `https://github.com/MatthiasMargot/typegen/pull/34`
* from the Pass API swagger OpenAPI file
*/
export enum ResponseCodeSuccess {
ProtonResponseCode_1000 = 1000,
}
export type ProtonError = {
Code?: number;
/* Error message */
Error?: string;
/* Error description (can be an empty object) */
Details?: {};
};
export type ItemMoveMultipleToShareRequest = {
/* Encrypted ID of the destination share */
ShareID: string;
/* Items to move to the destination share */
Items: ItemMoveIndividualToShareRequest[];
};
export type NewUserInviteCreateRequest = {
/* Email of the target user */
Email: string;
/* Invite target type. 1 = Vault, 2 = Item */
TargetType: number;
/* Base64 signature of "inviteemail|base64(vaultKey)" signed with the admin's address key */
Signature: string;
/* ShareRoleID for this invite. The values are in the top level Pass docs. */
ShareRoleID: string;
/* Invite encrypted item ID (only in case the invite is of type Item) */
ItemID?: string | null;
/* Expiration time for the share */
ExpirationTime?: number | null;
};
export type NewUserInvitePromoteRequest = {
/* List of keys encrypted for the other user's address key and signed with your address key */
Keys: KeyRotationKeyPair[];
};
export type ItemCreateRequest = {
/* Encrypted ID of the VaultKey used to create this item */
KeyRotation: number;
/* Version of the content format used to create the item */
ContentFormatVersion: number;
/* Encrypted item content encoded in Base64 */
Content: string;
/* Item key encrypted with the VaultKey, contents encoded in base64 */
ItemKey: string;
};
export type CustomAliasCreateRequest = {
/* Prefix for the alias to be created (prefix.xxx@domain.com) */
Prefix: string;
/* Signed suffix for the alias to be created (xxx.asdaa3@domain.com.signature) */
SignedSuffix: string;
/* IDs for the mailboxes that will receive emails sent to this alias */
MailboxIDs: number[];
Item: ItemCreateRequest2;
};
export type SetAliasMailboxesRequest = {
/* IDs for the mailboxes that will receive emails sent to this alias */
MailboxIDs: number[];
};
export type ImportItemBatchRequest = {
/* Items to be imported. At most 100 */
Items: ImportItemRequest[];
};
export type InviteAcceptRequest = {
/* Invite keys encrypted and signed with the User Key */
Keys: KeyRotationKeyPair[];
};
export type AliasAndItemCreateRequest = {
Alias: CustomAliasCreateRequest;
Item: ItemCreateRequest;
};
export type ItemsToTrashRequest = {
/* Pairs of item IDs with their latest revision. At most 100. */
Items: ItemIDRevision[];
};
export type ItemsToSoftDeleteRequest = {
/* ItemIDs with their current revision. At most 100 items. */
Items: ItemIDRevision2[];
/* Skip checking that the items are in the trash. Allows to delete directly */
SkipTrash?: boolean | null;
};
export type ItemUpdateRequest = {
KeyRotation: number;
/* Last item revision existing when the item was created */
LastRevision: number;
/* Encrypted item content encoded in Base64 */
Content?: string;
/* Version of the content format used to create the item */
ContentFormatVersion: number;
};
export type UpdateItemLastUseTimeRequest = {
/* Time when the item was last used. If no value is passed then the current server time will be used. */
LastUseTime?: number | null;
};
export type ItemMoveSingleToShareRequest = {
/* Encrypted ID of the destination share */
ShareID: string;
Item: ItemCreateRequest;
};
export type KeyRotationRequest = {
/* Current key rotation */
CurrentKeyRotation?: number;
/* New vault key base64 encoded, encrypted and signed with the current primary user key */
VaultKey: string;
/* New encryption keys for the items in the vault */
ItemKeys?: EncodedKeyRotationItemKey[];
/* Vault key encrypted for the users that have vault shares EXCEPT the current user */
VaultKeyForShares?: EncodedKeyRotationShareKeyForAddress[];
/* Item key encrypted each share of type item */
ItemKeysForShares?: EncodedKeyRotationShareKeyForAddress[];
};
export type PendingShareKeyPromoteRequest = {
/* Pending share keys to promote */
Keys: EncryptedKeyWithRotation[];
};
export type UserSessionLockRequest = {
/* Lock code to attach to this session */
LockCode: string;
/* Number of seconds the session will stay unlocked */
UnlockedSecs: number;
};
export type UserSessionUnlockRequest = {
/* Lock code to attach to this session */
LockCode: string;
};
export type InviteCreateRequest = {
/* List of keys encrypted for the other user's address key and signed with your address key */
Keys: KeyRotationKeyPair[];
/* Email of the target user */
Email: string;
/* Invite target type. 1 = Vault, 2 = Item */
TargetType: number;
/* ShareRoleID for this invite. The values are in the top level Pass docs. */
ShareRoleID?: string;
/* If this invite is generated from a new user invite. ID of the original new user invite */
SourceNewUserInviteID?: string | null;
/* Invite encrypted item ID (only in case the invite is of type Item) */
ItemID?: string | null;
/* Expiration time for the share */
ExpirationTime?: number | null;
};
export type ShareUpdateRequest = {
/* ShareRoleID to apply to this share */
ShareRoleID?: string | null;
/* Expiration time to set for this share */
ExpireTime?: number | null;
};
export type VaultCreateRequest = {
/* AddressID that should be displayed as the owner */
AddressID: string;
/* Vault content protocol buffer data encrypted with the vault key */
Content: string;
/* Vault content format version. Should be 1 for now. */
ContentFormatVersion: number;
/* Vault key encrypted and signed with the primary user key */
EncryptedVaultKey: string;
/* Mark this vault as primary vault */
Primary?: boolean;
};
export type VaultUpdateRequest = {
/* Vault content protocol buffer data encrypted with the vault key */
Content: string;
/* Vault content format version. Should be 1 for now. */
ContentFormatVersion: number;
/* Key rotation used to encrypt the content */
KeyRotation: number;
};
export type VaultTransferOwnershipRequest = {
/* ShareID to move the ownership to. It has to have admin privileges */
NewOwnerShareID: string;
};
export type ItemMoveMultipleResponse = {
Items: ItemRevisionContentsResponse[];
};
export type AliasOptionsResponse = {
/* List of possible suffixes when creating a new alias. Only valid for 10 minutes */
Suffixes: AliasSuffixResponse[];
/* List of possible mailboxes when creating a new alias */
Mailboxes: AliasMailboxResponse[];
/* Whether the user can create new alias */
CanCreateAlias: boolean;
};
export type ItemRevisionContentsResponse = {
ItemID: string;
Revision: number;
ContentFormatVersion: number;
KeyRotation?: number;
/* Base64 encoded item contents */
Content: string;
/* Base64 encoded item key. Only for vault shares. */
ItemKey?: string | null;
/* Revision state. Values: 1 = Active, 2 = Trashed */
State: number;
/* Whether this item is pinned for this user */
Pinned?: boolean;
/* In case this item contains an alias, this is the email address for the alias */
AliasEmail?: string | null;
/* Creation time of the item */
CreateTime: number;
/* Time of the latest modification of the item */
ModifyTime: number;
/* Time when the item was last used */
LastUseTime?: number;
/* Creation time of this revision */
RevisionTime: number;
};
export type AliasDetailsResponse = {
/* Email of the alias */
Email: string;
/* List of mailboxes of the alias */
Mailboxes: AliasMailboxResponse2[];
/* List of mailboxes that can be linked to the alias */
AvailableMailboxes: AliasMailboxResponse2[];
};
export type ItemRevisionListResponse = {
RevisionsData: ItemRevisionContentsResponse[];
/* Total number of items */
Total: number;
/* Token to pass for getting the next page. Null if there is none */
LastToken: string | null;
};
export type InvitesGetResponse = {
/* UserInvites */
Invites: InviteDataForUser[];
};
export type ShareGetResponse = {
ShareID: string;
VaultID: string;
/* AddressID that will be displayed as the owner of the share */
AddressID: string;
/* Whether this vault is primary for this user */
Primary: boolean;
/* Whether the user is owner of this vault */
Owner: boolean;
/* Type of share. 1 for vault, 2 for item */
TargetType: number;
/* TargetID for this share */
TargetID: string;
/* Members for the target of this share */
TargetMembers: number;
/* Max members allowed for the target of this share */
TargetMaxMembers: number;
/* Whether this share is shared or not */
Shared: boolean;
/* How many invites are pending of acceptance */
PendingInvites: number;
/* How many new user invites are waiting for an admin to create the proper invite */
NewUserInvitesReady: number;
/* Permissions for this share */
Permission: number;
/* ShareRoleID for this share. The values are in the top level Pass docs. */
ShareRoleID?: string;
/* Base64 encoded content of the share. Only shown if it a vault share */
Content?: string | null;
/* Key rotation that should be used to open the content */
ContentKeyRotation?: number | null;
/* Content format version */
ContentFormatVersion?: number | null;
/* If the share will expire, when it will expire */
ExpireTime?: number | null;
/* Share creation time */
CreateTime: number;
};
export type AliasAndItemResponse = {
Alias: ItemRevisionContentsResponse;
Item: ItemRevisionContentsResponse;
};
export type ItemTrashResponse = {
/* Updated items */
Items: ItemRevisionResponse[];
};
export type ItemLatestKeyResponse = {
/* Key rotation */
KeyRotation: number;
/* Base64 representation of the encrypted Item Key */
Key: string;
};
export type ItemGetKeysResponse = {
/* Keys */
Keys: ItemKeyResponse[];
/* Total number of keys */
Total: number;
};
export type ShareKeysResponse = {
/* Keys */
Keys: ShareKeyResponse[];
/* Total number of keys */
Total: number;
};
export type ShareKeyResponse = {
/* Rotation for this key */
KeyRotation: number;
/* Base64 encoded key */
Key: string;
/* UserKeyID to open this key */
UserKeyID?: string;
/* When was this key created */
CreateTime: number;
};
export type PendingShareKeysListResponse = {
/* Pending share keys */
Pending?: PendingShareKeyGetResponse[];
};
export type EventIDGetResponse = {
/* Last event ID for this share */
EventID?: string;
};
export type PassEventListResponse = {
/* Updated share in case the vault content changes */
UpdatedShare?: ShareGetResponse | undefined | null;
/* New or updated items */
UpdatedItems: ItemRevisionContentsResponse[];
/* Deleted items */
DeletedItemIDs: string[];
/* Items that have the last use time updated */
LastUseItems?: ItemIDLastUseTime[];
/* New key rotation value if there has been a key rotation */
NewKeyRotation?: number | null;
/* New eventID if for future requests */
LatestEventID: string;
/* If there are more events to process this will be true */
EventsPending: boolean;
/* If the share needs a full refresh this will be true */
FullRefresh?: boolean;
};
export type SessionLockStorageTokenResponse = {
/* Storage token to encrypt the local storage */
StorageToken: string;
};
export type SessionLockCheckExistsResponse = {
/* Whether this session has a lock registered or not */
Exists: boolean;
/* If the lock exists, that is the unlocked time */
UnlockedSecs?: number | null;
};
export type SharesGetResponse = {
/* List of shares */
Shares: ShareGetResponse[];
};
export type InvitesForVaultGetResponse = {
/* Invites for this share */
Invites: VaultInviteData[];
/* New user invites for this share */
NewUserInvites: NewUserInviteGetResponse[];
};
export type ActiveSharesInVaultGetResponse = {
/* Shares */
Shares: ActiveShareGetResponse[];
/* Total amount of shares */
Total: number;
};
export type ActiveShareGetResponse = {
/* ID of the share */
ShareID: string;
/* Name of the user */
UserName: string;
/* Email of the user */
UserEmail: string;
/* Whether this is the owner of the share */
Owner: boolean;
/* Type of share. 1 for vault, 2 for item */
TargetType: number;
/* ID of the top object that this share gives access to */
TargetID: string;
/* Permissions this share has */
Permission: number;
/* ShareRoleID this share has */
ShareRoleID: string;
/* Expiration time if set */
ExpireTime?: number | null;
/* Creation time of this share */
CreateTime: number;
};
export type UserAccessGetResponse = {
Plan: PassPlanResponse;
/* Pending invites for this user */
PendingInvites: number;
/* Number of new user invites ready for an admin to accept */
WaitingNewUserInvites: number;
};
export type UserAccessCheckGetResponse = {
/* When this user started using Pass */
ActivationTime: number;
};
export type GetMissingAliasResponse = {
/* MissingAlias */
MissingAlias?: MissingAliasDto[];
};
export type ItemMoveIndividualToShareRequest = {
/* Encrypted ID of the source item to move */
ItemID: string;
Item: ItemCreateRequest;
};
export type KeyRotationKeyPair = {
/* Key rotation */
KeyRotation: number;
/* Encrypted key encoded in base64 */
Key: string;
};
export type ItemCreateRequest2 = {};
export type ImportItemRequest = {
Item: ItemCreateRequest;
/* Alias email in case this item is an alias item */
AliasEmail?: string | null;
/* Wether this item is the trash. Default value is false. */
Trashed?: boolean;
/* When was this item created. By default it will be now */
CreateTime?: number | null;
/* When was this item modified. By default it will be now */
ModifyTime?: number | null;
};
export type ItemIDRevision = {};
export type ItemIDRevision2 = {
/* ItemID */
ItemID: string;
/* Current revision for the item */
Revision: number;
};
export type EncodedKeyRotationItemKey = {
/* ItemID for this encrypted key */
ItemID: string;
/* Base64 encoded item key */
ItemKey: string;
};
export type EncodedKeyRotationShareKeyForAddress = {
/* ShareID for this key */
ShareID: string;
/* AddressID to which this key is encrypted */
AddressID: string;
/* Base64 encoded key encrypted for the address key of the user and signed with our address key */
EncryptedKeyForAddress: string;
};
export type EncryptedKeyWithRotation = {
/* Key rotation */
KeyRotation: number;
/* Encrypted key encoded in base64 */
EncryptedKey: string;
};
export type AliasSuffixResponse = {
/* Alias ending including the domain */
Suffix?: string;
/* Signed suffix to ensure users cannot generate their own */
SignedSuffix?: string;
/* Whether this is a user domain or a public SL domain */
IsCustom?: boolean;
/* Domain that this suffix uses */
Domain?: string;
};
export type AliasMailboxResponse = {
/* ID of the mailbox in SimpleLogin */
ID: number;
/* Email of the mailbox */
Email: string;
};
export type AliasMailboxResponse2 = {
/* ID of the mailbox in SimpleLogin */
ID: number;
/* Email of the mailbox */
Email: string;
};
export type InviteDataForUser = {
/* InviteToken */
InviteToken: string;
/* Number of reminders sent */
RemindersSent: number;
/* Type of target for this invite */
TargetType: number;
/* TargetID for this invite */
TargetID: string;
/* Email of the inviter */
InviterEmail: string;
/* Invited email */
InvitedEmail: string;
/* Invited AddressID */
InvitedAddressID?: string;
/* Share keys encrypted for the address key of the invitee and signed with the user keys of the inviter */
Keys: KeyRotationKeyPair[];
VaultData?: InviteVaultDataForUser;
/* True if the invite comes from a NewUserInvite */
FromNewUser: boolean;
/* Creation time for the invite */
CreateTime: number;
};
export type ItemRevisionResponse = {
/* ID of the item */
ItemID: number;
/* Latest item revision */
Revision: number;
/* Revision state. Values: 1 = Active, 2 = Trashed */
State: number;
/* Time of the latest modification of the item */
ModifyTime: number;
/* Creation time of this revision */
RevisionTime: number;
};
export type ItemKeyResponse = {
/* Rotation for this key */
KeyRotation: number;
/* Base64 encoded key */
Key: string;
};
export type PendingShareKeyGetResponse = {
/* Pending share key ID */
PendingShareKeyID: string;
/* AddressID for this pending share key */
AddressID: string;
/* AddressID that did the key rotation. Should be signing this key. */
RotatorAddressID?: string;
/* Key rotation for this pending share key */
KeyRotation: number;
/* Base64 encoded encrypted shake key for this address */
EncryptedKey: string;
};
export type ItemIDLastUseTime = {
/* Item ID */
ItemID: string;
/* Last use time for this item */
LastUseTime: number;
};
export type VaultInviteData = {
/* InviteID */
InviteID: string;
/* Email of the invited user */
InvitedEmail: string;
/* Email of the user who created the invite */
InviterEmail: string;
/* Share role for this invite */
ShareRoleID: string;
/* Target type for the invite */
TargetType: number;
/* Target ID for the invite */
TargetID: string;
/* Number of reminders sent to the invited user */
RemindersSent: number;
/* Creation time for the invite */
CreateTime: number;
/* Modify time for the invite */
ModifyTime: number;
};
export type NewUserInviteGetResponse = {
/* ID of the invite */
NewUserInviteID?: string;
/* State of the invite. <ul><li>1 - Waiting for user creation.</li><li>2 - User has been created and invite can be created</li></ul> */
State?: number;
/* Type of target for this invite */
TargetType?: number;
/* TargetID for this invite */
TargetID?: string;
/* Share role for this invite */
ShareRoleID?: string;
/* Invited email */
InvitedEmail?: string;
/* Email of the inviter */
InviterEmail?: string;
/* Base64 encoded signature with the inviter email address keys */
Signature?: string;
/* Creation time for the invite */
CreateTime?: number;
/* Last modification time for the invite */
ModifyTime?: number;
};
export type PassPlanResponse = {
Type: PlanType;
/* Internal name of the plan */
InternalName: string;
/* Display name of the plan */
DisplayName: string;
/* Force hide the upgrade button independently of plan */
HideUpgrade?: boolean;
/* If the user is in trial show when the trial ends. Otherwise it sill be null */
TrialEnd?: number | null;
/* Vault limit, null for plans with Pass plus */
VaultLimit?: number | null;
/* Alias limit, null for plans with Pass plus */
AliasLimit?: number | null;
/* TOTP limit, null for plans with Pass plus */
TotpLimit?: number | null;
};
export type MissingAliasDto = {
/* Email of the alias */
Email?: string;
/* Email note as stored in SL */
Note?: string;
};
export type InviteVaultDataForUser = {
/* Base64 encoded content of the share. Only shown if it a vault share */
Content: string;
/* Key rotation that should be used to open the content */
ContentKeyRotation: number;
/* Content format version */
ContentFormatVersion: number;
/* Number of members that have access to this vault */
MemberCount?: number;
/* Number of items in this vault */
ItemCount?: number;
};
export enum PlanType {
free = 'free',
plus = 'plus',
}
export type ApiMethod = string;
export type ApiResponse<Path extends string, Method extends ApiMethod> = Path extends `pass/v1/vault/${string}/primary`
? Method extends `put`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/vault/${string}/owner`
? Method extends `put`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/vault/${string}`
? Method extends `put`
? { Code?: ResponseCodeSuccess; Share?: ShareGetResponse }
: Method extends `delete`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/vault`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Share?: ShareGetResponse }
: never
: Path extends `pass/v1/user/session/lock/unlock`
? Method extends `post`
? { Code?: ResponseCodeSuccess; LockData?: SessionLockStorageTokenResponse }
: never
: Path extends `pass/v1/user/session/lock/force_lock`
? Method extends `post`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/user/session/lock/check`
? Method extends `get`
? { Code?: ResponseCodeSuccess; LockInfo?: SessionLockCheckExistsResponse }
: never
: Path extends `pass/v1/user/session/lock`
? Method extends `post`
? { Code?: ResponseCodeSuccess; LockData?: SessionLockStorageTokenResponse }
: Method extends `delete`
? { Code?: ResponseCodeSuccess; LockData?: SessionLockStorageTokenResponse }
: never
: Path extends `pass/v1/user/missing_alias`
? Method extends `get`
? GetMissingAliasResponse & { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/user/access/check`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Data?: undefined | null }
: never
: Path extends `pass/v1/user/access`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Access?: UserAccessGetResponse }
: Method extends `post`
? { Code?: ResponseCodeSuccess; Access?: UserAccessGetResponse }
: never
: Path extends `pass/v1/share/${string}/user/${string}`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Share?: ActiveShareGetResponse }
: Method extends `put`
? { Code?: ResponseCodeSuccess }
: Method extends `delete`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/user`
? Method extends `get`
? ActiveSharesInVaultGetResponse & { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/key/pending`
? Method extends `get`
? {
Code?: ResponseCodeSuccess;
PendingShareKeys?: PendingShareKeysListResponse;
}
: Method extends `post`
? { Code?: ResponseCodeSuccess; ShareKeys?: ShareKeysResponse }
: never
: Path extends `pass/v1/share/${string}/key`
? Method extends `get`
? { Code?: ResponseCodeSuccess; ShareKeys?: ShareKeysResponse }
: Method extends `post`
? { Code?: ResponseCodeSuccess; ShareKey?: ShareKeyResponse }
: never
: Path extends `pass/v1/share/${string}/item/with_alias`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Bundle?: AliasAndItemResponse }
: never
: Path extends `pass/v1/share/${string}/item/untrash`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Items?: ItemTrashResponse }
: never
: Path extends `pass/v1/share/${string}/item/trash`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Items?: ItemTrashResponse }
: never
: Path extends `pass/v1/share/${string}/item/share`
? Method extends `put`
? ItemMoveMultipleResponse & { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/item/import/batch`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Revisions?: ItemRevisionListResponse }
: never
: Path extends `pass/v1/share/${string}/item/${string}/share`
? Method extends `put`
? { Code?: ResponseCodeSuccess; Item?: ItemRevisionContentsResponse }
: never
: Path extends `pass/v1/share/${string}/item/${string}/revision`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Revisions?: ItemRevisionListResponse }
: never
: Path extends `pass/v1/share/${string}/item/${string}/pin`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Item?: ItemRevisionContentsResponse }
: Method extends `delete`
? { Code?: ResponseCodeSuccess; Item?: ItemRevisionContentsResponse }
: never
: Path extends `pass/v1/share/${string}/item/${string}/lastuse`
? Method extends `put`
? { Code?: ResponseCodeSuccess; Revision?: ItemRevisionContentsResponse }
: never
: Path extends `pass/v1/share/${string}/item/${string}/key/latest`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Key?: ItemLatestKeyResponse }
: never
: Path extends `pass/v1/share/${string}/item/${string}/key`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Keys?: ItemGetKeysResponse }
: never
: Path extends `pass/v1/share/${string}/item/${string}`
? Method extends `put`
? { Code?: ResponseCodeSuccess; Item?: ItemRevisionContentsResponse }
: never
: Path extends `pass/v1/share/${string}/item`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Items?: ItemRevisionListResponse }
: Method extends `post`
? { Code?: ResponseCodeSuccess; Item?: ItemRevisionContentsResponse }
: Method extends `delete`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/invite/new_user/${string}/keys`
? Method extends `post`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/invite/new_user/${string}`
? Method extends `delete`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/invite/new_user`
? Method extends `post`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/invite/${string}/reminder`
? Method extends `post`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/invite/${string}`
? Method extends `delete`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/invite`
? Method extends `get`
? InvitesForVaultGetResponse & { Code?: ResponseCodeSuccess }
: Method extends `post`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/event/${string}`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Events?: PassEventListResponse }
: never
: Path extends `pass/v1/share/${string}/event`
? Method extends `get`
? EventIDGetResponse & { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share/${string}/alias/random`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Item?: ItemRevisionContentsResponse }
: never
: Path extends `pass/v1/share/${string}/alias/options`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Options?: AliasOptionsResponse }
: never
: Path extends `pass/v1/share/${string}/alias/custom`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Item?: ItemRevisionContentsResponse }
: never
: Path extends `pass/v1/share/${string}/alias/${string}/mailbox`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Item?: AliasDetailsResponse }
: never
: Path extends `pass/v1/share/${string}/alias/${string}`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Item?: AliasDetailsResponse }
: never
: Path extends `pass/v1/share/${string}`
? Method extends `get`
? { Code?: ResponseCodeSuccess; Share?: ShareGetResponse }
: Method extends `delete`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/share`
? Method extends `get`
? SharesGetResponse & { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/invite/${string}`
? Method extends `post`
? { Code?: ResponseCodeSuccess; Share?: ShareGetResponse }
: Method extends `delete`
? { Code?: ResponseCodeSuccess }
: never
: Path extends `pass/v1/invite`
? Method extends `get`
? InvitesGetResponse & { Code?: ResponseCodeSuccess }
: never
: any;
export type ApiRequest<Path extends string, Method extends ApiMethod> = Path extends `pass/v1/vault/${string}/primary`
? Method extends `put`
? never
: never
: Path extends `pass/v1/vault/${string}/owner`
? Method extends `put`
? VaultTransferOwnershipRequest
: never
: Path extends `pass/v1/vault/${string}`
? Method extends `put`
? VaultUpdateRequest
: Method extends `delete`
? never
: never
: Path extends `pass/v1/vault`
? Method extends `post`
? VaultCreateRequest
: never
: Path extends `pass/v1/user/session/lock/unlock`
? Method extends `post`
? UserSessionUnlockRequest
: never
: Path extends `pass/v1/user/session/lock/force_lock`
? Method extends `post`
? never
: never
: Path extends `pass/v1/user/session/lock/check`
? Method extends `get`
? never
: never
: Path extends `pass/v1/user/session/lock`
? Method extends `post`
? UserSessionLockRequest
: Method extends `delete`
? UserSessionUnlockRequest
: never
: Path extends `pass/v1/user/missing_alias`
? Method extends `get`
? never
: never
: Path extends `pass/v1/user/access/check`
? Method extends `get`
? never
: never
: Path extends `pass/v1/user/access`
? Method extends `get`
? never
: Method extends `post`
? never
: never
: Path extends `pass/v1/share/${string}/user/${string}`
? Method extends `get`
? never
: Method extends `put`
? ShareUpdateRequest
: Method extends `delete`
? never
: never
: Path extends `pass/v1/share/${string}/user`
? Method extends `get`
? never
: never
: Path extends `pass/v1/share/${string}/key/pending`
? Method extends `get`
? never
: Method extends `post`
? PendingShareKeyPromoteRequest
: never
: Path extends `pass/v1/share/${string}/key`
? Method extends `get`
? never
: Method extends `post`
? KeyRotationRequest
: never
: Path extends `pass/v1/share/${string}/item/with_alias`
? Method extends `post`
? AliasAndItemCreateRequest
: never
: Path extends `pass/v1/share/${string}/item/untrash`
? Method extends `post`
? ItemsToTrashRequest
: never
: Path extends `pass/v1/share/${string}/item/trash`
? Method extends `post`
? { ''?: ItemsToTrashRequest }
: never
: Path extends `pass/v1/share/${string}/item/share`
? Method extends `put`
? ItemMoveMultipleToShareRequest
: never
: Path extends `pass/v1/share/${string}/item/import/batch`
? Method extends `post`
? ImportItemBatchRequest
: never
: Path extends `pass/v1/share/${string}/item/${string}/share`
? Method extends `put`
? ItemMoveSingleToShareRequest
: never
: Path extends `pass/v1/share/${string}/item/${string}/revision`
? Method extends `get`
? never
: never
: Path extends `pass/v1/share/${string}/item/${string}/pin`
? Method extends `post`
? never
: Method extends `delete`
? never
: never
: Path extends `pass/v1/share/${string}/item/${string}/lastuse`
? Method extends `put`
? UpdateItemLastUseTimeRequest
: never
: Path extends `pass/v1/share/${string}/item/${string}/key/latest`
? Method extends `get`
? never
: never
: Path extends `pass/v1/share/${string}/item/${string}/key`
? Method extends `get`
? never
: never
: Path extends `pass/v1/share/${string}/item/${string}`
? Method extends `put`
? ItemUpdateRequest
: never
: Path extends `pass/v1/share/${string}/item`
? Method extends `get`
? never
: Method extends `post`
? ItemCreateRequest
: Method extends `delete`
? ItemsToSoftDeleteRequest
: never
: Path extends `pass/v1/share/${string}/invite/new_user/${string}/keys`
? Method extends `post`
? NewUserInvitePromoteRequest
: never
: Path extends `pass/v1/share/${string}/invite/new_user/${string}`
? Method extends `delete`
? never
: never
: Path extends `pass/v1/share/${string}/invite/new_user`
? Method extends `post`
? NewUserInviteCreateRequest
: never
: Path extends `pass/v1/share/${string}/invite/${string}/reminder`
? Method extends `post`
? never
: never
: Path extends `pass/v1/share/${string}/invite/${string}`
? Method extends `delete`
? never
: never
: Path extends `pass/v1/share/${string}/invite`
? Method extends `get`
? never
: Method extends `post`
? InviteCreateRequest
: never
: Path extends `pass/v1/share/${string}/event/${string}`
? Method extends `get`
? never
: never
: Path extends `pass/v1/share/${string}/event`
? Method extends `get`
? never
: never
: Path extends `pass/v1/share/${string}/alias/random`
? Method extends `post`
? ItemCreateRequest
: never
: Path extends `pass/v1/share/${string}/alias/options`
? Method extends `get`
? never
: never
: Path extends `pass/v1/share/${string}/alias/custom`
? Method extends `post`
? CustomAliasCreateRequest
: never
: Path extends `pass/v1/share/${string}/alias/${string}/mailbox`
? Method extends `post`
? SetAliasMailboxesRequest
: never
: Path extends `pass/v1/share/${string}/alias/${string}`
? Method extends `get`
? never
: never
: Path extends `pass/v1/share/${string}`
? Method extends `get`
? never
: Method extends `delete`
? never
: never
: Path extends `pass/v1/share`
? Method extends `get`
? never
: never
: Path extends `pass/v1/invite/${string}`
? Method extends `post`
? InviteAcceptRequest
: Method extends `delete`
? never
: never
: Path extends `pass/v1/invite`
? Method extends `get`
? never
: never
: any;
| 8,082
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/api/plan.ts
|
import { PlanType } from './pass';
export enum UserPassPlan {
FREE = PlanType.free,
PLUS = PlanType.plus,
TRIAL = 'trial',
}
| 8,083
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/api/session-lock.ts
|
export enum SessionLockStatus {
LOCKED = 'LOCKED',
REGISTERED = 'REGISTERED',
NONE = 'NONE',
}
| 8,084
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/browser/index.ts
|
export type Browser = 'chrome' | 'firefox';
| 8,085
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/crypto/index.ts
|
export * from './pass-crypto';
export * from './pass-types';
| 8,086
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/crypto/pass-crypto.ts
|
import type {
InviteAcceptRequest,
InviteCreateRequest,
ItemCreateRequest,
ItemKeyResponse,
ItemMoveSingleToShareRequest,
ItemRevisionContentsResponse,
ItemUpdateRequest,
KeyRotationKeyPair,
NewUserInviteCreateRequest,
NewUserInvitePromoteRequest,
ShareGetResponse,
ShareKeyResponse,
VaultCreateRequest,
VaultUpdateRequest,
} from '@proton/pass/types/api';
import type { ShareRole, ShareType } from '@proton/pass/types/data/shares';
import type { MaybeNull } from '@proton/pass/types/utils';
import type { Address, DecryptedKey, User } from '@proton/shared/lib/interfaces';
import type { ItemKey, OpenedItem, Rotation, ShareId, TypedOpenedShare, VaultKey } from './pass-types';
export type PassCryptoManagerContext = {
user?: User;
userKeys?: DecryptedKey[];
addresses?: Address[];
primaryUserKey?: DecryptedKey;
primaryAddress?: Address;
shareManagers: Map<ShareId, ShareManager>;
};
export type PassCryptoSnapshot = Pick<PassCryptoManagerContext, 'shareManagers'>;
export interface PassCryptoWorker extends SerializableCryptoContext<PassCryptoSnapshot> {
getContext: () => PassCryptoManagerContext;
hydrate: (data: {
addresses: Address[];
keyPassword: string;
snapshot?: SerializedCryptoContext<PassCryptoSnapshot>;
user: User;
}) => Promise<void>;
clear: () => void;
getShareManager: (shareId: string) => ShareManager;
createVault: (content: Uint8Array) => Promise<VaultCreateRequest>;
updateVault: (data: { shareId: string; content: Uint8Array }) => Promise<VaultUpdateRequest>;
canOpenShare: (shareId: string) => boolean;
openShare: <T extends ShareType = ShareType>(data: {
encryptedShare: ShareGetResponse;
shareKeys: ShareKeyResponse[];
}) => Promise<MaybeNull<TypedOpenedShare<T>>>;
updateShareKeys: (data: { shareId: string; shareKeys: ShareKeyResponse[] }) => Promise<void>;
removeShare: (shareId: string) => void;
openItem: (data: { shareId: string; encryptedItem: ItemRevisionContentsResponse }) => Promise<OpenedItem>;
createItem: (data: { shareId: string; content: Uint8Array }) => Promise<ItemCreateRequest>;
updateItem: (data: {
content: Uint8Array;
lastRevision: number;
latestItemKey: ItemKeyResponse;
shareId: string;
}) => Promise<ItemUpdateRequest>;
moveItem: (data: { destinationShareId: string; content: Uint8Array }) => Promise<ItemMoveSingleToShareRequest>;
createVaultInvite: (data: {
email: string;
invitedPublicKey: string;
role: ShareRole;
shareId: string;
}) => Promise<InviteCreateRequest>;
promoteInvite: (data: { shareId: string; invitedPublicKey: string }) => Promise<NewUserInvitePromoteRequest>;
createNewUserVaultInvite: (data: {
email: string;
role: ShareRole;
shareId: string;
}) => Promise<NewUserInviteCreateRequest>;
acceptVaultInvite: (data: {
invitedAddressId: string;
inviteKeys: KeyRotationKeyPair[];
inviterPublicKeys: string[];
}) => Promise<InviteAcceptRequest>;
readVaultInvite: (data: {
encryptedVaultContent: string;
invitedAddressId: string;
inviteKey: KeyRotationKeyPair;
inviterPublicKeys: string[];
}) => Promise<Uint8Array>;
}
export type ShareContext<T extends ShareType = ShareType> = {
share: TypedOpenedShare<T>;
latestRotation: Rotation;
vaultKeys: Map<Rotation, VaultKey>;
itemKeys: Map<Rotation, ItemKey>;
};
export interface ShareManager<T extends ShareType = ShareType> extends SerializableCryptoContext<ShareContext> {
getShare: () => TypedOpenedShare<T>;
setShare: (share: TypedOpenedShare<T>) => void;
getLatestRotation: () => Rotation;
setLatestRotation: (rotation: Rotation) => void;
hasVaultKey: (rotation: Rotation) => boolean;
getVaultKey: (rotation: Rotation) => VaultKey;
getVaultKeys: () => VaultKey[];
addVaultKey: (vaultKey: VaultKey) => void;
isActive: (userKeys?: DecryptedKey[]) => boolean;
}
export interface SerializableCryptoContext<S> {
serialize: () => SerializedCryptoContext<S>;
}
export type SerializedCryptoContext<T> = T extends SerializableCryptoContext<infer U>
? SerializedCryptoContext<U>
: T extends Uint8Array
? string
: T extends Map<infer K, infer U>
? (readonly [K, SerializedCryptoContext<U>])[]
: T extends (infer U)[]
? SerializedCryptoContext<U>[]
: T extends {}
? { [K in keyof T as T[K] extends CryptoKey ? never : K]: SerializedCryptoContext<T[K]> }
: T;
| 8,087
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/crypto/pass-types.ts
|
import type { ItemState, Maybe, MaybeNull, ShareRole, ShareType } from '@proton/pass/types';
export enum PassEncryptionTag {
Cache = 'cache' /* web-only usage */,
ItemContent = 'itemcontent',
ItemKey = 'itemkey',
VaultContent = 'vaultcontent',
}
export enum PassSignatureContext {
VaultInviteExistingUser = 'pass.invite.vault.existing-user',
VaultInviteNewUser = 'pass.invite.vault.new-user',
}
export const CONTENT_FORMAT_VERSION = 1;
/* type aliases */
export type Rotation = number;
export type ShareId = string;
export type RotationKey = {
key: CryptoKey;
raw: Uint8Array;
rotation: Rotation;
};
export type VaultKey = RotationKey & { userKeyId: Maybe<string> };
export type ItemKey = RotationKey;
type OpenedShareBase = {
addressId: string;
createTime: number;
expireTime?: MaybeNull<number>;
newUserInvitesReady: number;
owner: boolean;
permission: number;
shared: boolean;
shareId: string;
shareRoleId: ShareRole;
targetId: string;
targetMaxMembers: number;
targetMembers: number;
vaultId: string;
};
export type OpenedShare = OpenedShareBase &
(
| {
content: Uint8Array;
contentFormatVersion: number;
contentKeyRotation: Rotation;
targetType: ShareType.Vault;
}
| {
content: null;
contentFormatVersion: null;
contentKeyRotation: null;
targetType: ShareType.Item;
}
);
export type TypedOpenedShare<T extends ShareType> = Extract<OpenedShare, { targetType: T }>;
export type OpenedItem = {
aliasEmail: MaybeNull<string>;
content: Uint8Array;
contentFormatVersion: number;
createTime: number;
itemId: string;
lastUseTime: MaybeNull<number>;
modifyTime: number;
revision: number;
revisionTime: number;
state: ItemState;
};
| 8,088
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/alias.ts
|
export type AliasMailbox = { email: string; id: number };
export type AliasSuffix = {
suffix: string;
signedSuffix: string;
isCustom: boolean;
domain: string;
};
| 8,089
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/index.ts
|
export * from './alias';
export * from './invites';
export * from './items';
export * from './items.dto';
export * from './labels';
export * from './shares';
export * from './vault.dto';
| 8,090
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/invites.dto.ts
|
import type { ItemRevision, SelectedItem } from '@proton/pass/types/data/items';
import type { Share, ShareRole, ShareType } from '@proton/pass/types/data/shares';
import type { KeyRotationKeyPair } from '../api';
export type NewUserInvitePromoteIntent = { newUserInviteId: string; shareId: string };
export type NewUserInviteRemoveIntent = { newUserInviteId: string; shareId: string };
export type InviteCreateIntent = { shareId: string; email: string; role: ShareRole };
export type InviteCreateSuccess =
| {
item: SelectedItem;
movedItem: ItemRevision;
share: Share<ShareType.Vault>;
shareId: string;
withVaultCreation: true;
}
| { shareId: string; withVaultCreation: false };
export type InviteResendIntent = { shareId: string; inviteId: string };
export type InviteRemoveIntent = { shareId: string; inviteId: string };
export type InviteRejectIntent = { inviteToken: string };
export type InviteAcceptIntent = {
invitedAddressId: string;
inviteKeys: KeyRotationKeyPair[];
inviterEmail: string;
inviteToken: string;
};
| 8,091
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/invites.ts
|
import type { KeyRotationKeyPair } from '../api';
import { type MaybeNull } from '../utils';
import type { ShareRole, ShareType, VaultShareContent } from './shares';
export enum NewUserInviteState {
WAITING = 1,
READY = 2,
}
export type InviteBase = {
createTime: number;
invitedEmail: string;
inviterEmail: string;
targetId: string;
targetType: ShareType;
};
export type PendingInvite = InviteBase & {
inviteId: string;
modifyTime: number;
remindersSent: number;
};
export type NewUserPendingInvite = InviteBase & {
newUserInviteId: string;
signature: string;
state: NewUserInviteState;
};
export type InviteVaultData = {
content: VaultShareContent;
itemCount: number;
memberCount: number;
};
export type Invite = InviteBase & {
fromNewUser: boolean;
invitedAddressId: string;
keys: KeyRotationKeyPair[];
remindersSent: number;
token: string;
vault: InviteVaultData;
};
export type ShareMember = {
createTime: number;
email: string;
expireTime?: MaybeNull<number>;
name: string;
owner: boolean;
shareId: string;
shareRoleId: ShareRole;
targetId: string;
targetType: ShareType;
};
| 8,092
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/items.dto.ts
|
import type { CustomAliasCreateRequest } from '../api';
import type { ItemType } from '../protobuf';
import type { Item } from './items';
type AliasMailbox = {
id: number;
email: string;
};
export type AliasCreationDTO = {
mailboxes: AliasMailbox[];
prefix: CustomAliasCreateRequest['Prefix'];
signedSuffix: CustomAliasCreateRequest['SignedSuffix'];
aliasEmail: string;
};
export type LoginWithAliasCreationDTO = { withAlias: true; alias: ItemCreateIntent<'alias'> } | { withAlias: false };
/**
* Item creation DTO indexed on ItemType keys
* - alias specifics : extra parameters required for alias creation
* - login specifics : support login with alias creation intent
*/
export type ItemCreateIntentDTO = {
alias: AliasCreationDTO;
login: LoginWithAliasCreationDTO;
note: never;
};
export type ItemEditIntentDTO = {
alias: { aliasOwner: boolean; mailboxes: AliasMailbox[]; aliasEmail: string };
login: never;
note: never;
};
export type ItemImportIntentDTO = {
alias: { aliasEmail: string };
login: never;
note: never;
};
/* Intent payloads */
export type ItemCreateIntent<T extends ItemType = ItemType> = Item<T, ItemCreateIntentDTO> & {
optimisticId: string;
shareId: string;
createTime: number;
};
export type ItemEditIntent<T extends ItemType = ItemType> = Item<T, ItemEditIntentDTO> & {
itemId: string;
shareId: string;
lastRevision: number;
};
export type ItemImportIntent<T extends ItemType = ItemType> = Item<T, ItemImportIntentDTO> & {
trashed: boolean;
createTime?: number;
modifyTime?: number;
};
| 8,093
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/items.ts
|
import { type XorObfuscation } from '@proton/pass/utils/obfuscate/xor';
import type { OpenedItem } from '../crypto';
import type {
ExtraFieldType,
ItemType,
Metadata,
ProtobufItemAlias,
ProtobufItemCreditCard,
ProtobufItemLogin,
ProtobufItemNote,
} from '../protobuf';
import type { ExtraHiddenField, ExtraTotp, PlatformSpecific } from '../protobuf/item-v1';
import type { MaybeNull } from '../utils';
type Obfuscate<T, K extends keyof T> = Omit<T, K> & { [Obf in K]: XorObfuscation };
type Deobfuscate<T> = {
[K in keyof T]: T[K] extends XorObfuscation ? string : T[K] extends {} ? Deobfuscate<T[K]> : T[K];
};
type ExtraFieldContent<T extends ExtraFieldType> = {
totp: Obfuscate<ExtraTotp, 'totpUri'>;
text: Obfuscate<ExtraHiddenField, 'content'>;
hidden: Obfuscate<ExtraHiddenField, 'content'>;
}[T];
export type ItemContent<T extends ItemType> = {
alias: ProtobufItemAlias;
note: ProtobufItemNote;
login: Obfuscate<ProtobufItemLogin, 'username' | 'password' | 'totpUri'>;
creditCard: Obfuscate<ProtobufItemCreditCard, 'number' | 'verificationNumber' | 'pin'>;
}[T];
export type UnsafeItemContent<T extends ItemType = ItemType> = Deobfuscate<ItemContent<T>>;
export type ItemExtraField<T extends ExtraFieldType = ExtraFieldType> = {
[Key in T]: {
fieldName: string;
type: Key;
data: ExtraFieldContent<Key>;
};
}[T];
export type UnsafeItemExtraField<T extends ExtraFieldType = ExtraFieldType> = Deobfuscate<ItemExtraField<T>>;
/**
* Derives a generic "distributive object type" over all possible
* oneofKind keys - This will allow us to create generic functions
* and "object mappers" over every item type derived from the original
* protoc-gen-ts generated types
*
* Item types can be extended via an "Extra" type (an object type indexed
* on ItemType keys) - this will let us create "qualified" generics over
* the base Item type (see ./items.dto.ts for an example)
*/
export type Item<T extends ItemType = ItemType, ExtraData extends { [K in T]?: any } = never> = {
[Key in T]: {
type: Key;
content: ItemContent<Key>;
platformSpecific?: PlatformSpecific;
extraFields: ItemExtraField[];
metadata: Obfuscate<Metadata, 'note'>;
} & (ExtraData[Key] extends never ? {} : { extraData: ExtraData[Key] });
}[T];
export type UnsafeItem<T extends ItemType = ItemType> = Deobfuscate<Item<T>>;
export enum ItemState {
Active = 1,
Trashed = 2,
}
export type ItemRevision<T extends ItemType = ItemType> = Omit<OpenedItem, 'content'> & {
data: Item<T>;
shareId: string;
};
export type UnsafeItemRevision<T extends ItemType = ItemType> = Deobfuscate<ItemRevision<T>>;
/**
* Adds an optimistic & failed property to
* the ItemRevision type
*/
export type ItemRevisionWithOptimistic<T extends ItemType = ItemType> = ItemRevision<T> & {
optimistic: boolean;
failed: boolean;
};
/**
* Generic utility type to construct
* item key mappers over the different item types
*/
export type ItemMap<T> = { [type in ItemType]: T };
export type UniqueItem = { shareId: string; itemId: string };
export type SelectedItem = UniqueItem;
export type ItemSortFilter = 'recent' | 'titleASC' | 'createTimeDESC' | 'createTimeASC';
export type ItemTypeFilter = '*' | ItemType;
export type ItemFilters = {
search: string;
selectedShareId: MaybeNull<string>;
sort: ItemSortFilter;
type: ItemTypeFilter;
};
| 8,094
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/labels.ts
|
export interface Label {
labelId: string;
content: Uint8Array;
createTime: number;
modifyTime: number;
}
| 8,095
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/pass-icon.ts
|
import type { IconName } from '@proton/components/components';
export enum PassIconStatus {
ACTIVE = 'protonpass-icon-active',
DISABLED = 'protonpass-icon-disabled',
LOCKED = 'protonpass-icon-locked',
LOCKED_DROPDOWN = 'protonpass-icon-locked-dropdown',
}
const PassIconStatusValues = Object.values(PassIconStatus) as string[];
export const isPassIcon = (icon: PassIconStatus | string): icon is PassIconStatus =>
PassIconStatusValues.includes(icon);
export type DropdownIcon = IconName | PassIconStatus;
| 8,096
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/shares.dto.ts
|
import type { NewUserPendingInvite, PendingInvite, ShareMember } from './invites';
import type { ShareRole } from './shares';
export type ShareRemoveMemberAccessIntent = { shareId: string; userShareId: string };
export type ShareEditMemberAccessIntent = { shareId: string; userShareId: string; shareRoleId: ShareRole };
export type ShareAccessOptions = {
shareId: string;
invites: PendingInvite[];
newUserInvites: NewUserPendingInvite[];
members: ShareMember[];
};
| 8,097
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/shares.ts
|
import type { VaultColor, VaultIcon } from '../protobuf/vault-v1';
export enum ShareType {
Vault = 1,
Item = 2,
}
export enum ShareRole {
ADMIN = '1',
WRITE = '2',
READ = '3',
}
export type VaultShareContent = {
description: string;
display: { icon?: VaultIcon; color?: VaultColor };
name: string;
};
export type ItemShareContent = {};
export type ShareContent<T extends ShareType = ShareType> = T extends ShareType.Vault
? VaultShareContent
: T extends ShareType.Item
? ItemShareContent
: never;
export type ShareBase<T extends ShareType = ShareType> = {
content: ShareContent<T>;
createTime: number;
newUserInvitesReady: number;
owner: boolean;
shared: boolean;
shareId: string;
shareRoleId: ShareRole;
targetId: string;
targetMaxMembers: number;
targetMembers: number;
targetType: T;
vaultId: string;
};
export type WithEventId<T> = T & { eventId: string };
export type Share<T extends ShareType = ShareType> = WithEventId<ShareBase<T>>;
export type ShareAccessKeys =
| 'newUserInvitesReady'
| 'owner'
| 'shared'
| 'shareId'
| 'shareRoleId'
| 'targetMaxMembers'
| 'targetMembers';
| 8,098
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/types
|
petrpan-code/ProtonMail/WebClients/packages/pass/types/data/telemetry.ts
|
import type { ImportProvider } from '@proton/pass/lib/import/types';
import type { PassPlanResponse } from '@proton/pass/types';
import type { ItemType } from '../protobuf';
export type TelemetryPlatform = 'browser' | 'any';
export enum TelemetryEventName {
ItemCreation = 'item.creation',
ItemUpdate = 'item.update',
ItemRead = 'item.read',
ItemDeletion = 'item.deletion',
AutosuggestAliasCreated = 'autosuggest.alias_created',
ImportCompletion = 'import.complete',
AutosaveDone = 'autosave.done',
AutosaveDisplay = 'autosave.display',
AutofillDisplay = 'autofill.display',
AutofillTriggered = 'autofill.triggered',
SearchTriggered = 'search.triggered',
SearchClick = 'search.click',
TwoFAAutofill = '2fa.autofill',
TwoFADisplay = '2fa.display',
TwoFACreation = '2fa.creation',
TwoFAUpdate = '2fa.update',
}
type BaseTelemetryEvent<T extends TelemetryEventName, V = {}, D = {}> = {
MeasurementGroup: `pass.${TelemetryPlatform}.user_actions`;
Event: T;
Values: V;
Dimensions: { user_tier?: PassPlanResponse['InternalName'] } & D;
} & T;
type AutofillSource = 'source' | 'app';
export type TelemetryEvent<T extends TelemetryEventName = TelemetryEventName> = Extract<
{
[TelemetryEventName.ItemCreation]: BaseTelemetryEvent<T, {}, { type: ItemType }>;
[TelemetryEventName.ItemUpdate]: BaseTelemetryEvent<T, {}, { type: ItemType }>;
[TelemetryEventName.ItemRead]: BaseTelemetryEvent<T, {}, { type: ItemType }>;
[TelemetryEventName.ItemDeletion]: BaseTelemetryEvent<T, {}, { type: ItemType }>;
[TelemetryEventName.AutosuggestAliasCreated]: BaseTelemetryEvent<T>;
[TelemetryEventName.AutosaveDisplay]: BaseTelemetryEvent<T>;
[TelemetryEventName.AutosaveDone]: BaseTelemetryEvent<T>;
[TelemetryEventName.AutofillDisplay]: BaseTelemetryEvent<T, {}, { location: AutofillSource }>;
[TelemetryEventName.AutofillTriggered]: BaseTelemetryEvent<T, {}, { location: AutofillSource }>;
[TelemetryEventName.SearchTriggered]: BaseTelemetryEvent<T>;
[TelemetryEventName.SearchClick]: BaseTelemetryEvent<T>;
[TelemetryEventName.ImportCompletion]: BaseTelemetryEvent<
T,
{ item_count: number; vaults: number },
{ source: ImportProvider }
>;
[TelemetryEventName.TwoFAAutofill]: BaseTelemetryEvent<T>;
[TelemetryEventName.TwoFADisplay]: BaseTelemetryEvent<T>;
[TelemetryEventName.TwoFACreation]: BaseTelemetryEvent<T>;
[TelemetryEventName.TwoFAUpdate]: BaseTelemetryEvent<T>;
}[T],
T
>;
| 8,099
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.