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/docs
|
petrpan-code/ProtonMail/WebClients/packages/pass/docs/extension/coms.md
|
# Communication Layer
| 7,700
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/docs
|
petrpan-code/ProtonMail/WebClients/packages/pass/docs/extension/quickstart.md
|
# Quickstart
### Environment variables
| Name | Values | Default | Dev only |
| ----------------------------------- | --------------------------------- | ----------------------- | -------- |
| **ENV** | `"development"` \| `"production"` | `"development"` | ❌ |
| **BUILD_TARGET** | `"chrome"` \| `"firefox"` | `"chrome"` | ❌ |
| **RESUME_FALLBACK**<sup>1</sup> | boolean | `ENV === "development"` | ✅ |
| **REDUX_DEVTOOLS_PORT** | number | `8000` | ✅ |
| **WEBPACK_DEV_PORT** | number | `8090` | ✅ |
| **RUNTIME_RELOAD**<sup>2</sup> | boolean | `false` | ✅ |
| **RUNTIME_RELOAD_PORT** | number | `8080` | ✅ |
| **HOT_MANIFEST_UPDATE**<sup>3</sup> | boolean | `false` | ✅ |
> <sup>1</sup> `RESUME_FALLBACK` allows by-passing SSL errors when using staging endpoints on extension start-up
> <sup>2</sup> `RUNTIME_RELOAD` allows reloading the extension on code update
> <sup>3</sup> `HOT_MANIFEST_UPDATE` will increment the extension version on code update
### Development
```bash
yarn start
yarn start:reload
```
> if the above commands fail, run `yarn workspace @proton/pass install:additional-tools`
| 7,701
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/fathom/fathom.js
|
/**
* A :func:`rule` depends on another rule which itself depends on the first
* rule again, either directly or indirectly.
*/
class CycleError extends Error {}
/**
* An examined element was not contained in a browser ``window`` object, but
* something needed it to be.
*/
class NoWindowError extends Error {}
var exceptions = /*#__PURE__*/ Object.freeze({
__proto__: null,
CycleError: CycleError,
NoWindowError: NoWindowError,
});
/**
* Return the passed-in arg. Useful as a default.
*/
function identity(x) {
return x;
}
/*eslint-env browser*/
/**
* From an iterable return the best item, according to an arbitrary comparator
* function. In case of a tie, the first item wins.
*
* @arg by {function} Given an item of the iterable, return a value to compare
* @arg isBetter {function} Return whether its first arg is better than its
* second
*/
function best(iterable, by, isBetter) {
let bestSoFar, bestKeySoFar;
let isFirst = true;
forEach(function (item) {
const key = by(item);
if (isBetter(key, bestKeySoFar) || isFirst) {
bestSoFar = item;
bestKeySoFar = key;
isFirst = false;
}
}, iterable);
if (isFirst) {
throw new Error('Tried to call best() on empty iterable');
}
return bestSoFar;
}
/**
* Return the maximum item from an iterable, as defined by >.
*
* Works with any type that works with >. If multiple items are equally great,
* return the first.
*
* @arg by {function} Given an item of the iterable, returns a value to
* compare
*/
function max(iterable, by = identity) {
return best(iterable, by, (a, b) => a > b);
}
/**
* Return an Array of maximum items from an iterable, as defined by > and ===.
*
* If an empty iterable is passed in, return [].
*/
function maxes(iterable, by = identity) {
let bests = [];
let bestKeySoFar;
let isFirst = true;
forEach(function (item) {
const key = by(item);
if (key > bestKeySoFar || isFirst) {
bests = [item];
bestKeySoFar = key;
isFirst = false;
} else if (key === bestKeySoFar) {
bests.push(item);
}
}, iterable);
return bests;
}
/**
* Return the minimum item from an iterable, as defined by <.
*
* If multiple items are equally great, return the first.
*/
function min(iterable, by = identity) {
return best(iterable, by, (a, b) => a < b);
}
/**
* Return the sum of an iterable, as defined by the + operator.
*/
function sum(iterable) {
let total;
let isFirst = true;
forEach(function assignOrAdd(addend) {
if (isFirst) {
total = addend;
isFirst = false;
} else {
total += addend;
}
}, iterable);
return total;
}
/**
* Return the number of items in an iterable, consuming it as a side effect.
*/
function length(iterable) {
let num = 0;
// eslint-disable-next-line no-unused-vars
for (let item of iterable) {
num++;
}
return num;
}
/**
* Iterate, depth first, over a DOM node. Return the original node first.
*
* @arg shouldTraverse {function} Given a node, say whether we should
* include it and its children. Default: always true.
*/
function* walk(element, shouldTraverse = (element) => true) {
yield element;
for (let child of element.childNodes) {
if (shouldTraverse(child)) {
for (let w of walk(child, shouldTraverse)) {
yield w;
}
}
}
}
const blockTags = new Set([
'ADDRESS',
'BLOCKQUOTE',
'BODY',
'CENTER',
'DIR',
'DIV',
'DL',
'FIELDSET',
'FORM',
'H1',
'H2',
'H3',
'H4',
'H5',
'H6',
'HR',
'ISINDEX',
'MENU',
'NOFRAMES',
'NOSCRIPT',
'OL',
'P',
'PRE',
'TABLE',
'UL',
'DD',
'DT',
'FRAMESET',
'LI',
'TBODY',
'TD',
'TFOOT',
'TH',
'THEAD',
'TR',
'HTML',
]);
/**
* Return whether a DOM element is a block element by default (rather than by
* styling).
*/
function isBlock(element) {
return blockTags.has(element.tagName);
}
/**
* Yield strings of text nodes within a normalized DOM node and its children,
* without venturing into any contained block elements.
*
* @arg shouldTraverse {function} Specify additional elements to exclude by
* returning false
*/
function* inlineTexts(element, shouldTraverse = (element) => true) {
// TODO: Could we just use querySelectorAll() with a really long
// selector rather than walk(), for speed?
for (let child of walk(
element,
(element) =>
!(isBlock(element) || (element.tagName === 'SCRIPT' && element.tagName === 'STYLE')) &&
shouldTraverse(element)
)) {
if (child.nodeType === child.TEXT_NODE) {
// wholeText() is not implemented by jsdom, so we use
// textContent(). The result should be the same, since
// we're calling it on only text nodes, but it may be
// slower. On the positive side, it means we don't need to
// normalize the DOM tree first.
yield child.textContent;
}
}
}
/**
* Return the total length of the inline text within an element, with
* whitespace collapsed.
*
* @arg shouldTraverse {function} Specify additional elements to exclude by
* returning false
*/
function inlineTextLength(element, shouldTraverse = (element) => true) {
return sum(map((text) => collapseWhitespace(text).length, inlineTexts(element, shouldTraverse)));
}
/**
* Return a string with each run of whitespace collapsed to a single space.
*/
function collapseWhitespace(str) {
return str.replace(/\s{2,}/g, ' ');
}
/**
* Return the ratio of the inline text length of the links in an element to the
* inline text length of the entire element.
*
* @arg inlineLength {number} Optionally, the precalculated inline
* length of the fnode. If omitted, we will calculate it ourselves.
*/
function linkDensity(fnode, inlineLength) {
if (inlineLength === undefined) {
inlineLength = inlineTextLength(fnode.element);
}
const lengthWithoutLinks = inlineTextLength(fnode.element, (element) => element.tagName !== 'A');
return (inlineLength - lengthWithoutLinks) / inlineLength;
}
/**
* Return whether an element is a text node that consist wholly of whitespace.
*/
function isWhitespace(element) {
return element.nodeType === element.TEXT_NODE && element.textContent.trim().length === 0;
}
/**
* Get a key of a map, first setting it to a default value if it's missing.
*/
function setDefault(map, key, defaultMaker) {
if (map.has(key)) {
return map.get(key);
}
const defaultValue = defaultMaker();
map.set(key, defaultValue);
return defaultValue;
}
/**
* Get a key of a map or, if it's missing, a default value.
*/
function getDefault(map, key, defaultMaker) {
if (map.has(key)) {
return map.get(key);
}
return defaultMaker();
}
/**
* Return an Array, the reverse topological sort of the given nodes.
*
* @arg nodes An iterable of arbitrary things
* @arg nodesThatNeed {function} Take a node and returns an Array of nodes
* that depend on it
*/
function toposort(nodes, nodesThatNeed) {
const ret = [];
const todo = new Set(nodes);
const inProgress = new Set();
function visit(node) {
if (inProgress.has(node)) {
throw new CycleError('The graph has a cycle.');
}
if (todo.has(node)) {
inProgress.add(node);
for (let needer of nodesThatNeed(node)) {
visit(needer);
}
inProgress.delete(node);
todo.delete(node);
ret.push(node);
}
}
while (todo.size > 0) {
visit(first(todo));
}
return ret;
}
/**
* A Set with the additional methods it ought to have had
*/
class NiceSet extends Set {
/**
* Remove and return an arbitrary item. Throw an Error if I am empty.
*/
pop() {
for (let v of this.values()) {
this.delete(v);
return v;
}
throw new Error('Tried to pop from an empty NiceSet.');
}
/**
* Union another set or other iterable into myself.
*
* @return myself, for chaining
*/
extend(otherSet) {
for (let item of otherSet) {
this.add(item);
}
return this;
}
/**
* Subtract another set from a copy of me.
*
* @return a copy of myself excluding the elements in ``otherSet``.
*/
minus(otherSet) {
const ret = new NiceSet(this);
for (const item of otherSet) {
ret.delete(item);
}
return ret;
}
/**
* Actually show the items in me.
*/
toString() {
return '{' + Array.from(this).join(', ') + '}';
}
}
/**
* Return the first item of an iterable.
*/
function first(iterable) {
for (let i of iterable) {
return i;
}
}
/**
* Given any node in a DOM tree, return the root element of the tree, generally
* an HTML element.
*/
function rootElement(element) {
return element.ownerDocument.documentElement;
}
/**
* Return the number of times a regex occurs within the string `haystack`.
*
* Caller must make sure `regex` has the 'g' option set.
*/
function numberOfMatches(regex, haystack) {
return (haystack.match(regex) || []).length;
}
/**
* Wrap a scoring callback, and set its element to the page root iff a score is
* returned.
*
* This is used to build rulesets which classify entire pages rather than
* picking out specific elements.
*
* For example, these rules might classify a page as a "login page", influenced
* by whether they have login buttons or username fields:
*
* ``rule(type('loginPage'), score(page(pageContainsLoginButton))),``
* ``rule(type('loginPage'), score(page(pageContainsUsernameField)))``
*/
function page(scoringFunction) {
function wrapper(fnode) {
const scoreAndTypeAndNote = scoringFunction(fnode);
if (scoreAndTypeAndNote.score !== undefined) {
scoreAndTypeAndNote.element = rootElement(fnode.element);
}
return scoreAndTypeAndNote;
}
return wrapper;
}
/**
* Sort the elements by their position in the DOM.
*
* @arg fnodes {iterable} fnodes to sort
* @return {Array} sorted fnodes
*/
function domSort(fnodes) {
function compare(a, b) {
const element = a.element;
const position = element.compareDocumentPosition(b.element);
if (position & element.DOCUMENT_POSITION_FOLLOWING) {
return -1;
} else if (position & element.DOCUMENT_POSITION_PRECEDING) {
return 1;
} else {
return 0;
}
}
return Array.from(fnodes).sort(compare);
}
/* istanbul ignore next */
/**
* Return the DOM element contained in a passed-in fnode. Return passed-in DOM
* elements verbatim.
*
* @arg fnodeOrElement {Node|Fnode}
*/
function toDomElement(fnodeOrElement) {
return isDomElement(fnodeOrElement) ? fnodeOrElement : fnodeOrElement.element;
}
/**
* Checks whether any of the element's attribute values satisfy some condition.
*
* Example::
*
* rule(type('foo'),
* score(attributesMatch(element,
* attr => attr.includes('good'),
* ['id', 'alt']) ? 2 : 1))
*
* @arg element {Node} Element whose attributes you want to search
* @arg predicate {function} A condition to check. Take a string and
* return a boolean. If an attribute has multiple values (e.g. the class
* attribute), attributesMatch will check each one.
* @arg attrs {string[]} An Array of attributes you want to search. If none are
* provided, search all.
* @return Whether any of the attribute values satisfy the predicate function
*/
function attributesMatch(element, predicate, attrs = []) {
const attributes = attrs.length === 0 ? Array.from(element.attributes).map((a) => a.name) : attrs;
for (let i = 0; i < attributes.length; i++) {
const attr = element.getAttribute(attributes[i]);
// If the attribute is an array, apply the scoring function to each element
if (attr && ((Array.isArray(attr) && attr.some(predicate)) || predicate(attr))) {
return true;
}
}
return false;
}
/* istanbul ignore next */
/**
* Yield an element and each of its ancestors.
*/
function* ancestors(element) {
yield element;
let parent;
while ((parent = element.parentNode) !== null && parent.nodeType === parent.ELEMENT_NODE) {
yield parent;
element = parent;
}
}
/**
* Return the sigmoid of the argument: 1 / (1 + exp(-x)). This is useful for
* crunching a feature value that may have a wide range into the range (0, 1)
* without a hard ceiling: the sigmoid of even a very large number will be a
* little larger than that of a slightly smaller one.
*
* @arg x {Number} a number to be compressed into the range (0, 1)
*/
function sigmoid(x) {
return 1 / (1 + Math.exp(-x));
}
/* istanbul ignore next */
/**
* Return whether an element is practically visible, considering things like 0
* size or opacity, ``visibility: hidden`` and ``overflow: hidden``.
*
* Merely being scrolled off the page in either horizontally or vertically
* doesn't count as invisible; the result of this function is meant to be
* independent of viewport size.
*
* @throws {NoWindowError} The element (or perhaps one of its ancestors) is not
* in a window, so we can't find the `getComputedStyle()` routine to call.
* That routine is the source of most of the information we use, so you
* should pick a different strategy for non-window contexts.
*/
function isVisible(fnodeOrElement) {
// This could be 5x more efficient if https://github.com/w3c/csswg-drafts/issues/4122 happens.
const element = toDomElement(fnodeOrElement);
const elementWindow = windowForElement(element);
const elementRect = element.getBoundingClientRect();
const elementStyle = elementWindow.getComputedStyle(element);
// Alternative to reading ``display: none`` due to Bug 1381071.
if (elementRect.width === 0 && elementRect.height === 0 && elementStyle.overflow !== 'hidden') {
return false;
}
if (elementStyle.visibility === 'hidden') {
return false;
}
// Check if the element is irrevocably off-screen:
if (elementRect.x + elementRect.width < 0 || elementRect.y + elementRect.height < 0) {
return false;
}
for (const ancestor of ancestors(element)) {
const isElement = ancestor === element;
const style = isElement ? elementStyle : elementWindow.getComputedStyle(ancestor);
if (style.opacity === '0') {
return false;
}
if (style.display === 'contents') {
// ``display: contents`` elements have no box themselves, but children are
// still rendered.
continue;
}
const rect = isElement ? elementRect : ancestor.getBoundingClientRect();
if ((rect.width === 0 || rect.height === 0) && elementStyle.overflow === 'hidden') {
// Zero-sized ancestors don’t make descendants hidden unless the descendant
// has ``overflow: hidden``.
return false;
}
}
return true;
}
/**
* Return the extracted [r, g, b, a] values from a string like "rgba(0, 5, 255, 0.8)",
* and scale them to 0..1. If no alpha is specified, return undefined for it.
*/
function rgbaFromString(str) {
const m = str.match(/^rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)$/i);
if (m) {
return [m[1] / 255, m[2] / 255, m[3] / 255, m[4] === undefined ? undefined : parseFloat(m[4])];
} else {
throw new Error('Color ' + str + ' did not match pattern rgb[a](r, g, b[, a]).');
}
}
/**
* Return the saturation 0..1 of a color defined by RGB values 0..1.
*/
function saturation(r, g, b) {
const cMax = Math.max(r, g, b);
const cMin = Math.min(r, g, b);
const delta = cMax - cMin;
const lightness = (cMax + cMin) / 2;
const denom = 1 - Math.abs(2 * lightness - 1);
// Return 0 if it's black (R, G, and B all 0).
return denom === 0 ? 0 : delta / denom;
}
/**
* Scale a number to the range [0, 1] using a linear slope.
*
* For a rising line, the result is 0 until the input reaches zeroAt, then
* increases linearly until oneAt, at which it becomes 1. To make a falling
* line, where the result is 1 to the left and 0 to the right, use a zeroAt
* greater than oneAt.
*/
function linearScale(number, zeroAt, oneAt) {
const isRising = zeroAt < oneAt;
if (isRising) {
if (number <= zeroAt) {
return 0;
} else if (number >= oneAt) {
return 1;
}
} else {
if (number >= zeroAt) {
return 0;
} else if (number <= oneAt) {
return 1;
}
}
const slope = 1 / (oneAt - zeroAt);
return slope * (number - zeroAt);
}
// -------- Routines below this point are private to the framework. --------
/**
* Flatten out an iterable of iterables into a single iterable of non-
* iterables. Does not consider strings to be iterable.
*/
function* flatten(iterable) {
for (const i of iterable) {
if (typeof i !== 'string' && !(i instanceof Element) && isIterable(i)) {
yield* flatten(i);
} else {
yield i;
}
}
}
/**
* A lazy, top-level ``Array.map()`` workalike that works on anything iterable
*/
function* map(fn, iterable) {
for (const i of iterable) {
yield fn(i);
}
}
/**
* A lazy, top-level ``Array.forEach()`` workalike that works on anything
* iterable
*/
function forEach(fn, iterable) {
for (const i of iterable) {
fn(i);
}
}
/* istanbul ignore next */
/**
* @return whether a thing appears to be a DOM element.
*/
function isDomElement(thing) {
return thing.nodeName !== undefined;
}
function isIterable(thing) {
return thing && typeof thing[Symbol.iterator] === 'function';
}
/**
* Return an backward iterator over an Array without reversing it in place.
*/
function* reversed(array) {
for (let i = array.length - 1; i >= 0; i--) {
yield array[i];
}
}
/* istanbul ignore next */
/*
* Return the window an element is in.
*
* @throws {NoWindowError} There isn't such a window.
*/
function windowForElement(element) {
let doc = element.ownerDocument;
if (doc === null) {
// The element itself was a document.
doc = element;
}
const win = doc.defaultView;
if (win === null) {
throw new NoWindowError();
}
return win;
}
var utilsForFrontend = /*#__PURE__*/ Object.freeze({
__proto__: null,
NiceSet: NiceSet,
ancestors: ancestors,
attributesMatch: attributesMatch,
best: best,
collapseWhitespace: collapseWhitespace,
domSort: domSort,
first: first,
flatten: flatten,
forEach: forEach,
getDefault: getDefault,
identity: identity,
inlineTextLength: inlineTextLength,
inlineTexts: inlineTexts,
isBlock: isBlock,
isDomElement: isDomElement,
isVisible: isVisible,
isWhitespace: isWhitespace,
length: length,
linearScale: linearScale,
linkDensity: linkDensity,
map: map,
max: max,
maxes: maxes,
min: min,
numberOfMatches: numberOfMatches,
page: page,
reversed: reversed,
rgbaFromString: rgbaFromString,
rootElement: rootElement,
saturation: saturation,
setDefault: setDefault,
sigmoid: sigmoid,
sum: sum,
toDomElement: toDomElement,
toposort: toposort,
walk: walk,
windowForElement: windowForElement,
});
/**
* Return the number of stride nodes between 2 DOM nodes *at the same
* level of the tree*, without going up or down the tree.
*
* ``left`` xor ``right`` may also be undefined.
*/
function numStrides(left, right) {
let num = 0;
// Walk right from left node until we hit the right node or run out:
let sibling = left;
let shouldContinue = sibling && sibling !== right;
while (shouldContinue) {
sibling = sibling.nextSibling;
if ((shouldContinue = sibling && sibling !== right) && !isWhitespace(sibling)) {
num += 1;
}
}
if (sibling !== right) {
// Don't double-punish if left and right are siblings.
// Walk left from right node:
sibling = right;
while (sibling) {
sibling = sibling.previousSibling;
if (sibling && !isWhitespace(sibling)) {
num += 1;
}
}
}
return num;
}
/**
* Return a topological distance between 2 DOM nodes or :term:`fnodes<fnode>`
* weighted according to the similarity of their ancestry in the DOM. For
* instance, if one node is situated inside ``<div><span><b><theNode>`` and the
* other node is at ``<differentDiv><span><b><otherNode>``, they are considered
* close to each other for clustering purposes. This is useful for picking out
* nodes which have similar purposes.
*
* Return ``Number.MAX_VALUE`` if one of the nodes contains the other.
*
* This is largely an implementation detail of :func:`clusters`, but you can
* call it yourself if you wish to implement your own clustering. Takes O(n log
* n) time.
*
* Note that the default costs may change; pass them in explicitly if they are
* important to you.
*
* @arg fnodeA {Node|Fnode}
* @arg fnodeB {Node|Fnode}
* @arg differentDepthCost {number} Cost for each level deeper one node is than
* the other below their common ancestor
* @arg differentTagCost {number} Cost for a level below the common ancestor
* where tagNames differ
* @arg sameTagCost {number} Cost for a level below the common ancestor where
* tagNames are the same
* @arg strideCost {number} Cost for each stride node between A and B. Stride
* nodes are siblings or siblings-of-ancestors that lie between the 2
* nodes. These interposed nodes make it less likely that the 2 nodes
* should be together in a cluster.
* @arg additionalCost {function} Return an additional cost, given 2 fnodes or
* nodes.
*
*/
function distance(
fnodeA,
fnodeB,
{
differentDepthCost = 2,
differentTagCost = 2,
sameTagCost = 1,
strideCost = 1,
additionalCost = (fnodeA, fnodeB) => 0,
} = {}
) {
// I was thinking of something that adds little cost for siblings. Up
// should probably be more expensive than down (see middle example in the
// Nokia paper).
// TODO: Test and tune default costs. They're off the cuff at the moment.
if (fnodeA === fnodeB) {
return 0;
}
const elementA = isDomElement(fnodeA) ? fnodeA : fnodeA.element;
const elementB = isDomElement(fnodeB) ? fnodeB : fnodeB.element;
// Stacks that go from the common ancestor all the way to A and B:
const aAncestors = [elementA];
const bAncestors = [elementB];
let aAncestor = elementA;
let bAncestor = elementB;
// Ascend to common parent, stacking them up for later reference:
while (!aAncestor.contains(elementB)) {
// Note: an element does contain() itself.
aAncestor = aAncestor.parentNode;
aAncestors.push(aAncestor); //aAncestors = [a, b]. aAncestor = b // if a is outer: no loop here; aAncestors = [a]. aAncestor = a.
}
// In compareDocumentPosition()'s opinion, inside implies after. Basically,
// before and after pertain to opening tags.
const comparison = elementA.compareDocumentPosition(elementB);
// If either contains the other, abort. We'd either return a misleading
// number or else walk upward right out of the document while trying to
// make the ancestor stack.
if (comparison & (elementA.DOCUMENT_POSITION_CONTAINS | elementA.DOCUMENT_POSITION_CONTAINED_BY)) {
return Number.MAX_VALUE;
}
// Make an ancestor stack for the right node too so we can walk
// efficiently down to it:
do {
bAncestor = bAncestor.parentNode; // Assumes we've early-returned above if A === B. This walks upward from the outer node and up out of the tree. It STARTS OUT with aAncestor === bAncestor!
bAncestors.push(bAncestor);
} while (bAncestor !== aAncestor);
// Figure out which node is left and which is right, so we can follow
// sibling links in the appropriate directions when looking for stride
// nodes:
let left = aAncestors;
let right = bAncestors;
let cost = 0;
if (comparison & elementA.DOCUMENT_POSITION_FOLLOWING) {
// A is before, so it could contain the other node. What did I mean to do if one contained the other?
left = aAncestors;
right = bAncestors;
} else if (comparison & elementA.DOCUMENT_POSITION_PRECEDING) {
// A is after, so it might be contained by the other node.
left = bAncestors;
right = aAncestors;
}
// Descend to both nodes in parallel, discounting the traversal
// cost iff the nodes we hit look similar, implying the nodes dwell
// within similar structures.
while (left.length || right.length) {
const l = left.pop();
const r = right.pop();
if (l === undefined || r === undefined) {
// Punishment for being at different depths: same as ordinary
// dissimilarity punishment for now
cost += differentDepthCost;
} else {
// TODO: Consider similarity of classList.
cost += l.tagName === r.tagName ? sameTagCost : differentTagCost;
}
// Optimization: strides might be a good dimension to eliminate.
if (strideCost !== 0) {
cost += numStrides(l, r) * strideCost;
}
}
return cost + additionalCost(fnodeA, fnodeB);
}
/**
* Return the spatial distance between 2 fnodes or elements, assuming a
* rendered page.
*
* Specifically, return the distance in pixels between the centers of
* ``fnodeA.element.getBoundingClientRect()`` and
* ``fnodeB.element.getBoundingClientRect()``.
*/
function euclidean(fnodeA, fnodeB) {
/**
* Return the horizontal distance from the left edge of the viewport to the
* center of an element, given a DOMRect object for it. It doesn't matter
* that the distance is affected by the page's scroll offset, since the 2
* elements have the same offset.
*/
function xCenter(domRect) {
return domRect.left + domRect.width / 2;
}
function yCenter(domRect) {
return domRect.top + domRect.height / 2;
}
const elementA = toDomElement(fnodeA);
const elementB = toDomElement(fnodeB);
const aRect = elementA.getBoundingClientRect();
const bRect = elementB.getBoundingClientRect();
return Math.sqrt((xCenter(aRect) - xCenter(bRect)) ** 2 + (yCenter(aRect) - yCenter(bRect)) ** 2);
}
/** A lower-triangular matrix of inter-cluster distances */
class DistanceMatrix {
/**
* @arg distance {function} Some notion of distance between 2 given nodes
*/
constructor(elements, distance) {
// A sparse adjacency matrix:
// {A => {},
// B => {A => 4},
// C => {A => 4, B => 4},
// D => {A => 4, B => 4, C => 4}
// E => {A => 4, B => 4, C => 4, D => 4}}
//
// A, B, etc. are arrays of [arrays of arrays of...] nodes, each
// array being a cluster. In this way, they not only accumulate a
// cluster but retain the steps along the way.
//
// This is an efficient data structure in terms of CPU and memory, in
// that we don't have to slide a lot of memory around when we delete a
// row or column from the middle of the matrix while merging. Of
// course, we lose some practical efficiency by using hash tables, and
// maps in particular are slow in their early implementations.
this._matrix = new Map();
// Convert elements to clusters:
const clusters = elements.map((el) => [el]);
// Init matrix:
for (let outerCluster of clusters) {
const innerMap = new Map();
for (let innerCluster of this._matrix.keys()) {
innerMap.set(innerCluster, distance(outerCluster[0], innerCluster[0]));
}
this._matrix.set(outerCluster, innerMap);
}
this._numClusters = clusters.length;
}
// Return (distance, a: clusterA, b: clusterB) of closest-together clusters.
// Replace this to change linkage criterion.
closest() {
const self = this;
if (this._numClusters < 2) {
throw new Error('There must be at least 2 clusters in order to return the closest() ones.');
}
// Return the distances between every pair of clusters.
function clustersAndDistances() {
const ret = [];
for (let [outerKey, row] of self._matrix.entries()) {
for (let [innerKey, storedDistance] of row.entries()) {
ret.push({ a: outerKey, b: innerKey, distance: storedDistance });
}
}
return ret;
}
// Optimizing this by inlining the loop and writing it less
// functionally doesn't help:
return min(clustersAndDistances(), (x) => x.distance);
}
// Look up the distance between 2 clusters in me. Try the lookup in the
// other direction if the first one falls in the nonexistent half of the
// triangle.
_cachedDistance(clusterA, clusterB) {
let ret = this._matrix.get(clusterA).get(clusterB);
if (ret === undefined) {
ret = this._matrix.get(clusterB).get(clusterA);
}
return ret;
}
// Merge two clusters.
merge(clusterA, clusterB) {
// An example showing how rows merge:
// A: {}
// B: {A: 1}
// C: {A: 4, B: 4},
// D: {A: 4, B: 4, C: 4}
// E: {A: 4, B: 4, C: 2, D: 4}}
//
// Step 2:
// C: {}
// D: {C: 4}
// E: {C: 2, D: 4}}
// AB: {C: 4, D: 4, E: 4}
//
// Step 3:
// D: {}
// AB: {D: 4}
// CE: {D: 4, AB: 4}
// Construct new row, finding min distances from either subcluster of
// the new cluster to old clusters.
//
// There will be no repetition in the matrix because, after all,
// nothing pointed to this new cluster before it existed.
const newRow = new Map();
for (let outerKey of this._matrix.keys()) {
if (outerKey !== clusterA && outerKey !== clusterB) {
newRow.set(
outerKey,
Math.min(this._cachedDistance(clusterA, outerKey), this._cachedDistance(clusterB, outerKey))
);
}
}
// Delete the rows of the clusters we're merging.
this._matrix.delete(clusterA);
this._matrix.delete(clusterB);
// Remove inner refs to the clusters we're merging.
for (let inner of this._matrix.values()) {
inner.delete(clusterA);
inner.delete(clusterB);
}
// Attach new row.
this._matrix.set([clusterA, clusterB], newRow);
// There is a net decrease of 1 cluster:
this._numClusters -= 1;
}
numClusters() {
return this._numClusters;
}
// Return an Array of nodes for each cluster in me.
clusters() {
// TODO: Can't get map to work here. Don't know why.
return Array.from(this._matrix.keys()).map((e) => Array.from(flatten(e)));
}
}
/**
* Partition the given nodes into one or more clusters by position in the DOM
* tree.
*
* This implements an agglomerative clustering. It uses single linkage, since
* we're talking about adjacency here more than Euclidean proximity: the
* clusters we're talking about in the DOM will tend to be adjacent, not
* overlapping. We haven't tried other linkage criteria yet.
*
* In a later release, we may consider score or notes.
*
* @arg {Fnode[]|Node[]} fnodes :term:`fnodes<fnode>` or DOM nodes to group
* into clusters
* @arg {number} splittingDistance The closest-nodes :func:`distance` beyond
* which we will not attempt to unify 2 clusters. Make this larger to make
* larger clusters.
* @arg getDistance {function} A function that returns some notion of numerical
* distance between 2 nodes. Default: :func:`distance`
* @return {Array} An Array of Arrays, with each Array containing all the
* nodes in one cluster. Note that neither the clusters nor the nodes are
* in any particular order. You may find :func:`domSort` helpful to remedy
* the latter.
*/
function clusters(fnodes, splittingDistance, getDistance = distance) {
const matrix = new DistanceMatrix(fnodes, getDistance);
let closest;
while (matrix.numClusters() > 1 && (closest = matrix.closest()).distance < splittingDistance) {
matrix.merge(closest.a, closest.b);
}
return matrix.clusters();
}
var clusters$1 = /*#__PURE__*/ Object.freeze({
__proto__: null,
clusters: clusters,
distance: distance,
euclidean: euclidean,
});
// The left-hand side of a rule
/**
* Take nodes that match a given DOM selector. Example:
* ``dom('meta[property="og:title"]')``
*
* Every ruleset has at least one ``dom`` or :func:`element` rule, as that is
* where nodes begin to flow into the system. If run against a subtree of a
* document, the root of the subtree is not considered as a possible match.
*/
function dom(selector) {
return new DomLhs(selector);
}
/**
* Take a single given node if it matches a given DOM selector, without looking
* through its descendents or ancestors. Otherwise, take no nodes. Example:
* ``element('input')``
*
* This is useful for applications in which you want Fathom to classify an
* element the user has selected, rather than scanning the whole page for
* candidates.
*/
function element(selector) {
return new ElementLhs(selector);
}
/**
* PROTON EXTENSION
* Allows running a custom function when selecting
* DOM elements in a fathom LHS rule.
*/
function domQuery(query) {
return new DomQueryLhs(query);
}
/**
* Rules and the LHSs and RHSs that comprise them have no mutable state. This
* lets us make BoundRulesets from Rulesets without duplicating the rules. It
* also lets us share a common cache among rules: multiple ones might care
* about a cached type(), for instance; there isn't a one-to-one relationship
* of storing with caring. There would also, because of the interdependencies
* of rules in a ruleset, be little use in segmenting the caches: if you do
* something that causes one to need to be cleared, you'll need to clear many
* more as well.
*
* Lhses are responsible for maintaining ruleset.maxCache.
*
* Lhs and its subclasses are private to the Fathom framework.
*/
class Lhs {
constructor() {
this._predicate = () => true;
}
/** Return a new Lhs of the appropriate kind, given its first call. */
static fromFirstCall(firstCall) {
// firstCall is never 'dom', because dom() directly returns a DomLhs.
if (firstCall.method === 'type') {
return new TypeLhs(...firstCall.args);
} else if (firstCall.method === 'and') {
return new AndLhs(firstCall.args);
} else if (firstCall.method === 'nearest') {
return new NearestLhs(firstCall.args);
} else {
throw new Error('The left-hand side of a rule() must start with dom(), type(), and(), or nearest().');
}
}
/**
* Prune nodes from consideration early in run execution, before scoring is
* done.
*
* Reserve this for where you are sure it is always correct or when
* performance demands it. It is generally preferable to use :func:`score`
* and let the :doc:`trainer<training>` determine the relative significance
* of each rule. Human intuition as to what is important is often wrong:
* for example, one might assume that a music player website would include
* the word "play", but this does not hold once you include sites in other
* languages.
*
* Can be chained after :func:`type` or :func:`dom`.
*
* Example: ``dom('p').when(isVisible)``
*
* @arg {function} predicate Accepts a fnode and returns a boolean
*/
when(predicate) {
let lhs = this.clone();
lhs._predicate = predicate;
return lhs;
}
/**
* Of all the dom nodes selected by type() or dom(), return only
* the fnodes that satisfy all the predicates imposed by calls to
* when()
*/
fnodesSatisfyingWhen(fnodes) {
return Array.from(fnodes).filter(this._predicate);
}
/**
* Return an iterable of output fnodes selected by this left-hand-side
* expression.
*
* Pre: The rules I depend on have already been run, and their results are
* in ruleset.typeCache.
*
* @arg ruleset {BoundRuleset}
*/
// fnodes (ruleset) {}
/**
* Check that a RHS-emitted fact is legal for this kind of LHS, and throw
* an error if it isn't.
*/
checkFact(fact) {}
/**
* Return the single type the output of the LHS is guaranteed to have.
* Return undefined if there is no such single type we can ascertain.
*/
guaranteedType() {}
/**
* Return the type I aggregate if I am an aggregate LHS; return undefined
* otherwise.
*/
aggregatedType() {}
/**
* Return each combination of types my selected nodes could be locally (that
* is, by this rule only) constrained to have.
*
* For example, type(A) would return [A]. and(A, or(B, C)) would return
* [AB, AC, ABC]. More examples:
*
* or(A, B) → typeIn(A, B, C) # Finalizes A, B. combos A, B, AB: finalizes AB. Optimization: there's no point in returning the last combo in ors. Compilation into 2 rules with identical RHSs will inherently implement this optimization.
* or(A, B) → typeIn(A, B) # Finalizes A, B
* or(A, B) → A # Finalizes B
* and(A) -> A # Finalizes nothing
* and(A, B) -> A # Finalizes nothing. AB: Ø
* and(A) -> typeIn(A, B) # Finalizes A. A
* and(A, B) -> typeIn(A, B) # Finalizes nothing. AB
* and(A, B) -> typeIn(A, B, C) # Finalizes A, B. AB
* and(A, or(B, C)) -> D # Finalizes A, B, C. AB, AC, ABC: ABC
* and(A, or(B, C)) -> B # Finalizes A, C. AB, AC, ABC: AC
* type(A).not(and(A, B)) ->
*
* @return {NiceSet[]}
*/
// possibleTypeCombinations() {}
/**
* Types mentioned in this LHS.
*
* In other words, the types I need to know the assignment status of before
* I can make my selections
*
* @return NiceSet of strings
*/
// typesMentioned() {}
}
class DomLhs extends Lhs {
constructor(selector) {
super();
if (selector === undefined) {
throw new Error(
'A querySelector()-style selector is required as the argument to ' + this._callName() + '().'
);
}
this.selector = selector;
}
/**
* Return the name of this kind of LHS, for use in error messages.
*/
_callName() {
return 'dom';
}
clone() {
return new this.constructor(this.selector);
}
fnodes(ruleset) {
return this._domNodesToFilteredFnodes(ruleset, ruleset.doc.querySelectorAll(this.selector));
}
/**
* Turn a NodeList of DOM nodes into an array of fnodes, and filter out
* those that don't match the :func:`when()` clause.
*/
_domNodesToFilteredFnodes(ruleset, domNodes) {
let ret = [];
for (let i = 0; i < domNodes.length; i++) {
ret.push(ruleset.fnodeForElement(domNodes[i]));
}
return this.fnodesSatisfyingWhen(ret);
}
checkFact(fact) {
if (fact.type === undefined) {
throw new Error(
`The right-hand side of a ${this._callName()}() rule failed to specify a type. This means there is no way for its output to be used by later rules. All it specified was ${fact}.`
);
}
}
asLhs() {
return this;
}
possibleTypeCombinations() {
return [];
}
typesMentioned() {
return new NiceSet();
}
}
class ElementLhs extends DomLhs {
_callName() {
return 'element';
}
fnodes(ruleset) {
return this._domNodesToFilteredFnodes(ruleset, ruleset.doc.matches(this.selector) ? [ruleset.doc] : []);
}
}
/**
* PROTON EXTENSION
* Extends DomLhs rule but instead of passing
* a single string selector, allows passing a
* custom selector function that will be run
* against the document
*/
class DomQueryLhs extends DomLhs {
constructor(query) {
/**
* mock selector to avoid parent DomLhs
* throwing in constructor call
*/
super('');
this.query = query;
}
_callName() {
return 'domQuery';
}
clone() {
return new DomQueryLhs(this.query);
}
fnodes(ruleset) {
return this._domNodesToFilteredFnodes(ruleset, this.query(ruleset.doc));
}
}
/** Internal representation of a LHS constrained by type but not by max() */
class TypeLhs extends Lhs {
constructor(type) {
super();
if (type === undefined) {
throw new Error('A type name is required when calling type().');
}
this._type = type; // the input type
}
clone() {
return new this.constructor(this._type);
}
fnodes(ruleset) {
const cached = getDefault(ruleset.typeCache, this._type, () => []);
return this.fnodesSatisfyingWhen(cached);
}
/** Override the type previously specified by this constraint. */
type(inputType) {
// Preserve the class in case this is a TypeMaxLhs.
return new this.constructor(inputType);
}
/**
* Of the nodes selected by a ``type`` call to the left, constrain the LHS
* to return only the max-scoring one. If there is a tie, more than 1 node
* will be returned. Example: ``type('titley').max()``
*/
max() {
return new TypeMaxLhs(this._type);
}
/**
* Take the nodes selected by a ``type`` call to the left, group them into
* clusters, and return the nodes in the cluster that has the highest total
* score (on the relevant type).
*
* Nodes come out in arbitrary order, so, if you plan to emit them,
* consider using ``.out('whatever').allThrough(domSort)``. See
* :func:`domSort`.
*
* If multiple clusters have equally high scores, return an arbitrary one,
* because Fathom has no way to represent arrays of arrays in rulesets.
*
* @arg options {Object} The same depth costs taken by :func:`distance`,
* plus ``splittingDistance``, which is the distance beyond which 2
* clusters will be considered separate. ``splittingDistance``, if
* omitted, defaults to 3.
*/
bestCluster(options) {
return new BestClusterLhs(this._type, options);
}
// Other clustering calls could be called biggestCluster() (having the most
// nodes) and bestAverageCluster() (having the highest average score).
guaranteedType() {
return this._type;
}
possibleTypeCombinations() {
return [this.typesMentioned()];
}
typesMentioned() {
return new NiceSet([this._type]);
}
}
/**
* Abstract LHS that is an aggregate function taken across all fnodes of a type
*
* The main point here is that any aggregate function over a (typed) set of
* nodes depends on first computing all the rules that could emit those nodes
* (nodes of that type).
*/
class AggregateTypeLhs extends TypeLhs {
aggregatedType() {
return this._type;
}
}
/**
* Internal representation of a LHS that has both type and max([NUMBER])
* constraints. max(NUMBER != 1) support is not yet implemented.
*/
class TypeMaxLhs extends AggregateTypeLhs {
/**
* Return the max-scoring node (or nodes if there is a tie) of the given
* type.
*/
fnodes(ruleset) {
// TODO: Optimize better. Walk the dependency tree, and run only the
// rules that could possibly lead to a max result. As part of this,
// make RHSs expose their max potential scores.
const self = this;
// Work around V8 bug:
// https://stackoverflow.com/questions/32943776/using-super-within-an-
// arrow-function-within-an-arrow-function-within-a-method
const getSuperFnodes = () => super.fnodes(ruleset);
return setDefault(ruleset.maxCache, this._type, function maxFnodesOfType() {
return maxes(getSuperFnodes(), (fnode) => ruleset.weightedScore(fnode.scoresSoFarFor(self._type)));
});
}
}
class BestClusterLhs extends AggregateTypeLhs {
constructor(type, options) {
super(type);
this._options = options || { splittingDistance: 3 };
}
/**
* Group the nodes of my type into clusters, and return the cluster with
* the highest total score for that type.
*/
fnodes(ruleset) {
// Get the nodes of the type:
const fnodesOfType = Array.from(super.fnodes(ruleset));
if (fnodesOfType.length === 0) {
return [];
}
// Cluster them:
const clusts = clusters(fnodesOfType, this._options.splittingDistance, (a, b) => distance(a, b, this._options));
// Tag each cluster with the total of its nodes' scores:
const clustsAndSums = clusts.map((clust) => [clust, sum(clust.map((fnode) => fnode.scoreFor(this._type)))]);
// Return the highest-scoring cluster:
return max(clustsAndSums, (clustAndSum) => clustAndSum[1])[0];
}
}
class AndLhs extends Lhs {
constructor(lhss) {
super();
// For the moment, we accept only type()s as args. TODO: Generalize to
// type().max() and such later.
this._args = lhss.map(sideToTypeLhs);
}
*fnodes(ruleset) {
// Take an arbitrary one for starters. Optimization: we could always
// choose the pickiest one to start with.
const fnodes = this._args[0].fnodes(ruleset);
// Then keep only the fnodes that have the type of every other arg:
fnodeLoop: for (let fnode of fnodes) {
for (let otherLhs of this._args.slice(1)) {
// Optimization: could use a .hasTypeSoFar() below
if (!fnode.hasType(otherLhs.guaranteedType())) {
// TODO: This is n^2. Why is there no set intersection in JS?!
continue fnodeLoop;
}
}
yield fnode;
}
}
possibleTypeCombinations() {
return [this.typesMentioned()];
}
typesMentioned() {
return new NiceSet(this._args.map((arg) => arg.guaranteedType()));
}
}
function sideToTypeLhs(side) {
const lhs = side.asLhs();
if (!(lhs.constructor === TypeLhs)) {
throw new Error('and() and nearest() support only simple type() calls as arguments for now.');
// TODO: Though we could solve this with a compilation step: and(type(A), type(B).max()) is equivalent to type(B).max() -> type(Bmax); and(type(A), type(Bmax)).
// In fact, we should be able to compile most (any?) arbitrary and()s, including nested ands and and(type(...).max(), ...) constructions into several and(type(A), type(B), ...) rules.
}
return lhs;
}
class NearestLhs extends Lhs {
constructor([a, b, distance]) {
super();
this._a = sideToTypeLhs(a);
this._b = sideToTypeLhs(b);
this._distance = distance;
}
/**
* Return an iterable of {fnodes, transformer} pairs.
*/
*fnodes(ruleset) {
// Go through all the left arg's nodes. For each one, find the closest
// right-arg's node. O(a * b). Once a right-arg's node is used, we
// don't eliminate it from consideration, because then order of left-
// args' nodes would matter.
// TODO: Still not sure how to get the distance to factor into the
// score unless we hard-code nearest() to do that. It's a
// matter of not being able to bind on the RHS to the output of the
// distance function on the LHS. Perhaps we could at least make
// distance part of the note and read it in a props() callback.
// We're assuming here that simple type() calls return just plain
// fnodes, not {fnode, rhsTransformer} pairs:
const as_ = this._a.fnodes(ruleset);
const bs = Array.from(this._b.fnodes(ruleset));
if (bs.length > 0) {
// If bs is empty, there can be no nearest nodes, so don't emit any.
for (const a of as_) {
const nearest = min(bs, (b) => this._distance(a, b));
yield {
fnode: a,
rhsTransformer: function setNoteIfEmpty(fact) {
// If note is explicitly set by the RHS, let it take
// precedence, even though that makes this entire LHS
// pointless.
if (fact.note === undefined) {
fact.note = nearest; // TODO: Wrap this in an object to make room to return distance later.
}
return fact;
},
};
}
}
}
checkFact(fact) {
// Barf if the fact doesn't set a type at least. It should be a *new* type or at least one that doesn't result in cycles, but we can't deduce that.
}
possibleTypeCombinations() {
return [new NiceSet([this._a.guaranteedType()])];
}
typesMentioned() {
return new NiceSet([this._a.guaranteedType(), this._b.guaranteedType()]);
}
guaranteedType() {
return this._a.guaranteedType();
}
}
// The right-hand side of a rule
const TYPE = 1;
const NOTE = 2;
const SCORE = 4;
const ELEMENT = 8;
const SUBFACTS = {
type: TYPE,
note: NOTE,
score: SCORE,
element: ELEMENT,
};
/**
* Expose the output of this rule's LHS as a "final result" to the surrounding
* program. It will be available by calling :func:`~BoundRuleset.get` on the
* ruleset and passing the key. You can run each node through a callback
* function first by adding :func:`through()`, or you can run the entire set of
* nodes through a callback function by adding :func:`allThrough()`.
*/
function out(key) {
return new OutwardRhs(key);
}
class InwardRhs {
constructor(calls = [], max = Infinity, types) {
this._calls = calls.slice();
this._max = max; // max score
this._types = new NiceSet(types); // empty set if unconstrained
}
/**
* Declare that the maximum returned subscore is such and such,
* which helps the optimizer plan efficiently. This doesn't force it to be
* true; it merely throws an error at runtime if it isn't. To lift an
* ``atMost`` constraint, call ``atMost()`` (with no args). The reason
* ``atMost`` and ``typeIn`` apply until explicitly cleared is so that, if
* someone used them for safety reasons on a lexically distant rule you are
* extending, you won't stomp on their constraint and break their
* invariants accidentally.
*/
atMost(score) {
return new this.constructor(this._calls, score, this._types);
}
_checkAtMost(fact) {
if (fact.score !== undefined && fact.score > this._max) {
throw new Error(`Score of ${fact.score} exceeds the declared atMost(${this._max}).`);
}
}
/**
* Determine any of type, note, score, and element using a callback. This
* overrides any previous call to `props` and, depending on what
* properties of the callback's return value are filled out, may override
* the effects of other previous calls as well.
*
* The callback should return...
*
* * An optional :term:`subscore`
* * A type (required on ``dom(...)`` rules, defaulting to the input one on
* ``type(...)`` rules)
* * Optional notes
* * An element, defaulting to the input one. Overriding the default
* enables a callback to walk around the tree and say things about nodes
* other than the input one.
*/
props(callback) {
function getSubfacts(fnode) {
const subfacts = callback(fnode);
// Filter the raw result down to okayed properties so callbacks
// can't insert arbitrary keys (like conserveScore, which might
// mess up the optimizer).
for (let subfact in subfacts) {
if (!SUBFACTS.hasOwnProperty(subfact) || !(SUBFACTS[subfact] & getSubfacts.possibleSubfacts)) {
// The ES5.1 spec says in 12.6.4 that it's fine to delete
// as we iterate.
delete subfacts[subfact];
}
}
return subfacts;
}
// Thse are the subfacts this call could affect:
getSubfacts.possibleSubfacts = TYPE | NOTE | SCORE | ELEMENT;
getSubfacts.kind = 'props';
return new this.constructor(this._calls.concat(getSubfacts), this._max, this._types);
}
/**
* Set the type applied to fnodes processed by this RHS.
*/
type(theType) {
// In the future, we might also support providing a callback that receives
// the fnode and returns a type. We couldn't reason based on these, but the
// use would be rather a consise way to to override part of what a previous
// .props() call provides.
// Actually emit a given type.
function getSubfacts() {
return { type: theType };
}
getSubfacts.possibleSubfacts = TYPE;
getSubfacts.type = theType;
getSubfacts.kind = 'type';
return new this.constructor(this._calls.concat(getSubfacts), this._max, this._types);
}
/**
* Constrain this rule to emit 1 of a set of given types. Pass no args to lift
* a previous ``typeIn`` constraint, as you might do when basing a LHS on a
* common value to factor out repetition.
*
* ``typeIn`` is mostly a hint for the query planner when you're emitting types
* dynamically from ``props`` calls—in fact, an error will be raised if
* ``props`` is used without a ``typeIn`` or ``type`` to constrain it—but it
* also checks conformance at runtime to ensure validity.
*/
typeIn(...types) {
// Rationale: If we used the spelling "type('a', 'b', ...)" instead of
// this, one might expect type('a', 'b').type(fn) to have the latter
// call override, while expecting type(fn).type('a', 'b') to keep both
// in effect. Then different calls to type() don't consistently
// override each other, and the rules get complicated. Plus you can't
// inherit a type constraint and then sub in another type-returning
// function that still gets the constraint applied.
return new this.constructor(this._calls, this._max, types);
}
/**
* Check a fact for conformance with any typeIn() call.
*
* @arg leftType the type of the LHS, which becomes my emitted type if the
* fact doesn't specify one
*/
_checkTypeIn(result, leftType) {
if (this._types.size > 0) {
if (result.type === undefined) {
if (!this._types.has(leftType)) {
throw new Error(
`A right-hand side claimed, via typeIn(...) to emit one of the types ${this._types} but actually inherited ${leftType} from the left-hand side.`
);
}
} else if (!this._types.has(result.type)) {
throw new Error(
`A right-hand side claimed, via typeIn(...) to emit one of the types ${this._types} but actually emitted ${result.type}.`
);
}
}
}
/**
* Whatever the callback returns (even ``undefined``) becomes the note of
* the fact. This overrides any previous call to ``note``.
*/
note(callback) {
function getSubfacts(fnode) {
return { note: callback(fnode) };
}
getSubfacts.possibleSubfacts = NOTE;
getSubfacts.kind = 'note';
return new this.constructor(this._calls.concat(getSubfacts), this._max, this._types);
}
/**
* Affect the confidence with which the input node should be considered a
* member of a type.
*
* The parameter is generally between 0 and 1 (inclusive), with 0 meaning
* the node does not have the "smell" this rule checks for and 1 meaning it
* does. The range between 0 and 1 is available to represent "fuzzy"
* confidences. If you have an unbounded range to compress down to [0, 1],
* consider using :func:`sigmoid` or a scaling thereof.
*
* Since every node can have multiple, independent scores (one for each
* type), this applies to the type explicitly set by the RHS or, if none,
* to the type named by the ``type`` call on the LHS. If the LHS has none
* because it's a ``dom(...)`` LHS, an error is raised.
*
* @arg {number|function} scoreOrCallback Can either be a static number,
* generally 0 to 1 inclusive, or else a callback which takes the fnode
* and returns such a number. If the callback returns a boolean, it is
* cast to a number.
*/
score(scoreOrCallback) {
let getSubfacts;
function getSubfactsFromNumber(fnode) {
return { score: scoreOrCallback };
}
function getSubfactsFromFunction(fnode) {
let result = scoreOrCallback(fnode);
if (typeof result === 'boolean') {
// Case bools to numbers for convenience. Boolean features are
// common. Don't cast other things, as it frustrates ruleset
// debugging.
result = Number(result);
}
return { score: result };
}
if (typeof scoreOrCallback === 'number') {
getSubfacts = getSubfactsFromNumber;
} else {
getSubfacts = getSubfactsFromFunction;
}
getSubfacts.possibleSubfacts = SCORE;
getSubfacts.kind = 'score';
return new this.constructor(this._calls.concat(getSubfacts), this._max, this._types);
}
// Future: why not have an .element() method for completeness?
// -------- Methods below this point are private to the framework. --------
/**
* Run all my props().type().note().score() stuff across a given fnode,
* enforce my max() stuff, and return a fact ({element, type, score,
* notes}) for incorporation into that fnode (or a different one, if
* element is specified). Any of the 4 fact properties can be missing;
* filling in defaults is a job for the caller.
*
* @arg leftType The type the LHS takes in
*/
fact(fnode, leftType) {
const doneKinds = new Set();
const result = {};
let haveSubfacts = 0;
for (let call of reversed(this._calls)) {
// If we've already called a call of this kind, then forget it.
if (!doneKinds.has(call.kind)) {
doneKinds.add(call.kind);
if (~haveSubfacts & call.possibleSubfacts) {
// This call might provide a subfact we are missing.
const newSubfacts = call(fnode);
// We start with an empty object, so we're okay here.
// eslint-disable-next-line guard-for-in
for (let subfact in newSubfacts) {
// A props() callback could insert arbitrary keys into
// the result, but it shouldn't matter, because nothing
// pays any attention to them.
if (!result.hasOwnProperty(subfact)) {
result[subfact] = newSubfacts[subfact];
}
haveSubfacts |= SUBFACTS[subfact];
}
}
}
}
this._checkAtMost(result);
this._checkTypeIn(result, leftType);
return result;
}
/**
* Return a record describing the types I might emit (which means either to
* add a type to a fnode or to output a fnode that already has that type).
* {couldChangeType: whether I might add a type to the fnode,
* possibleTypes: If couldChangeType, the types I might emit; empty set if
* we cannot infer it. If not couldChangeType, undefined.}
*/
possibleEmissions() {
// If there is a typeIn() constraint or there is a type() call to the
// right of all props() calls, we have a constraint. We hunt for the
// tightest constraint we can find, favoring a type() call because it
// gives us a single type but then falling back to a typeIn().
let couldChangeType = false;
for (let call of reversed(this._calls)) {
if (call.kind === 'props') {
couldChangeType = true;
break;
} else if (call.kind === 'type') {
return { couldChangeType: true, possibleTypes: new Set([call.type]) };
}
}
return { couldChangeType, possibleTypes: this._types };
}
}
class OutwardRhs {
constructor(key, through = (x) => x, allThrough = (x) => x) {
this.key = key;
this.callback = through;
this.allCallback = allThrough;
}
/**
* Append ``.through`` to :func:`out` to run each :term:`fnode` emitted
* from the LHS through an arbitrary function before returning it to the
* containing program. Example::
*
* out('titleLengths').through(fnode => fnode.noteFor('title').length)
*/
through(callback) {
return new this.constructor(this.key, callback, this.allCallback);
}
/**
* Append ``.allThrough`` to :func:`out` to run the entire iterable of
* emitted :term:`fnodes<fnode>` through an arbitrary function before
* returning them to the containing program. Example::
*
* out('sortedTitles').allThrough(domSort)
*/
allThrough(callback) {
return new this.constructor(this.key, this.callback, callback);
}
asRhs() {
return this;
}
}
function props(callback) {
return new Side({ method: 'props', args: [callback] });
}
/** Constrain to an input type on the LHS, or apply a type on the RHS. */
function type(theType) {
return new Side({ method: 'type', args: [theType] });
}
function note(callback) {
return new Side({ method: 'note', args: [callback] });
}
function score(scoreOrCallback) {
return new Side({ method: 'score', args: [scoreOrCallback] });
}
function atMost(score) {
return new Side({ method: 'atMost', args: [score] });
}
function typeIn(...types) {
return new Side({ method: 'typeIn', args: types });
}
/**
* Pull nodes that conform to multiple conditions at once.
*
* For example: ``and(type('title'), type('english'))``
*
* Caveats: ``and`` supports only simple ``type`` calls as arguments for now,
* and it may fire off more rules as prerequisites than strictly necessary.
* ``not`` and ``or`` don't exist yet, but you can express ``or`` the long way
* around by having 2 rules with identical RHSs.
*/
function and(...lhss) {
return new Side({ method: 'and', args: lhss });
}
/**
* Experimental. For each :term:`fnode` from ``typeCallA``, find the closest
* node from ``typeCallB``, and attach it as a note. The note is attached to
* the type specified by the RHS, defaulting to the type of ``typeCallA``. If
* no nodes are emitted from ``typeCallB``, do nothing.
*
* For example... ::
*
* nearest(type('image'), type('price'))
*
* The score of the ``typeCallA`` can be added to the new type's score by using
* :func:`conserveScore` (though this routine has since been removed)::
*
* rule(nearest(type('image'), type('price')),
* type('imageWithPrice').score(2).conserveScore())
*
* Caveats: ``nearest`` supports only simple ``type`` calls as arguments ``a``
* and ``b`` for now.
*
* @arg distance {function} A function that takes 2 fnodes and returns a
* numerical distance between them. Included options are :func:`distance`,
* which is a weighted topological distance, and :func:`euclidean`, which
* is a spatial distance.
*/
function nearest(typeCallA, typeCallB, distance = euclidean) {
return new Side({
method: 'nearest',
args: [typeCallA, typeCallB, distance],
});
}
/**
* A chain of calls that can be compiled into a Rhs or Lhs, depending on its
* position in a Rule. This lets us use type() as a leading call for both RHSs
* and LHSs. I would prefer to do this dynamically, but that wouldn't compile
* down to old versions of ES.
*/
class Side {
constructor(...calls) {
// A "call" is like {method: 'dom', args: ['p.smoo']}.
this._calls = calls;
}
max() {
return this._and('max');
}
bestCluster(options) {
return this._and('bestCluster', options);
}
props(callback) {
return this._and('props', callback);
}
type(...types) {
return this._and('type', ...types);
}
note(callback) {
return this._and('note', callback);
}
score(scoreOrCallback) {
return this._and('score', scoreOrCallback);
}
atMost(score) {
return this._and('atMost', score);
}
typeIn(...types) {
return this._and('typeIn', ...types);
}
and(...lhss) {
return this._and('and', lhss);
}
_and(method, ...args) {
return new this.constructor(...this._calls.concat({ method, args }));
}
asLhs() {
return this._asSide(Lhs.fromFirstCall(this._calls[0]), this._calls.slice(1));
}
asRhs() {
return this._asSide(new InwardRhs(), this._calls);
}
_asSide(side, calls) {
for (let call of calls) {
side = side[call.method](...call.args);
}
return side;
}
when(pred) {
return this._and('when', pred);
}
}
/**
* A wrapper around a DOM node, storing :term:`types<type>`,
* :term:`scores<score>`, and :term:`notes<note>` that apply to it
*/
class Fnode {
/**
* @arg element The DOM element described by the fnode.
* @arg ruleset The ruleset which created the fnode.
*/
constructor(element, ruleset) {
if (element === undefined) {
throw new Error("Someone tried to make a fnode without specifying the element they're talking about.");
}
/**
* The raw DOM element this fnode describes
*/
this.element = element;
this._ruleset = ruleset;
// A map of type => {score: number, note: anything}. `score` is always
// present and defaults to 1. A note is set iff `note` is present and
// not undefined.
this._types = new Map();
// Note: conserveScore() is temporarily absent in 3.0.
//
// By default, a fnode has an independent score for each of its types.
// However, a RHS can opt to conserve the score of an upstream type,
// carrying it forward into another type. To avoid runaway scores in
// the case that multiple rules choose to do this, we limit the
// contribution of an upstream type's score to being multiplied in a
// single time. In this set, we keep track of which upstream types'
// scores have already been multiplied into each type. LHS fnode => Set
// of types whose score for that node have been multiplied into this
// node's score.
this._conservedScores = new Map();
}
/**
* Return whether the given type is one of the ones attached to the wrapped
* HTML node.
*/
hasType(type) {
// Run type(theType) against the ruleset to make sure this doesn't
// return false just because we haven't lazily run certain rules yet.
this._computeType(type);
return this._types.has(type);
}
/**
* Return the confidence, in the range (0, 1), that the fnode belongs to the
* given type, 0 by default.
*/
scoreFor(type) {
this._computeType(type);
return sigmoid(
this._ruleset.weightedScore(this.scoresSoFarFor(type)) + getDefault(this._ruleset.biases, type, () => 0)
);
}
/**
* Return the fnode's note for the given type, ``undefined`` if none.
*/
noteFor(type) {
this._computeType(type);
return this._noteSoFarFor(type);
}
/**
* Return whether this fnode has a note for the given type.
*
* ``undefined`` is not considered a note and may be overwritten with
* impunity.
*/
hasNoteFor(type) {
this._computeType(type);
return this._hasNoteSoFarFor(type);
}
// -------- Methods below this point are private to the framework. --------
/**
* Return an iterable of the types tagged onto me by rules that have
* already executed.
*/
typesSoFar() {
return this._types.keys();
}
_noteSoFarFor(type) {
return this._typeRecordForGetting(type).note;
}
_hasNoteSoFarFor(type) {
return this._noteSoFarFor(type) !== undefined;
}
/**
* Return the score thus far computed on me for a certain type. Doesn't
* implicitly run any rules. If no score has yet been determined for the
* given type, return undefined.
*/
scoresSoFarFor(type) {
return this._typeRecordForGetting(type).score;
}
/**
* Add a given number to one of our per-type scores. Implicitly assign us
* the given type. Keep track of which rule it resulted from so we can
* later mess with the coeffs.
*/
addScoreFor(type, score, ruleName) {
this._typeRecordForSetting(type).score.set(ruleName, score);
}
/**
* Set the note attached to one of our types. Implicitly assign us that
* type if we don't have it already.
*/
setNoteFor(type, note) {
if (this._hasNoteSoFarFor(type)) {
if (note !== undefined) {
throw new Error(
`Someone (likely the right-hand side of a rule) tried to add a note of type ${type} to an element, but one of that type already exists. Overwriting notes is not allowed, since it would make the order of rules matter.`
);
}
// else the incoming note is undefined and we already have the
// type, so it's a no-op
} else {
// Apply either a type and note or just a type (which means a note
// that is undefined):
this._typeRecordForSetting(type).note = note;
}
}
/**
* Return a score/note record for a type, creating it if it doesn't exist.
*/
_typeRecordForSetting(type) {
return setDefault(this._types, type, () => ({ score: new Map() }));
}
/**
* Manifest a temporary type record for reading, working around the lack of
* a .? operator in JS.
*/
_typeRecordForGetting(type) {
return getDefault(this._types, type, () => ({ score: new Map() }));
}
/**
* Make sure any scores, notes, and type-tagging for the given type are
* computed for my element.
*/
_computeType(theType) {
if (!this._types.has(theType)) {
// Prevent infinite recursion when an A->A rule looks at A's note in a callback.
this._ruleset.get(type(theType));
}
}
}
/**
* Construct and return the proper type of rule class based on the
* inwardness/outwardness of the RHS.
*
* @arg lhs {Lhs} The left-hand side of the rule
* @arg rhs {Rhs} The right-hand side of the rule
* @arg options {object} Other, optional information about the rule.
* Currently, the only recognized option is ``name``, which points to a
* string that uniquely identifies this rule in a ruleset. The name
* correlates this rule with one of the coefficients passed into
* :func:`ruleset`. If no name is given, an identifier is assigned based on
* the index of this rule in the ruleset, but that is, of course, brittle.
*/
function rule(lhs, rhs, options) {
// Since out() is a valid call only on the RHS (unlike type()), we can take
// a shortcut here: any outward RHS will already be an OutwardRhs; we don't
// need to sidetrack it through being a Side. And OutwardRhs has an asRhs()
// that just returns itself.
if (typeof rhs === 'string') {
rhs = out(rhs);
}
return new (rhs instanceof OutwardRhs ? OutwardRule : InwardRule)(lhs, rhs, options);
}
let nextRuleNumber = 0;
function newInternalRuleName() {
return '_' + nextRuleNumber++;
}
/**
* We place the in/out distinction in Rules because it determines whether the
* RHS result is cached, and Rules are responsible for maintaining the rulewise
* cache ruleset.ruleCache.
*/
class Rule {
// abstract
constructor(lhs, rhs, options) {
this.lhs = lhs.asLhs();
this.rhs = rhs.asRhs();
// TODO: Make auto-generated rule names be based on the out types of
// the rules, e.g. _priceish_4. That way, adding rules for one type
// won't make the coeffs misalign for another.
this.name = (options ? options.name : undefined) || newInternalRuleName();
}
/**
* Return a NiceSet of the rules that this one shallowly depends on in the
* given ruleset. In a BoundRuleset, this may include rules that have
* already been executed.
*
* Depend on emitters of any LHS type this rule finalizes. (See
* _typesFinalized for a definition.) Depend on adders of any other LHS
* types (because, after all, we need to know what nodes have that type in
* order to find the set of LHS nodes). This works for simple rules and
* complex ones like and().
*
* Specific examples (where A is a type):
* * A.max->* depends on anything emitting A.
* * Even A.max->A depends on A emitters, because we have to have all the
* scores factored in first. For example, what if we did
* max(A)->score(.5)?
* * A->A depends on anything adding A.
* * A->(something other than A) depends on anything emitting A. (For
* example, we need the A score finalized before we could transfer it to
* B using conserveScore().)
* * A->out() also depends on anything emitting A. Fnode methods aren't
* smart enough to lazily run emitter rules as needed. We could make them
* so if it was shown to be an advantage.
*/
prerequisites(ruleset) {
// Optimization: we could cache the result of this when in a compiled (immutable) ruleset.
// Extend prereqs with rules derived from each of the given types. If
// no rules are found, raise an exception, as that indicates a
// malformed ruleset.
function extendOrThrow(prereqs, types, ruleGetter, verb) {
for (let type of types) {
const rules = ruleGetter(type);
if (rules.length > 0) {
prereqs.extend(rules);
} else {
throw new Error(`No rule ${verb} the "${type}" type, but another rule needs it as input.`);
}
}
}
const prereqs = new NiceSet();
// Add finalized types:
extendOrThrow(prereqs, this._typesFinalized(), (type) => ruleset.inwardRulesThatCouldEmit(type), 'emits');
// Add mentioned types:
// We could say this.lhs.typesMentioned().minus(typesFinalized) as an
// optimization. But since types mentioned are a superset of types
// finalized and rules adding are a subset of rules emitting, we get
// the same result without.
extendOrThrow(prereqs, this.lhs.typesMentioned(), (type) => ruleset.inwardRulesThatCouldAdd(type), 'adds');
return prereqs;
}
/**
* Return the types that this rule finalizes.
*
* To "finalize" a type means to make sure we're finished running all
* possible rules that might change a node's score or notes w.r.t. a given
* type. This is generally done because we're about to use those data for
* something, like computing a new type's score or or an aggregate
* function. Exhaustively, we're about to...
* * change the type of the nodes or
* * aggregate all nodes of a type
*
* This base-class implementation just returns what aggregate functions
* need, since that need spans inward and outward rules.
*
* @return Set of types
*/
_typesFinalized() {
// Get the types that are fed to aggregate functions. Aggregate
// functions are more demanding than a simple type() LHS. A type() LHS
// itself does not finalize its nodes because the things it could do to
// them without changing their type (adding notes, adding to score)
// are immutable or commutative (respectively). Thus, we require a RHS
// type change in order to require finalization of a simple type()
// mention. A max(B), OTOH, is not commutative with other B->B rules
// (imagine type(B).max()->score(.5)), so it must depend on B emitters
// and thus finalize B. (This will have to be relaxed or rethought when
// we do the max()/atMost() optimization. Perhaps we can delegate to
// aggregate functions up in Rule.prerequisites() to ask what their
// prereqs are. If they implement such an optimization, they can reply.
// Otherwise, we can assume they are all the nodes of their type.)
//
// TODO: Could arbitrary predicates (once we implement those) matter
// too? Maybe it's not just aggregations.
const type = this.lhs.aggregatedType();
return type === undefined ? new NiceSet() : new NiceSet([type]);
}
}
/**
* A normal rule, whose results head back into the Fathom knowledgebase, to be
* operated on by further rules.
*/
class InwardRule extends Rule {
// TODO: On construct, complain about useless rules, like a dom() rule that
// doesn't assign a type.
/**
* Return an iterable of the fnodes emitted by the RHS of this rule.
* Side effect: update ruleset's store of fnodes, its accounting of which
* rules are done executing, and its cache of results per type.
*/
results(ruleset) {
if (ruleset.doneRules.has(this)) {
// shouldn't happen
throw new Error(
'A bug in Fathom caused results() to be called on an inward rule twice. That could cause redundant score contributions, etc.'
);
}
const self = this;
// For now, we consider most of what a LHS computes to be cheap, aside
// from type() and type().max(), which are cached by their specialized
// LHS subclasses.
const leftResults = this.lhs.fnodes(ruleset);
// Avoid returning a single fnode more than once. LHSs uniquify
// themselves, but the RHS can change the element it's talking
// about and thus end up with dupes.
const returnedFnodes = new Set();
// Merge facts into fnodes:
forEach(
// leftResult can be either a fnode or a {fnode, rhsTransformer} pair.
function updateFnode(leftResult) {
const leftType = self.lhs.guaranteedType();
// Get a fnode and a RHS transformer, whether a plain fnode is
// returned or a {fnode, rhsTransformer} pair:
const { fnode: leftFnode = leftResult, rhsTransformer = identity } = leftResult;
// Grab the fact from the RHS, and run the LHS's optional
// transformer over it to pick up anything special it wants to
// do:
const fact = rhsTransformer(self.rhs.fact(leftFnode, leftType));
self.lhs.checkFact(fact);
const rightFnode = ruleset.fnodeForElement(fact.element || leftFnode.element);
// If the RHS doesn't specify a type, default to the
// type of the LHS, if any:
const rightType = fact.type || self.lhs.guaranteedType();
if (fact.score !== undefined) {
if (rightType !== undefined) {
rightFnode.addScoreFor(rightType, fact.score, self.name);
} else {
throw new Error(
`The right-hand side of a rule specified a score (${fact.score}) with neither an explicit type nor one we could infer from the left-hand side.`
);
}
}
if (fact.type !== undefined || fact.note !== undefined) {
// There's a reason to call setNoteFor.
if (rightType === undefined) {
throw new Error(
`The right-hand side of a rule specified a note (${fact.note}) with neither an explicit type nor one we could infer from the left-hand side. Notes are per-type, per-node, so that's a problem.`
);
} else {
rightFnode.setNoteFor(rightType, fact.note);
}
}
returnedFnodes.add(rightFnode);
},
leftResults
);
// Update ruleset lookup tables.
// First, mark this rule as done:
ruleset.doneRules.add(this);
// Then, stick each fnode in typeCache under all applicable types.
// Optimization: we really only need to loop over the types
// this rule can possibly add.
for (let fnode of returnedFnodes) {
for (let type of fnode.typesSoFar()) {
setDefault(ruleset.typeCache, type, () => new Set()).add(fnode);
}
}
return returnedFnodes.values();
}
/**
* Return a Set of the types that could be emitted back into the system.
* To emit a type means to either to add it to a fnode emitted from the RHS
* or to leave it on such a fnode where it already exists.
*/
typesItCouldEmit() {
const rhs = this.rhs.possibleEmissions();
if (!rhs.couldChangeType && this.lhs.guaranteedType() !== undefined) {
// It's a b -> b rule.
return new Set([this.lhs.guaranteedType()]);
} else if (rhs.possibleTypes.size > 0) {
// We can prove the type emission from the RHS alone.
return rhs.possibleTypes;
} else {
throw new Error(
'Could not determine the emitted type of a rule because its right-hand side calls props() without calling typeIn().'
);
}
}
/**
* Return a Set of types I could add to fnodes I output (where the fnodes
* did not already have them).
*/
typesItCouldAdd() {
const ret = new Set(this.typesItCouldEmit());
ret.delete(this.lhs.guaranteedType());
return ret;
}
/**
* Add the types we could change to the superclass's result.
*/
_typesFinalized() {
const self = this;
function typesThatCouldChange() {
const ret = new NiceSet();
// Get types that could change:
const emissions = self.rhs.possibleEmissions();
if (emissions.couldChangeType) {
// Get the possible guaranteed combinations of types on the LHS
// (taking just this LHS into account). For each combo, if the RHS
// adds a type that's not in the combo, the types in the combo get
// unioned into ret.
for (let combo of self.lhs.possibleTypeCombinations()) {
for (let rhsType of emissions.possibleTypes) {
if (!combo.has(rhsType)) {
ret.extend(combo);
break;
}
}
}
}
// Optimization: the possible combos could be later expanded to be
// informed by earlier rules which add the types mentioned in the LHS.
// If the only way for something to get B is to have Q first, then we
// can add Q to each combo and end up with fewer types finalized. Would
// this imply the existence of a Q->B->Q cycle and thus be impossible?
// Think about it. If we do this, we can centralize that logic here,
// rather than repeating it in all the Lhs subclasses).
return ret;
}
return typesThatCouldChange().extend(super._typesFinalized());
}
}
/**
* A rule whose RHS is an out(). This represents a final goal of a ruleset.
* Its results go out into the world, not inward back into the Fathom
* knowledgebase.
*/
class OutwardRule extends Rule {
/**
* Compute the whole thing, including any .through() and .allThrough().
* Do not mark me done in ruleset.doneRules; out rules are never marked as
* done so they can be requested many times without having to cache their
* (potentially big, since they aren't necessarily fnodes?) results. (We
* can add caching later if it proves beneficial.)
*/
results(ruleset) {
/**
* From a LHS's ``{fnode, rhsTransform}`` object or plain fnode, pick off just
* the fnode and return it.
*/
function justFnode(fnodeOrStruct) {
return fnodeOrStruct instanceof Fnode ? fnodeOrStruct : fnodeOrStruct.fnode;
}
return this.rhs.allCallback(map(this.rhs.callback, map(justFnode, this.lhs.fnodes(ruleset))));
}
/**
* @return the key under which the output of this rule will be available
*/
key() {
return this.rhs.key;
}
/**
* OutwardRules finalize all types mentioned.
*/
_typesFinalized() {
return this.lhs.typesMentioned().extend(super._typesFinalized());
}
}
/**
* A shortcut for creating a new :class:`Ruleset`, for symmetry with
* :func:`rule`
*/
function ruleset(rules, coeffs = [], biases = []) {
return new Ruleset(rules, coeffs, biases);
}
/**
* An unbound ruleset. When you bind it by calling :func:`~Ruleset.against()`,
* the resulting :class:`BoundRuleset` will be immutable.
*/
class Ruleset {
/**
* @arg rules {Array} Rules returned from :func:`rule`
* @arg coeffs {Map} A map of rule names to numerical weights, typically
* returned by the :doc:`trainer<training>`. Example:
* ``[['someRuleName', 5.04], ...]``. If not given, coefficients
* default to 1.
* @arg biases {object} A map of type names to neural-net biases. These
* enable accurate confidence estimates. Example: ``[['someType',
* -2.08], ...]``. If absent, biases default to 0.
*/
constructor(rules, coeffs = [], biases = []) {
this._inRules = [];
this._outRules = new Map(); // key -> rule
this._rulesThatCouldEmit = new Map(); // type -> [rules]
this._rulesThatCouldAdd = new Map(); // type -> [rules]
// Private to the framework:
this._coeffs = new Map(coeffs); // rule name => coefficient
this.biases = new Map(biases); // type name => bias
// Separate rules into out ones and in ones, and sock them away. We do
// this here so mistakes raise errors early.
for (let rule of rules) {
if (rule instanceof InwardRule) {
this._inRules.push(rule);
// Keep track of what inward rules can emit or add:
// TODO: Combine these hashes for space efficiency:
const emittedTypes = rule.typesItCouldEmit();
for (let type of emittedTypes) {
setDefault(this._rulesThatCouldEmit, type, () => []).push(rule);
}
for (let type of rule.typesItCouldAdd()) {
setDefault(this._rulesThatCouldAdd, type, () => []).push(rule);
}
} else if (rule instanceof OutwardRule) {
this._outRules.set(rule.key(), rule);
} else {
throw new Error(`This element of ruleset()'s first param wasn't a rule: ${rule}`);
}
}
}
/**
* Commit this ruleset to running against a specific DOM tree or subtree.
*
* When run against a subtree, the root of the subtree is not considered as
* a possible match.
*
* This doesn't actually modify the Ruleset but rather returns a fresh
* :class:`BoundRuleset`, which contains caches and other stateful, per-DOM
* bric-a-brac.
*/
against(doc) {
return new BoundRuleset(
doc,
this._inRules,
this._outRules,
this._rulesThatCouldEmit,
this._rulesThatCouldAdd,
this._coeffs,
this.biases
);
}
/**
* Return all the rules (both inward and outward) that make up this ruleset.
*
* From this, you can construct another ruleset like this one but with your
* own rules added.
*/
rules() {
return Array.from([...this._inRules, ...this._outRules.values()]);
}
}
/**
* A ruleset that is earmarked to analyze a certain DOM
*
* Carries a cache of rule results on that DOM. Typically comes from
* :meth:`~Ruleset.against`.
*/
class BoundRuleset {
/**
* @arg inRules {Array} Non-out() rules
* @arg outRules {Map} Output key -> out() rule
*/
constructor(doc, inRules, outRules, rulesThatCouldEmit, rulesThatCouldAdd, coeffs, biases) {
this.doc = doc;
this._inRules = inRules;
this._outRules = outRules;
this._rulesThatCouldEmit = rulesThatCouldEmit;
this._rulesThatCouldAdd = rulesThatCouldAdd;
this._coeffs = coeffs;
// Private, for the use of only helper classes:
this.biases = biases;
this._clearCaches();
this.elementCache = new WeakMap(); // DOM element => fnode about it
this.doneRules = new Set(); // InwardRules that have been executed. OutwardRules can be executed more than once because they don't change any fnodes and are thus idempotent.
}
/**
* Change my coefficients and biases after construction.
*
* @arg coeffs See the :class:`Ruleset` constructor.
* @arg biases See the :class:`Ruleset` constructor.
*/
setCoeffsAndBiases(coeffs, biases = []) {
// Destructuring assignment doesn't make it through rollup properly
// (https://github.com/rollup/rollup-plugin-commonjs/issues/358):
this._coeffs = new Map(coeffs);
this.biases = new Map(biases);
this._clearCaches();
}
/**
* Clear the typeCache and maxCache, usually in the wake of changing
* ``this._coeffs``, because both of thise depend on weighted scores.
*/
_clearCaches() {
this.maxCache = new Map(); // type => Array of max fnode (or fnodes, if tied) of this type
this.typeCache = new Map(); // type => Set of all fnodes of this type found so far. (The dependency resolution during execution ensures that individual types will be comprehensive just in time.)
}
/**
* Return an array of zero or more fnodes.
* @arg thing {string|Lhs|Node} Can be
*
* (1) A string which matches up with an "out" rule in the ruleset.
* If the out rule uses through(), the results of through's
* callback (which might not be fnodes) will be returned.
* (2) An arbitrary LHS which we calculate and return the results of.
* (3) A DOM node, for which we will return the corresponding fnode.
*
* Results are cached for cases (1) and (3).
*/
get(thing) {
if (typeof thing === 'string') {
if (this._outRules.has(thing)) {
return Array.from(this._execute(this._outRules.get(thing)));
} else {
throw new Error(`There is no out() rule with key "${thing}".`);
}
} else if (isDomElement(thing)) {
// Return the fnode and let it run type(foo) on demand, as people
// ask it things like scoreFor(foo).
return this.fnodeForElement(thing);
} else if (thing.asLhs !== undefined) {
// Make a temporary out rule, and run it. This may add things to
// the ruleset's cache, but that's fine: it doesn't change any
// future results; it just might make them faster. For example, if
// you ask for .get(type('smoo')) twice, the second time will be a
// cache hit.
const outRule = rule(thing, out(Symbol('outKey')));
return Array.from(this._execute(outRule));
} else {
throw new Error(
'ruleset.get() expects a string, an expression like on the left-hand side of a rule, or a DOM node.'
);
}
}
/**
* Return the weighted sum of the per-rule, per-type scores from a fnode.
*
* @arg mapOfScores a Map of rule name to the [0, 1] score it computed for
* the type in question
*/
weightedScore(mapOfScores) {
let total = 0;
for (const [name, score] of mapOfScores) {
total += score * getDefault(this._coeffs, name, () => 1);
}
return total;
}
// Provide an opaque context object to be made available to all ranker
// functions.
// context (object) {
// self.context = object;
// }
// -------- Methods below this point are private to the framework. --------
/**
* Return all the thus-far-unexecuted rules that will have to run to run
* the requested rule, in the form of Map(prereq: [rulesItIsNeededBy]).
*/
_prerequisitesTo(rule, undonePrereqs = new Map()) {
for (let prereq of rule.prerequisites(this)) {
if (!this.doneRules.has(prereq)) {
// prereq is not already run. (If it were, we wouldn't care
// about adding it to the graph.)
const alreadyAdded = undonePrereqs.has(prereq);
setDefault(undonePrereqs, prereq, () => []).push(rule);
// alreadyAdded means we've already computed the prereqs of
// this prereq and added them to undonePrereqs. So, now
// that we've hooked up the rule to this prereq in the
// graph, we can stop. But, if we haven't, then...
if (!alreadyAdded) {
this._prerequisitesTo(prereq, undonePrereqs);
}
}
}
return undonePrereqs;
}
/**
* Run the given rule (and its dependencies, in the proper order), and
* return its results.
*
* The caller is responsible for ensuring that _execute() is not called
* more than once for a given InwardRule, lest non-idempotent
* transformations, like score contributions, be applied to fnodes more
* than once.
*
* The basic idea is to sort rules in topological order (according to input
* and output types) and then run them. On top of that, we do some
* optimizations. We keep a cache of results by type (whether partial or
* comprehensive--either way, the topology ensures that any
* non-comprehensive typeCache entry is made comprehensive before another
* rule needs it). And we prune our search for prerequisite rules at the
* first encountered already-executed rule.
*/
_execute(rule) {
const prereqs = this._prerequisitesTo(rule);
let sorted;
try {
sorted = [rule].concat(toposort(prereqs.keys(), (prereq) => prereqs.get(prereq)));
} catch (exc) {
if (exc instanceof CycleError) {
throw new CycleError('There is a cyclic dependency in the ruleset.');
} else {
throw exc;
}
}
let fnodes;
for (let eachRule of reversed(sorted)) {
// Sock each set of results away in this.typeCache:
fnodes = eachRule.results(this);
}
return Array.from(fnodes);
}
/** @return {Rule[]} */
inwardRulesThatCouldEmit(type) {
return getDefault(this._rulesThatCouldEmit, type, () => []);
}
/** @return {Rule[]} */
inwardRulesThatCouldAdd(type) {
return getDefault(this._rulesThatCouldAdd, type, () => []);
}
/**
* @return the Fathom node that describes the given DOM element. This does
* not trigger any execution, so the result may be incomplete.
*/
fnodeForElement(element) {
return setDefault(this.elementCache, element, () => new Fnode(element, this));
}
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const version = '3.7.3';
export {
Fnode,
and,
atMost,
clusters$1 as clusters,
dom,
domQuery,
element,
exceptions,
nearest,
note,
out,
props,
rule,
ruleset,
score,
type,
typeIn,
utilsForFrontend as utils,
version,
};
| 7,702
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/fathom/index.d.ts
|
import { Fnode, rule, ruleset } from './fathom.js';
import * as fathomWeb from './fathom.js';
export { fathomWeb as fathom };
declare const FORM_CLUSTER_ATTR = 'data-protonpass-form';
declare const kFieldSelector = 'input, select, textarea';
declare const kEmailSelector = 'input[name="email"], input[id="email"]';
declare const kPasswordSelector = 'input[type="password"], input[type="text"][id="password"]';
declare const kCaptchaSelector = '[class*="captcha"], [id*="captcha"], [name*="captcha"]';
declare const kSocialSelector = '[class*=social], [aria-label*=with]';
declare const kEditorSelector =
'div[class*="editor" i], div[id*="editor" i], div[class*="composer" i], div[id*="composer" i]';
declare const kDomGroupSelector =
'[role="dialog"], [role="tabpanel"], [role="group"], [role="form"], [id*="modal"], [class*="modal"], header, section, nav, footer, aside';
declare const kUsernameSelector: string;
declare const kHiddenUsernameSelector: string;
declare const kHeadingSelector: string;
declare const kButtonSubmitSelector: string;
declare const kLayoutSelector = 'div, section, aside, main, nav';
declare const kAnchorLinkSelector = 'a, span[role="button"]';
declare const formCandidateSelector: string;
declare const inputCandidateSelector =
'input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="image"]):not([type="checkbox"])';
declare const buttonSelector: string;
declare const otpSelector = '[type="tel"], [type="number"], [type="text"], input:not([type])';
type AnyRule = ReturnType<typeof rule>;
type Ruleset = ReturnType<typeof ruleset>;
type BoundRuleset = ReturnType<Ruleset['against']>;
type Coeff = [string, number];
type Bias = [string, number];
type RulesetAggregation = {
rules: AnyRule[];
coeffs: Coeff[];
biases: Bias[];
};
type TrainingResults = {
coeffs: Coeff[];
bias: number;
cutoff: number;
};
type Trainee = TrainingResults & {
name: string;
getRules: () => AnyRule[];
};
declare enum FormType {
LOGIN = 'login',
REGISTER = 'register',
PASSWORD_CHANGE = 'password-change',
RECOVERY = 'recovery',
MFA = 'mfa',
NOOP = 'noop',
}
declare enum FieldType {
EMAIL = 'email',
USERNAME = 'username',
USERNAME_HIDDEN = 'username-hidden',
PASSWORD_CURRENT = 'password',
PASSWORD_NEW = 'new-password',
OTP = 'otp',
}
declare const formTypes: FormType[];
declare const fieldTypes: FieldType[];
declare const trainees: {
forms: Record<string, Trainee>;
fields: Record<string, Trainee>;
};
declare const rulesetMaker: () => ReturnType<typeof ruleset>;
declare const TEXT_ATTRIBUTES: string[];
declare const EL_ATTRIBUTES: string[];
declare const FORM_ATTRIBUTES: string[];
declare const FIELD_ATTRIBUTES: string[];
declare const getAttributes: (attributes: string[]) => (el: HTMLElement) => string[];
declare const getBaseAttributes: (el: HTMLElement) => string[];
declare const getTextAttributes: (el: HTMLElement) => string[];
declare const getFieldAttributes: (el: HTMLElement) => string[];
declare const getFormAttributes: (el: HTMLElement) => string[];
declare const splitFieldsByVisibility: (els: HTMLElement[]) => [HTMLElement[], HTMLElement[]];
declare const maybeEmail: (fnode: Fnode) => boolean;
declare const maybePassword: (fnode: Fnode) => boolean;
declare const maybeOTP: (fnode: Fnode) => boolean;
declare const maybeUsername: (fnode: Fnode) => boolean;
declare const maybeHiddenUsername: (fnode: Fnode) => boolean;
declare const isUsernameCandidate: (el: HTMLElement) => boolean;
declare const isEmailCandidate: (el: HTMLElement) => boolean;
declare const isOAuthCandidate: (el: HTMLElement) => boolean;
declare const isSubmitBtnCandidate: (btn: HTMLElement) => boolean;
declare const isProcessableField: (input: HTMLInputElement) => boolean;
declare const isClassifiableField: (fnode: Fnode) => boolean;
declare const selectInputCandidates: (target?: Document | HTMLElement) => HTMLInputElement[];
declare const isCluster: (el: HTMLElement) => boolean;
declare const flagCluster: (el: HTMLElement) => void;
declare const isIgnored: (el: HTMLElement) => boolean;
declare const getIgnoredParent: (el?: HTMLElement) => HTMLElement | null;
declare const flagAsIgnored: (el: HTMLElement) => boolean;
declare const removeIgnoredFlag: (el: HTMLElement) => boolean;
declare const flagSubtreeAsIgnored: (el: HTMLElement) => void;
declare const isProcessed: (el: HTMLElement) => boolean;
declare const flagAsProcessed: (el: HTMLElement) => boolean;
declare const removeProcessedFlag: (el: HTMLElement) => boolean;
declare const isPrediction: (el: HTMLElement) => boolean;
declare const removePredictionFlag: (el: HTMLElement) => boolean;
declare const getParentFormPrediction: (el?: HTMLElement) => HTMLElement | null;
declare const setPrediction: (_el: HTMLElement, type: string) => void;
declare const isPredictedType: (type: string) => (fnode: Fnode) => boolean;
declare const isClassifiable: (form: HTMLElement) => boolean;
declare const removeClassifierFlags: (el: HTMLElement) => void;
declare const getFormParent: (form: HTMLElement) => HTMLElement;
type FormInputIterator = ReturnType<typeof createInputIterator>;
declare const createInputIterator: (form: HTMLElement) => {
prev(input: HTMLElement): HTMLElement | null;
next(input: HTMLElement): HTMLElement | null;
};
declare const selectFormCandidates: (root?: Document | HTMLElement) => HTMLElement[];
declare const prepass: (doc?: Document) => void;
declare const shouldRunClassifier: () => boolean;
type VisibilityCache = WeakMap<HTMLElement, boolean>;
type IsVisibleOptions = {
opacity: boolean;
};
declare const cacheContext: Record<string, VisibilityCache>;
declare const getVisibilityCache: (key: string) => VisibilityCache;
declare const clearVisibilityCache: () => void;
declare const isVisible: (fnodeOrElement: Fnode | HTMLElement, options: IsVisibleOptions) => boolean;
declare const isVisibleEl: (el: HTMLElement) => boolean;
declare const isVisibleForm: (form: HTMLElement) => boolean;
declare const isVisibleField: (field: HTMLElement) => boolean;
declare const clearDetectionCache: () => void;
export {
type AnyRule,
type Bias,
type BoundRuleset,
type Coeff,
EL_ATTRIBUTES,
FIELD_ATTRIBUTES,
FORM_ATTRIBUTES,
FORM_CLUSTER_ATTR,
FieldType,
type FormInputIterator,
FormType,
type Ruleset,
type RulesetAggregation,
TEXT_ATTRIBUTES,
type Trainee,
type TrainingResults,
buttonSelector,
cacheContext,
clearDetectionCache,
clearVisibilityCache,
createInputIterator,
fieldTypes,
flagAsIgnored,
flagAsProcessed,
flagCluster,
flagSubtreeAsIgnored,
formCandidateSelector,
formTypes,
getAttributes,
getBaseAttributes,
getFieldAttributes,
getFormAttributes,
getFormParent,
getIgnoredParent,
getParentFormPrediction,
getTextAttributes,
getVisibilityCache,
inputCandidateSelector,
isClassifiable,
isClassifiableField,
isCluster,
isEmailCandidate,
isIgnored,
isOAuthCandidate,
isPredictedType,
isPrediction,
isProcessableField,
isProcessed,
isSubmitBtnCandidate,
isUsernameCandidate,
isVisible,
isVisibleEl,
isVisibleField,
isVisibleForm,
kAnchorLinkSelector,
kButtonSubmitSelector,
kCaptchaSelector,
kDomGroupSelector,
kEditorSelector,
kEmailSelector,
kFieldSelector,
kHeadingSelector,
kHiddenUsernameSelector,
kLayoutSelector,
kPasswordSelector,
kSocialSelector,
kUsernameSelector,
maybeEmail,
maybeHiddenUsername,
maybeOTP,
maybePassword,
maybeUsername,
otpSelector,
prepass,
removeClassifierFlags,
removeIgnoredFlag,
removePredictionFlag,
removeProcessedFlag,
rulesetMaker,
selectFormCandidates,
selectInputCandidates,
setPrediction,
shouldRunClassifier,
splitFieldsByVisibility,
trainees,
};
| 7,703
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/fathom/index.js
|
import { clusters as clusters$1, dom, out, rule, ruleset, score, type, utils } from './fathom.js';
import * as fathomWeb from './fathom.js';
export { fathomWeb as fathom };
const MAX_FORM_FIELD_WALK_UP = 3;
const MAX_FORM_HEADING_WALK_UP = 3;
const MAX_HEADING_HORIZONTAL_DIST = 75;
const MAX_HEADING_VERTICAL_DIST = 150;
const MIN_AREA_SUBMIT_BTN = 3500;
const MIN_FIELD_HEIGHT = 15;
const MIN_FIELD_WIDTH = 30;
const MAX_INPUTS_PER_FORM = 40;
const MAX_FIELDS_PER_FORM = 60;
const MAX_HIDDEN_FIELD_VALUE_LENGTH = 320;
const HIDDEN_FIELD_IGNORE_VALUES = ['0', '1', 'true', 'false'];
const OTP_PATTERNS = [
[1, 'd*'],
[6, 'd{6}'],
[1, '[0-9]*'],
[6, '[0-9]{6}'],
[5, '([0-9a-fA-F]{5}-?[0-9a-fA-F]{5})'],
];
const VALID_INPUT_TYPES = ['text', 'email', 'number', 'tel', 'password', 'hidden', 'search'];
const sanitizeString = (str) =>
str
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9\d\[\]]/g, '');
const LOGIN_RE =
/(?:(?:n(?:ouvelleses|uevase|ewses)s|iniciarses|connex)io|anmeldedate|sign[io])n|in(?:iciarsessao|troduce)|a(?:uthenticate|nmeld(?:ung|en))|authentifier|s(?:econnect|identifi)er|novasessao|(?:introduci|conecta|entr[ae])r|prihlasit|connect|acceder|login/i;
const REGISTER_RE =
/kontoerstellen|cr(?:ea(?:teaccount|rcuenta)|iarconta)|(?:nouveaucompt|creeruncompt|s?inscrir|unirs)e|re(?:gist(?:r(?:ieren|arse|ar)|er)|joindre)|nuevacuenta|neueskonto|getstarted|newaccount|novaconta|(?:com(?:mence|eca)|(?:empez|junt)a)r|signup|join/i;
const RECOVERY_RE =
/(?:wiederherstell|zurucksetz)en|re(?:(?:initialis|stablec)er|(?:defini|staur[ae])r|c(?:uper[ae]|ove)r|set)|problem|(?:troubl|restor|aid)e|a[jy]uda|h(?:ilfe|elp)/i;
const MULTI_STEP_RE = /p(?:rogres(?:s(?:ion|o)|o)|aso)|fortschritt|progress|s(?:chritt|t(?:age|ep))|etap[ae]|phase/i;
const TROUBLE_RE =
/schwierigkeit|(?:difficult|troubl|oubli|hilf)e|i(?:nciden(?:cia|t)|ssue)|vergessen|esquecido|olvidado|needhelp|questao|problem|forgot|ayuda/i;
const PASSWORD_RE =
/p(?:hrasesecrete|ass(?:(?:phras|cod)e|wor[dt]))|(?:c(?:havesecret|lavesecret|ontrasen)|deseguranc)a|(?:(?:zugangs|secret)cod|clesecret)e|codesecret|motdepasse|geheimnis|secret|heslo|senha|key/i;
const PASSWORD_OUTLIER_RE = /socialsecurity|nationalid/i;
const USERNAME_RE =
/identi(?:fiant|ty)|u(?:tilisateur|s(?:ername|uario))|(?:identifi|benutz)er|(?:screen|nick)name|nutzername|(?:anmeld|handl)e|pseudo/i;
const USERNAME_ATTR_RE = /identifyemail|(?:custom|us)erid|loginname|a(?:cc(?:ountid|t)|ppleid)|loginid/i;
const USERNAME_OUTLIER_RE =
/(?:nom(?:defamill|br)|tit[lr])e|(?:primeiro|sobre)nome|(?:company|middle|nach|vor)name|firstname|apellido|lastname|prenom/i;
const EMAIL_RE = /co(?:urriel|rrei?o)|email/i;
const EMAIL_ATTR_RE = /usermail/i;
const CREATE_ACTION_RE = /erstellen|n(?:o(?:uveau|vo)|uevo|e[uw])|cr(?:e(?:a(?:te|r)|er)|iar)|set/i;
const CREATE_ACTION_ATTR_END_RE = /\b.*(?:fst|1)$/i;
const RESET_ACTION_RE =
/(?:a(?:ktualisiere|nder)|zurucksetze)n|(?:re(?:initialise|stablece|defini)|mettreajou)r|a(?:ctualiz|tualiz|lter)ar|c(?:ambiar|hange)|update|reset/i;
const CONFIRM_ACTION_RE =
/digitarnovamente|v(?:olveraescribi|erifi(?:ca|e))r|saisiranouveau|(?:erneuteingeb|wiederhol|bestatig)en|verif(?:izieren|y)|re(?:pe(?:t[ei]r|at)|type)|confirm|again/i;
const CONFIRM_ACTION_ATTR_END_RE = /\b.*(?:snd|bis|2)$/i;
const STEP_ACTION_RE =
/(?:f(?:ertigstell|ortfahr)|abschlie)en|getstarted|siguiente|(?:preceden|suivan|accep)t|(?:finaliza|termin[ae]|anterio|weite)r|co(?:mplet(?:ar|e)|ntinu(?:ar|e))|pro(?:c(?:hain|eed)|ximo)|finish|zuruck|back|next/i;
const REMEMBER_ACTION_RE =
/angemeldetbleiben|lembrardemim|micherinnern|sesouvenirde|re(?:cordarme|member|ster)|manterme|mantener|stay|keep/i;
const SEARCH_ACTION_RE = /recherche|buscar|s(?:earch|uche)|query/i;
const CURRENT_VALUE_RE =
/(?:be(?:stehend|for)|vorherig|aktuell)e|exist(?:ente|ing)|pre(?:cedent|vious)|a(?:n(?:t(?:erior|igo)|cien)|ctu[ae]l|tual)|existant|dernier|current|(?:ultim|viej)o|(?:letz|al)te|last|old/i;
const HIDDEN_ATTR_RE = /s(?:creenreade)?ronly|(?:move)?offscreen|(?:displaynon|a11yhid)e|hidden/i;
const OAUTH_ATTR_RE = /facebook|twitch|google|apple/i;
const TOS_RE =
/(?:datenschutzrichtlini|politicadeprivacidad|confidentialit|a(?:cknowledg|gre))e|nutzungsbedingungen|(?:consentimi?ent|ac(?:ue|o)rd)o|(?:einwillig|zustimm)ung|consentement|condi(?:cione|tion)s|term(?:osdeuso|inos|sof)|(?:privacida|understan)d|guideline|consent|p(?:riva|oli)cy|accord/i;
const MFA_ACTION_RE = /enter(?:auth)?code|confirm|verify/i;
const MFA_RE =
/(?:authentifizierung|doisfatore|doispasso)s|(?:auth(?:entication)?cod|(?:securityc|codig)od|doubleetap|coded)e|(?:authentication|generator)app|(?:(?:authentifica|doublefac)teu|(?:(?:authentifika|doblefac|zweifak|twofac)t|aut(?:henticat|enticad))o)r|verifica(?:c(?:ion|ao)|tion)|multifa(?:ct(?:eu|o)|k?to)r|zweischritte|generadora|doblepaso|2(?:s(?:chritte|tep)|(?:etap[ae]|paso)s|fa)|twostep/i;
const MFA_ATTR_RE =
/phoneverification|(?:approvals|login)code|c(?:odeinput|hallenge)|two(?:factor|step)|twofa|tfa|[2m]fa/i;
const OTP_ATTR_RE = /totp(?:pin)?|o(?:netime|t[cp])|1time/i;
const OTP_OUTLIER_RE =
/n(?:(?:ue|o)vocodigo|ouveaucode|e(?:usenden|(?:uer|w)code))|re(?:enviar|send)|envoyer|senden|enviar|send/i;
const OTP_OUTLIER_ATTR_RE = /(?:phone(?:verification)?|email|tel)pin|email|sms/i;
const NEWSLETTER_RE = /newsletter|b(?:ul|o)letin|mailing/i;
const NEWSLETTER_ATTR_RE = /subscription|mailinglist|newsletter|emailform/i;
const EMAIL_VALUE_RE = /^[\w\-\.]+@([\w-]+\.)+[\w-]{2,5}$/;
const TEL_VALUE_RE = /^[\d()+-]{6,25}$/;
const USERNAME_VALUE_RE = /^[\w\-\.]{7,30}$/;
const reSanityCheck = (cb, options) => (str) => {
if (options.maxLength && str.length > options.maxLength) return false;
if (options.minLength && str.length < options.minLength) return false;
return cb(str);
};
const notRe = (reg, options) => (str) => !test(reg, options)(str);
const andRe = (reg, options) => and(reg.map((re) => test(re, options)));
const orRe = (reg, options) => or(reg.map((re) => test(re, options)));
const test = (re, options) =>
reSanityCheck(
(str) => re.test(str),
options !== null && options !== void 0
? options
: {
maxLength: 5e3,
minLength: 2,
}
);
const and = (tests) => (str) => tests.every((test) => test(str));
const or = (tests) => (str) => tests.some((test) => test(str));
const any = (test) => (strs) => strs.some(test);
const matchLogin = test(LOGIN_RE);
const matchRegister = test(REGISTER_RE);
const matchUsername = test(USERNAME_RE);
const matchUsernameAttr = orRe([USERNAME_ATTR_RE, USERNAME_RE]);
const matchUsernameValue = test(USERNAME_VALUE_RE);
const matchUsernameOutlier = test(USERNAME_OUTLIER_RE);
const matchEmailAttr = orRe([EMAIL_ATTR_RE, EMAIL_RE]);
const matchEmailValue = test(EMAIL_VALUE_RE, {
maxLength: 230,
minLength: 5,
});
const matchEmail = or([test(EMAIL_RE), matchEmailValue]);
const matchTelValue = test(TEL_VALUE_RE, {
maxLength: 25,
minLength: 6,
});
const matchRememberMe = test(REMEMBER_ACTION_RE);
const matchTOS = test(TOS_RE);
const matchTrouble = test(TROUBLE_RE);
const matchRecovery = orRe([RECOVERY_RE, TROUBLE_RE]);
const matchMultiStep = test(MULTI_STEP_RE);
const matchStepAction = orRe([STEP_ACTION_RE, MULTI_STEP_RE]);
const matchOAuth = test(OAUTH_ATTR_RE);
const matchSearchAction = test(SEARCH_ACTION_RE);
const matchPasswordReset = and([andRe([PASSWORD_RE, RESET_ACTION_RE]), notRe(CONFIRM_ACTION_RE)]);
const matchPasswordResetAttr = and([matchPasswordReset, notRe(CONFIRM_ACTION_ATTR_END_RE)]);
const matchPasswordCreate = and([andRe([PASSWORD_RE, CREATE_ACTION_RE]), notRe(CONFIRM_ACTION_RE)]);
const matchPasswordCreateAttr = and([matchPasswordCreate, notRe(CONFIRM_ACTION_ATTR_END_RE)]);
const matchPasswordConfirm = andRe([PASSWORD_RE, CONFIRM_ACTION_RE]);
const matchPasswordConfirmAttr = and([andRe([PASSWORD_RE, CONFIRM_ACTION_RE]), notRe(CREATE_ACTION_ATTR_END_RE)]);
const matchPasswordCurrent = and([andRe([PASSWORD_RE, CURRENT_VALUE_RE]), notRe(CONFIRM_ACTION_RE)]);
const matchPasswordCurrentAttr = and([matchPasswordCurrent, notRe(CONFIRM_ACTION_ATTR_END_RE)]);
const matchPasswordOutlier = test(PASSWORD_OUTLIER_RE);
const matchHidden = test(HIDDEN_ATTR_RE);
const matchMfaAction = test(MFA_ACTION_RE);
const matchMfa = test(MFA_RE);
const matchMfaAttr = test(MFA_ATTR_RE);
const matchOtpAttr = test(OTP_ATTR_RE);
const matchOtpOutlier = orRe([OTP_OUTLIER_ATTR_RE, OTP_OUTLIER_RE]);
const matchNewsletter = test(NEWSLETTER_RE);
orRe([NEWSLETTER_RE, NEWSLETTER_ATTR_RE]);
const FORM_CLUSTER_ATTR = 'data-protonpass-form';
const kFieldSelector = 'input, select, textarea';
const kEmailSelector = 'input[name="email"], input[id="email"]';
const kPasswordSelector = 'input[type="password"], input[type="text"][id="password"]';
const kCaptchaSelector = `[class*="captcha"], [id*="captcha"], [name*="captcha"]`;
const kSocialSelector = `[class*=social], [aria-label*=with]`;
const kEditorSelector = 'div[class*="editor" i], div[id*="editor" i], div[class*="composer" i], div[id*="composer" i]';
const kDomGroupSelector = `[role="dialog"], [role="tabpanel"], [role="group"], [role="form"], [id*="modal"], [class*="modal"], header, section, nav, footer, aside`;
const kUsernameSelector = [
'input[type="login"]',
'input[type="username"]',
'input[type="search"][name="loginName"]',
'input[type="password"][name="userID"]',
'input[type="password"][name="USERNAME"]',
'input[name="account"]',
'input[name="quickconnect-id"]',
].join(',');
const kHiddenUsernameSelector = [
'[name*="user" i]',
'[id*="user" i]',
'[name*="login" i]',
'[id*="login" i]',
'[name*="email" i]',
'[id*="email" i]',
'[name*="identifier" i]',
'[id*="identifier" i]',
].join(',');
const kHeadingSelector = [
...[1, 2, 3, 4, 5].flatMap((level) => [`h${level}, [aria-level="${level}"]`]),
'[role="heading"]',
'[class*="title"]',
'[class*="header"]',
'[name="title"]',
'div[style*="font-size: 2"]',
'div[style*="font-size: 3"]',
].join(',');
const kButtonSubmitSelector = [
'input[type="submit"]',
'button[id*="password" i]',
'button[type="submit"]',
'button[type="button"]',
'button[name="submit"]',
'a[role="submit"]',
'div[role="button"]',
'div[role="submit"]',
].join(',');
const kLayoutSelector = `div, section, aside, main, nav`;
const kAnchorLinkSelector = `a, span[role="button"]`;
const formCandidateSelector = `form, [${FORM_CLUSTER_ATTR}]`;
const inputCandidateSelector =
'input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="image"]):not([type="checkbox"])';
const buttonSelector = `button:not([type]), a[role="button"], ${kButtonSubmitSelector}`;
const otpSelector = '[type="tel"], [type="number"], [type="text"], input:not([type])';
const cacheContext = {};
const getVisibilityCache = (key) => {
var _a;
return (cacheContext[key] = (_a = cacheContext[key]) !== null && _a !== void 0 ? _a : new WeakMap());
};
const clearVisibilityCache = () => Object.keys(cacheContext).forEach((key) => delete cacheContext[key]);
const withCache = (cacheMap) => (els, visible) => {
els.forEach((el) => cacheMap.set(el, visible));
return visible;
};
const isVisible = (fnodeOrElement, options) => {
const element = utils.toDomElement(fnodeOrElement);
const seen = [element];
const cache = getVisibilityCache(JSON.stringify(options));
if (cache.has(element)) return cache.get(element);
const check = () => {
const elementWindow = utils.windowForElement(element);
const elementRect = element.getBoundingClientRect();
const elementStyle = elementWindow.getComputedStyle(element);
if (elementRect.width === 0 && elementRect.height === 0 && elementStyle.overflow !== 'hidden') return false;
if (elementStyle.visibility === 'hidden') return false;
if (elementRect.x + elementRect.width < 0 || elementRect.y + elementRect.height < 0) return false;
for (const ancestor of utils.ancestors(element)) {
if (ancestor === elementWindow.document.documentElement) continue;
if (cache === null || cache === void 0 ? void 0 : cache.has(ancestor)) {
const cachedVisible = cache.get(ancestor);
if (!cachedVisible) return false;
else continue;
}
const isElement = ancestor === element;
if (!isElement) seen.push(ancestor);
const style = isElement ? elementStyle : elementWindow.getComputedStyle(ancestor);
if (style.opacity === '0' && options.opacity) return false;
if (style.display === 'contents') continue;
const rect = isElement ? elementRect : ancestor.getBoundingClientRect();
if ((rect.width <= 1 || rect.height <= 1) && style.overflow === 'hidden') return false;
if (
style.position === 'fixed' &&
(rect.x >= elementWindow.innerWidth || rect.y >= elementWindow.innerHeight)
)
return false;
}
return true;
};
const visible = check();
return withCache(cache)(seen, visible);
};
const quickVisibilityCheck = (el, options) => {
const cache = getVisibilityCache(JSON.stringify(options));
if (cache.has(el)) return cache.get(el);
const check = () => {
const rect = el.getClientRects();
if (rect.length === 0) return false;
const classList = Array.from(el.classList).map(sanitizeString);
if (any(matchHidden)(classList)) return false;
const { visibility, display, maxHeight } = getComputedStyle(el);
if (visibility === 'hidden' || display === 'none' || maxHeight === '0px') return false;
if (el.offsetHeight === 0 || el.offsetWidth === 0) return false;
if (el.offsetHeight < options.minHeight || el.offsetWidth < options.minWidth) return false;
return true;
};
return withCache(cache)([el], check());
};
const isVisibleEl = (el) =>
quickVisibilityCheck(el, {
minHeight: 0,
minWidth: 0,
});
const isVisibleForm = (form) => {
if (
form.tagName !== 'FORM' &&
!isVisible(form, {
opacity: true,
})
)
return false;
const inputs = Array.from(form.querySelectorAll(inputCandidateSelector)).filter((field) => !field.disabled);
return (
inputs.length > 0 &&
inputs.some((input) =>
isVisible(input, {
opacity: false,
})
)
);
};
const isVisibleField = (field) => {
if (field instanceof HTMLInputElement) {
const { type, disabled, readOnly } = field;
if (type === 'hidden' || disabled || readOnly || field.getAttribute('aria-hidden') === 'true') return false;
}
return quickVisibilityCheck(field, {
minHeight: MIN_FIELD_HEIGHT,
minWidth: MIN_FIELD_WIDTH,
});
};
const closest = (start, match) => {
const parent = start.parentElement;
if (!parent) return null;
return match(parent) ? parent : closest(parent, match);
};
const walkUpWhile = (start, maxIterations) => (check) => {
const parent = start.parentElement;
if (maxIterations === 0 || parent === null) return start;
return check(parent, start) ? walkUpWhile(parent, maxIterations - 1)(check) : start;
};
const getNthParent = (el) => (n) => {
const parent = el.parentElement;
return parent === null || n === 0 ? el : getNthParent(parent)(n - 1);
};
const uniqueNodes = (...nodes) => Array.from(new Set(nodes.flat()));
const getNodeRect = (el) => {
const { height, width, top, bottom } = el.getBoundingClientRect();
const area = height * width;
return {
height,
width,
top,
bottom,
area,
};
};
const getSiblingWith = (el, match) => {
const prevEl = el.previousElementSibling;
if (prevEl === null) return null;
if (match(prevEl)) return prevEl;
return getSiblingWith(prevEl, match);
};
const getLabelFor = (el) => {
var _a;
const forId = (_a = el.getAttribute('id')) !== null && _a !== void 0 ? _a : el.getAttribute('name');
const label = document.querySelector(`label[for="${forId}"]`);
if (label) return label;
const closest = el.closest('label');
if (closest) return closest;
const siblingLabel = getSiblingWith(el, (sibling) => sibling.tagName === 'LABEL');
if (siblingLabel) return siblingLabel;
const parent = getNthParent(el)(2);
const parentLabels = parent.querySelectorAll('label');
if (parentLabels.length === 1) return parentLabels[0];
const textNodeAbove = getSiblingWith(el, (el) => el instanceof HTMLElement && el.innerText.trim().length > 0);
if (textNodeAbove) return textNodeAbove;
return null;
};
const getRectCenter = (rect) => ({
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
});
const getRectMinDistance = (rectA, rectB) => {
const centerA = getRectCenter(rectA);
const centerB = getRectCenter(rectB);
const dx = Math.abs(centerA.x - centerB.x) - (rectA.width + rectB.width) / 2;
const dy = Math.abs(centerA.y - centerB.y) - (rectA.height + rectB.height) / 2;
return {
dx,
dy,
};
};
const pruneNested = (els) =>
els.reduce((acc, el) => {
for (let i = 0; i <= acc.length - 1; i++) {
if (acc[i] === el) continue;
if (acc[i].contains(el)) return acc;
if (el.contains(acc[i])) {
acc[i] = el;
return acc;
}
}
acc.push(el);
return acc;
}, []);
const getCommonAncestor = (elementA, elementB) => {
if (elementA === elementB) return elementA;
return elementA.contains(elementB)
? elementA
: elementA.parentElement
? getCommonAncestor(elementA.parentElement, elementB)
: elementA;
};
const findStackedParent = (el, cache = [], maxIterations) => {
if (cache.some((group) => group.contains(el))) return null;
const parent = el.parentElement;
if (maxIterations === 0 || !parent) return null;
const computedStyle = getComputedStyle(parent);
const position = computedStyle.getPropertyValue('position');
if (position === 'fixed' || position === 'absolute') {
cache.push(parent);
return parent;
}
return findStackedParent(parent, cache, maxIterations - 1);
};
const findStackedParents = (els, maxIterations) => {
const cache = [];
return els.map((input) => findStackedParent(input, cache, maxIterations)).filter((el) => Boolean(el));
};
const isCluster = (el) => el.getAttribute(FORM_CLUSTER_ATTR) !== null;
const flagCluster = (el) => el.setAttribute(FORM_CLUSTER_ATTR, '');
const isIgnored = (el) => el.__PP_SKIP__ === true;
const getIgnoredParent = (el) => (el ? closest(el, isIgnored) : null);
const flagAsIgnored = (el) => (el.__PP_SKIP__ = true);
const removeIgnoredFlag = (el) => delete el.__PP_SKIP__;
const flagSubtreeAsIgnored = (el) => {
flagAsIgnored(el);
el.querySelectorAll(kFieldSelector).forEach(flagAsIgnored);
};
const isProcessed = (el) => el.__PP_SEEN__ === true;
const flagAsProcessed = (el) => (el.__PP_SEEN__ = true);
const removeProcessedFlag = (el) => delete el.__PP_SEEN__;
const isPrediction = (el) => el.__PP_TYPE__ !== undefined;
const removePredictionFlag = (el) => delete el.__PP_TYPE__;
const getParentFormPrediction = (el) => (el ? closest(el, isPrediction) : null);
const setPrediction = (_el, type) => {
const el = _el;
const currentType = el.__PP_TYPE__;
el.__PP_TYPE__ = currentType ? Array.from(new Set(currentType.split(',').concat(type))).join(',') : type;
};
const isPredictedType = (type) => (fnode) => {
const types = fnode.element.__PP_TYPE__;
return types ? types.split(',').includes(type) : false;
};
const isClassifiable = (form) => !(isPrediction(form) || isIgnored(form));
const removeClassifierFlags = (el) => {
removeProcessedFlag(el);
removePredictionFlag(el);
removeIgnoredFlag(el);
el.querySelectorAll(kFieldSelector).forEach(removeClassifierFlags);
};
var FormType;
(function (FormType) {
FormType['LOGIN'] = 'login';
FormType['REGISTER'] = 'register';
FormType['PASSWORD_CHANGE'] = 'password-change';
FormType['RECOVERY'] = 'recovery';
FormType['MFA'] = 'mfa';
FormType['NOOP'] = 'noop';
})(FormType || (FormType = {}));
var FieldType;
(function (FieldType) {
FieldType['EMAIL'] = 'email';
FieldType['USERNAME'] = 'username';
FieldType['USERNAME_HIDDEN'] = 'username-hidden';
FieldType['PASSWORD_CURRENT'] = 'password';
FieldType['PASSWORD_NEW'] = 'new-password';
FieldType['OTP'] = 'otp';
})(FieldType || (FieldType = {}));
const formTypes = Object.values(FormType);
const fieldTypes = Object.values(FieldType);
const TOLERANCE_LEVEL = 0.5;
const boolInt = (val) => Number(val);
const safeInt = (val, fallback = 0) => (Number.isFinite(val) ? val : fallback);
const throughEffect = (effect) => (fnode) => {
effect(fnode);
return fnode;
};
const typeEffect = (type) =>
throughEffect((fnode) => {
flagAsProcessed(fnode.element);
setPrediction(fnode.element, type);
});
const processFormEffect = throughEffect((fnode) => flagAsProcessed(fnode.element));
const processFieldEffect = throughEffect((fnode) => {
const { visible, type } = fnode.noteFor('field');
if (visible || type === 'hidden') flagAsProcessed(fnode.element);
});
const featureScore = (noteFor, key) =>
score((fnode) => {
const features = fnode.noteFor(noteFor);
if (Array.isArray(key)) return key.map((k) => features[k]).reduce((a, b) => a * b);
return features[key];
});
const getParentFormFnode = (fieldFnode) => {
const field = fieldFnode.element;
const ruleset = fieldFnode._ruleset;
const parentForms = ruleset.get(type('form'));
const form = parentForms.find(({ element }) => element.contains(field));
if (form) return form;
const preDetectedForm = getParentFormPrediction(field);
if (preDetectedForm) return ruleset.get(preDetectedForm);
return null;
};
const belongsToType = (type) => (fnode) => fnode.scoreFor(type) > TOLERANCE_LEVEL;
const getFormTypeScore = (formFnode, type) => {
if (!formFnode) return 0;
if (isPredictedType(type)(formFnode)) return 1;
return formFnode === null || formFnode === void 0 ? void 0 : formFnode.scoreFor(type);
};
const outRuleWithCache = (typeIn, typeOut) => [
rule(type(typeIn).when(isPredictedType(typeOut)), type(`${typeOut}-cache`), {}),
rule(type(`${typeOut}-cache`), type('cache'), {}),
rule(type(typeOut).when(belongsToType(typeOut)), type(`${typeOut}-result`), {}),
rule(type(`${typeOut}-cache`), type(`${typeOut}-result`), {}),
rule(type(`${typeOut}-result`), out(typeOut).through(typeEffect(typeOut)), {}),
];
const combineFeatures = (arr1, arr2) => arr1.flatMap((item1) => arr2.map((item2) => [item1, item2]));
const withFnodeEl = (fn) => (fnode) => fn(fnode.element);
const getFormClassification = (formFnode) => {
const login = getFormTypeScore(formFnode, FormType.LOGIN) > 0.5;
const register = getFormTypeScore(formFnode, FormType.REGISTER) > 0.5;
const pwChange = getFormTypeScore(formFnode, FormType.PASSWORD_CHANGE) > 0.5;
const recovery = getFormTypeScore(formFnode, FormType.RECOVERY) > 0.5;
const mfa = getFormTypeScore(formFnode, FormType.MFA) > 0.5;
const detectionResults = [login, register, pwChange, recovery, mfa];
const noop = detectionResults.every((detected) => !detected);
return {
login,
register,
pwChange,
recovery,
mfa,
noop,
};
};
const isNoopForm = (formFnode) => getFormClassification(formFnode).noop;
const getFormParent = (form) =>
walkUpWhile(form, MAX_FORM_FIELD_WALK_UP)((el) => el.querySelectorAll(formCandidateSelector).length <= 1);
const createInputIterator = (form) => {
const formEls = Array.from(form.querySelectorAll(inputCandidateSelector)).filter(isVisibleField);
return {
prev(input) {
var _a;
const idx = formEls.indexOf(input);
return idx === -1
? null
: (_a = formEls === null || formEls === void 0 ? void 0 : formEls[idx - 1]) !== null && _a !== void 0
? _a
: null;
},
next(input) {
var _a;
const idx = formEls.indexOf(input);
return idx === -1
? null
: (_a = formEls === null || formEls === void 0 ? void 0 : formEls[idx + 1]) !== null && _a !== void 0
? _a
: null;
},
};
};
const selectFormCandidates = (root = document) => {
const candidates = Array.from(root.querySelectorAll(formCandidateSelector));
return candidates.filter((form) => !isIgnored(form));
};
const TEXT_ATTRIBUTES = [
'title',
'aria-label',
'aria-labelledby',
'aria-describedby',
'placeholder',
'autocomplete',
'legend',
];
const EL_ATTRIBUTES = [
'id',
'class',
'role',
'jsaction',
'ng-controller',
'data-bind',
'ng-model',
'v-model',
'v-bind',
'data-testid',
'href',
];
const FORM_ATTRIBUTES = [EL_ATTRIBUTES, 'name', 'action'].flat();
const FIELD_ATTRIBUTES = [EL_ATTRIBUTES, 'name', 'inputmode'].flat();
const getAttributes = (attributes) => (el) =>
attributes
.filter((key) => key !== 'data-fathom')
.map((attr) => el.getAttribute(attr))
.filter(Boolean)
.map(sanitizeString);
const getBaseAttributes = getAttributes(EL_ATTRIBUTES);
const getTextAttributes = getAttributes(TEXT_ATTRIBUTES);
const getFieldAttributes = getAttributes(FIELD_ATTRIBUTES);
const getFormAttributes = getAttributes(FORM_ATTRIBUTES);
const getPageDescriptionText = (doc) => {
var _a;
const pageTitle = doc.title;
const metaDescription = doc.querySelector('meta[name="description"]');
const descriptionContent =
(_a =
metaDescription === null || metaDescription === void 0
? void 0
: metaDescription.getAttribute('content')) !== null && _a !== void 0
? _a
: '';
return sanitizeString(`${pageTitle} ${descriptionContent}`);
};
const getNodeText = (node) => {
const textAttrs = getTextAttributes(node).join('');
return sanitizeString(`${node.innerText}${textAttrs}`);
};
const getNodeAttributes = (node) => sanitizeString(getBaseAttributes(node).join(''));
const getAllNodeHaystacks = (node) => [getNodeText(node), getNodeAttributes(node)];
const getFormText = (form) => {
const textAttrs = getTextAttributes(form).join('');
const fieldsets = Array.from(form.querySelectorAll('fieldset'));
return sanitizeString(
`${textAttrs}${fieldsets.reduce((text, fieldset) => text.concat(getTextAttributes(fieldset).join('')), '')}`
);
};
const getFieldLabelText = (field) => {
const label = getLabelFor(field);
return label ? getNodeText(label) : '';
};
const getFieldHaystacks = (field) => {
const isHiddenInput = field instanceof HTMLInputElement && field.type === 'hidden';
const checkLabel = field instanceof HTMLInputElement && ['text', 'email', 'tel', 'password'].includes(field.type);
const fieldAttrs = getFieldAttributes(field);
const fieldText = isHiddenInput ? '' : getNodeText(field);
const labelText = checkLabel && !isHiddenInput ? getFieldLabelText(field) : '';
return {
fieldAttrs,
fieldText,
labelText,
};
};
const getAllFieldHaystacks = (field) => {
const { fieldAttrs, fieldText, labelText } = getFieldHaystacks(field);
return [fieldText, labelText, ...fieldAttrs];
};
const getNearestHeadingsText = (el) => {
var _a, _b;
const originRect = el.getBoundingClientRect();
const parent = walkUpWhile(
el,
MAX_FORM_HEADING_WALK_UP
)((parentEl, candidate) => {
if (parentEl === document.body) return false;
if (candidate.matches(kDomGroupSelector)) return false;
return true;
});
const headings = Array.from(parent.querySelectorAll(kHeadingSelector)).filter((heading) => {
if (el.contains(heading)) return true;
const headingRect = heading.getBoundingClientRect();
const { dx, dy } = getRectMinDistance(originRect, headingRect);
return dx < MAX_HEADING_HORIZONTAL_DIST && dy < MAX_HEADING_VERTICAL_DIST;
});
const textAbove =
(_b =
(_a =
headings.length === 0
? getSiblingWith(el, (el) => el instanceof HTMLElement && el.innerText.trim().length > 0)
: null) === null || _a === void 0
? void 0
: _a.innerText) !== null && _b !== void 0
? _b
: '';
return sanitizeString(textAbove + headings.map((el) => el.innerText).join(''));
};
const isActiveFieldFNode = (fnode) => {
const { visible, readonly, disabled } = fnode.noteFor('field');
return visible && !readonly && !disabled;
};
const splitFieldsByVisibility = (els) =>
els.reduce(
(acc, el) => {
if (isVisibleField(el)) acc[0].push(el);
else acc[1].push(el);
return acc;
},
[[], []]
);
const fType = (fnode, types) => types.includes(fnode.element.type);
const fMatch = (fnode, selector) => fnode.element.matches(selector);
const fMode = (fnode, inputMode) => fnode.element.inputMode === inputMode;
const fActive = (fn) => (fnode) => fn(fnode) && isActiveFieldFNode(fnode);
const maybeEmail = fActive((fnode) => fType(fnode, ['email', 'text']) || fMode(fnode, 'email'));
const maybePassword = fActive((fnode) => fMatch(fnode, kPasswordSelector));
const maybeOTP = fActive((fnode) => fMatch(fnode, otpSelector));
const maybeUsername = fActive(
(fnode) => (!fMode(fnode, 'email') && fType(fnode, ['text', 'tel'])) || fMatch(fnode, kUsernameSelector)
);
const maybeHiddenUsername = (fnode) => fType(fnode, ['email', 'text', 'hidden']) && !isActiveFieldFNode(fnode);
const isUsernameCandidate = (el) => !el.matches('input[type="email"]') && any(matchUsername)(getAllFieldHaystacks(el));
const isEmailCandidate = (el) => el.matches('input[type="email"]') || any(matchEmail)(getAllFieldHaystacks(el));
const isOAuthCandidate = (el) => any(matchOAuth)(getAllFieldHaystacks(el));
const isSubmitBtnCandidate = (btn) => {
if (btn.getAttribute('type') === 'submit') return true;
if (btn.innerText.trim().length <= 1) return false;
const height = btn.offsetHeight;
const width = btn.offsetWidth;
return height * width > MIN_AREA_SUBMIT_BTN;
};
const isProcessableField = (input) =>
!isProcessed(input) &&
isVisibleField(input) &&
isVisible(input, {
opacity: false,
});
const isClassifiableField = (fnode) => isClassifiable(fnode.element) && getParentFormFnode(fnode) !== null;
const selectInputCandidates = (target = document) =>
Array.from(target.querySelectorAll(inputCandidateSelector)).filter(isClassifiable);
const { linearScale: linearScale$1 } = utils;
const getFormFeatures = (fnode) => {
const form = fnode.element;
const parent = getFormParent(form);
const fields = Array.from(form.querySelectorAll(kFieldSelector));
const visibleFields = fields.filter(isVisibleField);
const doc = form.ownerDocument;
const inputs = fields.filter((el) => el.matches('input:not([type="submit"])'));
const visibleInputs = visibleFields.filter((el) => el.matches('input:not([type="submit"])'));
const fieldsets = form.querySelectorAll('fieldset');
const textareas = visibleFields.filter((el) => el.matches('textarea'));
const selects = visibleFields.filter((el, idx, fields) => {
var _a;
return (
el.matches('select') &&
((_a = fields === null || fields === void 0 ? void 0 : fields[idx + 1]) === null || _a === void 0
? void 0
: _a.type) !== 'tel'
);
});
const optionsCount = selects.reduce((total, el) => total + el.querySelectorAll('option').length, 0);
const submits = visibleFields.filter((el) => el.matches('[type="submit"]'));
const hidden = inputs.filter((el) => el.matches('[type="hidden"]'));
const texts = visibleInputs.filter((el) => el.matches('[type="text"]'));
const usernames = inputs.filter(isUsernameCandidate);
const emails = inputs.filter(isEmailCandidate);
const tels = inputs.filter((el) => el.matches('[type="tel"]'));
const pws = inputs.filter((el) => el.matches(kPasswordSelector));
const [identifiers, hiddenIdentifiers] = splitFieldsByVisibility(uniqueNodes(usernames, emails, tels));
const [passwords, hiddenPasswords] = splitFieldsByVisibility(pws);
const radios = visibleInputs.filter((el) => el.matches('[type="radio"]'));
const checkboxes = visibleInputs.filter((el) => el.matches('[type="checkbox"]'));
const numbers = visibleInputs.filter((el) => el.matches('[type="number"]'));
const dates = visibleInputs.filter((el) => el.matches('[type="date"]'));
const files = visibleInputs.filter((el) => el.matches('[type="file"]'));
const mfas = tels.concat(numbers).concat(texts);
const required = visibleInputs.filter((el) => el.matches('[required]'));
const patterns = visibleInputs.filter((el) => el.matches('[pattern]'));
const minMaxLengths = visibleInputs.filter((el) => el.matches('[minLength], [maxLength]'));
const autofocused = visibleInputs.find((el) => el.matches('input[autofocus]:first-of-type'));
const captchas = parent.querySelectorAll(kCaptchaSelector);
const socialEls = Array.from(parent.querySelectorAll(kSocialSelector));
const btns = Array.from(form.querySelectorAll(buttonSelector));
const submitBtns = btns.filter(isSubmitBtnCandidate);
const btnCandidates = submits.concat(submitBtns);
const anchors = Array.from(form.querySelectorAll(kAnchorLinkSelector)).filter(isVisibleEl);
const oauths = socialEls.concat(submitBtns).filter(isOAuthCandidate);
const layouts = Array.from(form.querySelectorAll(kLayoutSelector));
const autofocusedIsIdentifier = Boolean(autofocused && identifiers.includes(autofocused));
const autofocusedIsPassword = Boolean(autofocused && passwords.includes(autofocused));
const pageDescriptionText = getPageDescriptionText(doc);
const nearestHeadingsText = getNearestHeadingsText(form);
const formTextAttrText = getFormText(form);
const formAttributes = getFormAttributes(form);
const pwHaystack = pws.flatMap(getAllFieldHaystacks);
const identifierHaystack = identifiers.flatMap(getAllFieldHaystacks);
const submitBtnHaystack = btnCandidates.flatMap(getAllFieldHaystacks);
const checkboxesHaystack = checkboxes.flatMap(getAllFieldHaystacks);
const anchorsHaystack = anchors.flatMap(getAllNodeHaystacks);
const mfaInputsHaystack = mfas.flatMap(getAllFieldHaystacks);
const layoutHaystack = layouts.map(getNodeAttributes);
const outlierHaystack = [formTextAttrText, formTextAttrText, nearestHeadingsText];
const pageLogin = matchLogin(pageDescriptionText);
const formTextLogin = matchLogin(formTextAttrText);
const formAttrsLogin = any(matchLogin)(formAttributes);
const headingsLogin = matchLogin(nearestHeadingsText);
const layoutLogin = any(matchLogin)(layoutHaystack);
const rememberMeCheckbox = any(matchRememberMe)(checkboxesHaystack);
const submitLogin = any(matchLogin)(submitBtnHaystack);
const troubleLink = any(matchTrouble)(anchorsHaystack);
const pageRegister = matchRegister(pageDescriptionText);
const formTextRegister = matchRegister(formTextAttrText);
const formAttrsRegister = any(matchRegister)(formAttributes);
const headingsRegister = matchRegister(nearestHeadingsText);
const layoutRegister = any(matchRegister)(layoutHaystack);
const TOSRef = any(matchTOS)(checkboxesHaystack.concat(anchorsHaystack));
const submitRegister = any(matchRegister)(submitBtnHaystack);
const pwNewRegister = any(matchPasswordCreateAttr)(pwHaystack);
const pwConfirmRegister = any(matchPasswordConfirmAttr)(pwHaystack);
const pagePwReset = matchPasswordReset(pageDescriptionText);
const formTextPwReset = matchPasswordReset(formTextAttrText);
const formAttrsPwReset = any(matchPasswordResetAttr)(formAttributes);
const headingsPwReset = matchPasswordReset(nearestHeadingsText);
const layoutPwReset = any(matchPasswordResetAttr)(layoutHaystack);
const pageRecovery = matchRecovery(pageDescriptionText);
const formTextRecovery = matchRecovery(formTextAttrText);
const formAttrsRecovery = any(matchRecovery)(formAttributes);
const headingsRecovery = matchRecovery(nearestHeadingsText);
const layoutRecovery = any(matchRecovery)(layoutHaystack);
const submitRecovery = any(matchRecovery)(submitBtnHaystack);
const identifierRecovery = any(matchRecovery)(identifierHaystack);
const formTextMFA = matchMfa(formTextAttrText);
const formAttrsMFA = any(matchMfaAttr)(formAttributes);
const headingsMFA = matchMfa(nearestHeadingsText);
const layoutMFA = any(matchMfa)(layoutHaystack);
const buttonVerify = any(matchMfaAction)(submitBtnHaystack);
const inputsMFA = any(matchMfaAttr)(mfaInputsHaystack);
const inputsOTP = any(matchOtpAttr)(mfaInputsHaystack);
const linkOTPOutlier = any(matchOtpOutlier)(anchorsHaystack.concat(submitBtnHaystack));
const newsletterForm = any(matchNewsletter)(outlierHaystack);
const searchForm = any(matchSearchAction)(outlierHaystack);
const buttonMultiStep = any(matchStepAction)(submitBtnHaystack);
const headingsMultiStep = matchMultiStep(nearestHeadingsText);
return {
fieldsCount: linearScale$1(visibleFields.length, 1, 5),
inputCount: linearScale$1(visibleInputs.length, 1, 5),
fieldsetCount: linearScale$1(fieldsets.length, 1, 5),
textCount: linearScale$1(texts.length, 0, 3),
textareaCount: linearScale$1(textareas.length, 0, 2),
selectCount: linearScale$1(selects.length, 0, 2),
optionsCount: linearScale$1(optionsCount, 0, 5),
checkboxCount: linearScale$1(checkboxes.length, 0, 2),
radioCount: linearScale$1(radios.length, 0, 5),
identifierCount: linearScale$1(identifiers.length, 0, 2),
hiddenIdentifierCount: linearScale$1(hiddenIdentifiers.length, 0, 2),
hiddenCount: linearScale$1(hidden.length, 0, 5),
passwordCount: linearScale$1(passwords.length, 0, 2),
hiddenPasswordCount: linearScale$1(hiddenPasswords.length, 0, 2),
usernameCount: linearScale$1(usernames.length, 0, 2),
emailCount: linearScale$1(emails.length, 0, 2),
submitCount: linearScale$1(submits.length, 0, 2),
hasTels: boolInt(tels.length > 0),
hasOAuth: boolInt(oauths.length > 0),
hasCaptchas: boolInt(captchas.length > 0),
hasFiles: boolInt(files.length > 0),
hasDate: boolInt(dates.length > 0),
hasNumber: boolInt(numbers.length > 0),
oneVisibleField: boolInt(visibleInputs.length === 1),
twoVisibleFields: boolInt(visibleInputs.length === 2),
threeOrMoreVisibleFields: boolInt(visibleInputs.length >= 3),
noPasswords: boolInt(passwords.length === 0),
onePassword: boolInt(passwords.length === 1),
twoPasswords: boolInt(passwords.length === 2),
threeOrMorePasswords: boolInt(passwords.length >= 3),
noIdentifiers: boolInt(identifiers.length === 0),
oneIdentifier: boolInt(identifiers.length === 1),
twoIdentifiers: boolInt(identifiers.length === 2),
threeOrMoreIdentifiers: boolInt(identifiers.length >= 3),
autofocusedIsIdentifier: boolInt(autofocusedIsIdentifier),
autofocusedIsPassword: boolInt(autofocusedIsPassword),
inputRatio: safeInt(inputs.length / fields.length),
hiddenRatio: safeInt(hidden.length / fields.length),
visibleRatio: safeInt(visibleInputs.length / fields.length),
identifierRatio: safeInt(identifiers.length / visibleFields.length),
emailRatio: safeInt(emails.length / visibleFields.length),
usernameRatio: safeInt(usernames.length / visibleFields.length),
passwordRatio: safeInt(passwords.length / visibleFields.length),
checkboxRatio: safeInt(checkboxes.length / visibleFields.length),
requiredRatio: safeInt(required.length / visibleFields.length),
patternRatio: safeInt(patterns.length / visibleFields.length),
minMaxLengthRatio: safeInt(minMaxLengths.length / visibleFields.length),
pageLogin: boolInt(pageLogin),
formTextLogin: boolInt(formTextLogin),
formAttrsLogin: boolInt(formAttrsLogin),
headingsLogin: boolInt(headingsLogin),
layoutLogin: boolInt(layoutLogin),
rememberMeCheckbox: boolInt(rememberMeCheckbox),
troubleLink: boolInt(troubleLink),
submitLogin: boolInt(submitLogin),
pageRegister: boolInt(pageRegister),
formTextRegister: boolInt(formTextRegister),
formAttrsRegister: boolInt(formAttrsRegister),
headingsRegister: boolInt(headingsRegister),
layoutRegister: boolInt(layoutRegister),
pwNewRegister: boolInt(pwNewRegister),
pwConfirmRegister: boolInt(pwConfirmRegister),
submitRegister: boolInt(submitRegister),
TOSRef: boolInt(TOSRef),
pagePwReset: boolInt(pagePwReset),
formTextPwReset: boolInt(formTextPwReset),
formAttrsPwReset: boolInt(formAttrsPwReset),
headingsPwReset: boolInt(headingsPwReset),
layoutPwReset: boolInt(layoutPwReset),
pageRecovery: boolInt(pageRecovery),
formTextRecovery: boolInt(formTextRecovery),
formAttrsRecovery: boolInt(formAttrsRecovery),
headingsRecovery: boolInt(headingsRecovery),
layoutRecovery: boolInt(layoutRecovery),
identifierRecovery: boolInt(identifierRecovery),
submitRecovery: boolInt(submitRecovery),
formTextMFA: boolInt(formTextMFA),
formAttrsMFA: boolInt(formAttrsMFA),
headingsMFA: boolInt(headingsMFA),
layoutMFA: boolInt(layoutMFA),
buttonVerify: boolInt(buttonVerify),
inputsMFA: boolInt(inputsMFA),
inputsOTP: boolInt(inputsOTP),
linkOTPOutlier: boolInt(linkOTPOutlier),
newsletterForm: boolInt(newsletterForm),
searchForm: boolInt(searchForm),
multiStepForm: boolInt(buttonMultiStep || headingsMultiStep),
multiAuthForm: boolInt(submitRegister && submitLogin),
formInputIterator: createInputIterator(form),
};
};
const FORM_FEATURES = [
'fieldsCount',
'inputCount',
'fieldsetCount',
'textCount',
'textareaCount',
'selectCount',
'optionsCount',
'radioCount',
'identifierCount',
'hiddenIdentifierCount',
'usernameCount',
'emailCount',
'hiddenCount',
'hiddenPasswordCount',
'submitCount',
'hasTels',
'hasOAuth',
'hasCaptchas',
'hasFiles',
'hasDate',
'hasNumber',
'oneVisibleField',
'twoVisibleFields',
'threeOrMoreVisibleFields',
'noPasswords',
'onePassword',
'twoPasswords',
'threeOrMorePasswords',
'noIdentifiers',
'oneIdentifier',
'twoIdentifiers',
'threeOrMoreIdentifiers',
'autofocusedIsIdentifier',
'autofocusedIsPassword',
'visibleRatio',
'inputRatio',
'hiddenRatio',
'identifierRatio',
'emailRatio',
'usernameRatio',
'passwordRatio',
'requiredRatio',
'checkboxRatio',
'pageLogin',
'formTextLogin',
'formAttrsLogin',
'headingsLogin',
'layoutLogin',
'rememberMeCheckbox',
'troubleLink',
'submitLogin',
'pageRegister',
'formTextRegister',
'formAttrsRegister',
'headingsRegister',
'layoutRegister',
'pwNewRegister',
'pwConfirmRegister',
'submitRegister',
'TOSRef',
'pagePwReset',
'formTextPwReset',
'formAttrsPwReset',
'headingsPwReset',
'layoutPwReset',
'pageRecovery',
'formTextRecovery',
'formAttrsRecovery',
'headingsRecovery',
'layoutRecovery',
'identifierRecovery',
'submitRecovery',
'formTextMFA',
'formAttrsMFA',
'headingsMFA',
'layoutMFA',
'buttonVerify',
'inputsMFA',
'inputsOTP',
'linkOTPOutlier',
'newsletterForm',
'searchForm',
'multiStepForm',
'multiAuthForm',
];
const results$a = {
coeffs: [
['login-fieldsCount', 9.260546684265137],
['login-inputCount', 3.3868980407714844],
['login-fieldsetCount', -10.234439849853516],
['login-textCount', 1.1708984375],
['login-textareaCount', -6.201153755187988],
['login-selectCount', -6.244014263153076],
['login-optionsCount', -6.176764011383057],
['login-radioCount', -5.9987874031066895],
['login-identifierCount', -2.961151123046875],
['login-hiddenIdentifierCount', 10.851139068603516],
['login-usernameCount', 9.447742462158203],
['login-emailCount', -8.629166603088379],
['login-hiddenCount', 16.093061447143555],
['login-hiddenPasswordCount', 18.617231369018555],
['login-submitCount', -3.068704843521118],
['login-hasTels', -5.7915825843811035],
['login-hasOAuth', 5.8498687744140625],
['login-hasCaptchas', -2.090794801712036],
['login-hasFiles', -6.0167555809021],
['login-hasDate', -10.732929229736328],
['login-hasNumber', -5.980225563049316],
['login-oneVisibleField', 9.622528076171875],
['login-twoVisibleFields', 5.231987476348877],
['login-threeOrMoreVisibleFields', -10.353397369384766],
['login-noPasswords', -18.85025978088379],
['login-onePassword', 12.314238548278809],
['login-twoPasswords', -14.515039443969727],
['login-threeOrMorePasswords', -6.0650835037231445],
['login-noIdentifiers', -12.99234390258789],
['login-oneIdentifier', -2.68302583694458],
['login-twoIdentifiers', -1.3880155086517334],
['login-threeOrMoreIdentifiers', -7.5584797859191895],
['login-autofocusedIsIdentifier', 11.91942024230957],
['login-autofocusedIsPassword', 37.33961486816406],
['login-visibleRatio', 2.911050796508789],
['login-inputRatio', 3.799626588821411],
['login-hiddenRatio', -24.132291793823242],
['login-identifierRatio', 15.340856552124023],
['login-emailRatio', -2.0597195625305176],
['login-usernameRatio', -21.554241180419922],
['login-passwordRatio', -6.707980632781982],
['login-requiredRatio', 2.429833173751831],
['login-checkboxRatio', 34.79150390625],
['login-pageLogin', 14.611160278320312],
['login-formTextLogin', 8.536316871643066],
['login-formAttrsLogin', 4.859513759613037],
['login-headingsLogin', 16.488920211791992],
['login-layoutLogin', 4.245265483856201],
['login-rememberMeCheckbox', 8.000603675842285],
['login-troubleLink', 20.40095329284668],
['login-submitLogin', 11.593767166137695],
['login-pageRegister', -12.783998489379883],
['login-formTextRegister', 0.052930302917957306],
['login-formAttrsRegister', -15.765278816223145],
['login-headingsRegister', -13.759665489196777],
['login-layoutRegister', -2.7408759593963623],
['login-pwNewRegister', -24.914588928222656],
['login-pwConfirmRegister', -19.122373580932617],
['login-submitRegister', -17.61235809326172],
['login-TOSRef', 2.7695138454437256],
['login-pagePwReset', -6.1394853591918945],
['login-formTextPwReset', -6.047491550445557],
['login-formAttrsPwReset', -7.93905782699585],
['login-headingsPwReset', -11.728208541870117],
['login-layoutPwReset', 1.9481669664382935],
['login-pageRecovery', -2.3499460220336914],
['login-formTextRecovery', -0.05300094932317734],
['login-formAttrsRecovery', -40.93749237060547],
['login-headingsRecovery', -4.877048015594482],
['login-layoutRecovery', -0.7296434044837952],
['login-identifierRecovery', 0.871780276298523],
['login-submitRecovery', -8.45190715789795],
['login-formTextMFA', -0.018208570778369904],
['login-formAttrsMFA', -28.500751495361328],
['login-headingsMFA', -18.91704559326172],
['login-layoutMFA', -4.592078685760498],
['login-buttonVerify', -6.714724540710449],
['login-inputsMFA', -20.373138427734375],
['login-inputsOTP', -30.870197296142578],
['login-linkOTPOutlier', -4.563948631286621],
['login-newsletterForm', -8.15023422241211],
['login-searchForm', -7.200606346130371],
['login-multiStepForm', 3.7781412601470947],
['login-multiAuthForm', 13.921825408935547],
['login-visibleRatio,fieldsCount', -5.210275173187256],
['login-visibleRatio,identifierCount', -15.320694923400879],
['login-visibleRatio,passwordCount', 10.74003791809082],
['login-visibleRatio,hiddenIdentifierCount', -15.647726058959961],
['login-visibleRatio,hiddenPasswordCount', 36.91423034667969],
['login-identifierRatio,fieldsCount', -27.68492889404297],
['login-identifierRatio,identifierCount', 15.424700736999512],
['login-identifierRatio,passwordCount', -13.829729080200195],
['login-identifierRatio,hiddenIdentifierCount', 4.846118927001953],
['login-identifierRatio,hiddenPasswordCount', -10.7938871383667],
['login-passwordRatio,fieldsCount', 9.243396759033203],
['login-passwordRatio,identifierCount', -13.610177040100098],
['login-passwordRatio,passwordCount', -9.334450721740723],
['login-passwordRatio,hiddenIdentifierCount', 32.88718795776367],
['login-passwordRatio,hiddenPasswordCount', 1.4116586446762085],
['login-requiredRatio,fieldsCount', 12.827005386352539],
['login-requiredRatio,identifierCount', -20.5583438873291],
['login-requiredRatio,passwordCount', 16.311241149902344],
['login-requiredRatio,hiddenIdentifierCount', -29.923545837402344],
['login-requiredRatio,hiddenPasswordCount', 18.124889373779297],
],
bias: -6.3730974197387695,
cutoff: 0.48,
};
const FORM_COMBINED_FEATURES = [
...FORM_FEATURES,
...combineFeatures(
['visibleRatio', 'identifierRatio', 'passwordRatio', 'requiredRatio'],
['fieldsCount', 'identifierCount', 'passwordCount', 'hiddenIdentifierCount', 'hiddenPasswordCount']
),
];
const login = {
name: FormType.LOGIN,
coeffs: FORM_COMBINED_FEATURES.map((feat) => {
var _a, _b;
return [
`login-${feat}`,
(_b =
(_a = results$a.coeffs.find(([feature]) => feature === `login-${feat}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$a.bias,
cutoff: results$a.cutoff,
getRules: () => [
rule(type('form'), type(FormType.LOGIN), {}),
...FORM_COMBINED_FEATURES.map((feat) =>
rule(type(FormType.LOGIN), featureScore('form', feat), {
name: `login-${feat}`,
})
),
...outRuleWithCache('form-candidate', FormType.LOGIN),
],
};
const results$9 = {
coeffs: [
['pw-change-fieldsCount', -2.849605083465576],
['pw-change-inputCount', -2.549915075302124],
['pw-change-fieldsetCount', -6.059319972991943],
['pw-change-textCount', -6.019736289978027],
['pw-change-textareaCount', -6.081956386566162],
['pw-change-selectCount', -6.053798198699951],
['pw-change-optionsCount', -6.029593467712402],
['pw-change-radioCount', -6.043890476226807],
['pw-change-identifierCount', -5.4684624671936035],
['pw-change-hiddenIdentifierCount', -3.339617967605591],
['pw-change-usernameCount', -6.082462787628174],
['pw-change-emailCount', -4.619750022888184],
['pw-change-hiddenCount', -4.060936450958252],
['pw-change-hiddenPasswordCount', -6.034674167633057],
['pw-change-submitCount', -3.7810566425323486],
['pw-change-hasTels', -6.03959846496582],
['pw-change-hasOAuth', -6.034022331237793],
['pw-change-hasCaptchas', -6.09065580368042],
['pw-change-hasFiles', -6.076785087585449],
['pw-change-hasDate', -5.976832866668701],
['pw-change-hasNumber', -5.990964889526367],
['pw-change-oneVisibleField', -6.082982540130615],
['pw-change-twoVisibleFields', -3.199659824371338],
['pw-change-threeOrMoreVisibleFields', -0.9176915287971497],
['pw-change-noPasswords', -6.018117427825928],
['pw-change-onePassword', -6.01702880859375],
['pw-change-twoPasswords', 9.116572380065918],
['pw-change-threeOrMorePasswords', 22.571439743041992],
['pw-change-noIdentifiers', -1.1158397197723389],
['pw-change-oneIdentifier', -6.076854705810547],
['pw-change-twoIdentifiers', -6.0351338386535645],
['pw-change-threeOrMoreIdentifiers', 4.4391937255859375],
['pw-change-autofocusedIsIdentifier', -6.042590141296387],
['pw-change-autofocusedIsPassword', 19.56791877746582],
['pw-change-visibleRatio', -3.86659574508667],
['pw-change-inputRatio', -3.968968629837036],
['pw-change-hiddenRatio', -4.739645957946777],
['pw-change-identifierRatio', -5.768206596374512],
['pw-change-emailRatio', -5.145118236541748],
['pw-change-usernameRatio', -5.927550792694092],
['pw-change-passwordRatio', 2.23026967048645],
['pw-change-requiredRatio', -4.440613269805908],
['pw-change-checkboxRatio', -5.908611297607422],
['pw-change-pageLogin', -6.451207637786865],
['pw-change-formTextLogin', -5.944624900817871],
['pw-change-formAttrsLogin', -6.078995704650879],
['pw-change-headingsLogin', -6.092985153198242],
['pw-change-layoutLogin', -6.022044658660889],
['pw-change-rememberMeCheckbox', -5.911662578582764],
['pw-change-troubleLink', -3.6543996334075928],
['pw-change-submitLogin', -5.971057891845703],
['pw-change-pageRegister', -5.91569709777832],
['pw-change-formTextRegister', 0.041428856551647186],
['pw-change-formAttrsRegister', -5.969199180603027],
['pw-change-headingsRegister', -6.03828239440918],
['pw-change-layoutRegister', -5.976802349090576],
['pw-change-pwNewRegister', 11.097345352172852],
['pw-change-pwConfirmRegister', 8.048815727233887],
['pw-change-submitRegister', -7.195167541503906],
['pw-change-TOSRef', -6.861124038696289],
['pw-change-pagePwReset', 15.718603134155273],
['pw-change-formTextPwReset', 23.176179885864258],
['pw-change-formAttrsPwReset', 2.7543129920959473],
['pw-change-headingsPwReset', 17.890968322753906],
['pw-change-layoutPwReset', 17.851831436157227],
['pw-change-pageRecovery', -6.0303263664245605],
['pw-change-formTextRecovery', -0.03785283863544464],
['pw-change-formAttrsRecovery', -6.054781913757324],
['pw-change-headingsRecovery', -5.961613655090332],
['pw-change-layoutRecovery', -3.806657314300537],
['pw-change-identifierRecovery', -6.013106346130371],
['pw-change-submitRecovery', 0.5705376863479614],
['pw-change-formTextMFA', 0.04786650091409683],
['pw-change-formAttrsMFA', -6.017983436584473],
['pw-change-headingsMFA', -6.015376091003418],
['pw-change-layoutMFA', -6.080138206481934],
['pw-change-buttonVerify', -6.1084184646606445],
['pw-change-inputsMFA', -5.995019435882568],
['pw-change-inputsOTP', -5.977421283721924],
['pw-change-linkOTPOutlier', -5.954542636871338],
['pw-change-newsletterForm', -5.9653801918029785],
['pw-change-searchForm', -6.086610317230225],
['pw-change-multiStepForm', -5.942900657653809],
['pw-change-multiAuthForm', -6.06475830078125],
['pw-change-visibleRatio,fieldsCount', -2.5807697772979736],
['pw-change-visibleRatio,identifierCount', -5.702645301818848],
['pw-change-visibleRatio,passwordCount', 2.6345810890197754],
['pw-change-visibleRatio,hiddenIdentifierCount', -2.1961960792541504],
['pw-change-visibleRatio,hiddenPasswordCount', -6.049030303955078],
['pw-change-identifierRatio,fieldsCount', -4.411734104156494],
['pw-change-identifierRatio,identifierCount', -5.406412601470947],
['pw-change-identifierRatio,passwordCount', -4.3397345542907715],
['pw-change-identifierRatio,hiddenIdentifierCount', -6.10110330581665],
['pw-change-identifierRatio,hiddenPasswordCount', -5.99431848526001],
['pw-change-passwordRatio,fieldsCount', 4.848816871643066],
['pw-change-passwordRatio,identifierCount', -4.359196662902832],
['pw-change-passwordRatio,passwordCount', 7.522293567657471],
['pw-change-passwordRatio,hiddenIdentifierCount', 0.12668076157569885],
['pw-change-passwordRatio,hiddenPasswordCount', -6.0297160148620605],
['pw-change-requiredRatio,fieldsCount', -4.642848014831543],
['pw-change-requiredRatio,identifierCount', -5.928743839263916],
['pw-change-requiredRatio,passwordCount', -0.5462040901184082],
['pw-change-requiredRatio,hiddenIdentifierCount', 2.8457155227661133],
['pw-change-requiredRatio,hiddenPasswordCount', -6.076464653015137],
],
bias: -4.067059516906738,
cutoff: 1,
};
const passwordChange = {
name: FormType.PASSWORD_CHANGE,
coeffs: FORM_COMBINED_FEATURES.map((key) => {
var _a, _b;
return [
`pw-change-${key}`,
(_b =
(_a = results$9.coeffs.find(([feature]) => feature === `pw-change-${key}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$9.bias,
cutoff: results$9.cutoff,
getRules: () => [
rule(type('form'), type(FormType.PASSWORD_CHANGE), {}),
...FORM_COMBINED_FEATURES.map((key) =>
rule(type(FormType.PASSWORD_CHANGE), featureScore('form', key), {
name: `pw-change-${key}`,
})
),
...outRuleWithCache('form-candidate', FormType.PASSWORD_CHANGE),
],
};
const results$8 = {
coeffs: [
['register-fieldsCount', 2.1488468647003174],
['register-inputCount', 3.8953444957733154],
['register-fieldsetCount', 4.369948387145996],
['register-textCount', 4.406470775604248],
['register-textareaCount', -0.5395322442054749],
['register-selectCount', -13.801981925964355],
['register-optionsCount', 8.93043041229248],
['register-radioCount', 8.134862899780273],
['register-identifierCount', 6.878338813781738],
['register-hiddenIdentifierCount', 26.6212100982666],
['register-usernameCount', -8.497008323669434],
['register-emailCount', 0.5601682066917419],
['register-hiddenCount', -16.191883087158203],
['register-hiddenPasswordCount', 13.505952835083008],
['register-submitCount', 3.9190540313720703],
['register-hasTels', -0.054031264036893845],
['register-hasOAuth', 5.235856056213379],
['register-hasCaptchas', 4.430254936218262],
['register-hasFiles', -6.080432891845703],
['register-hasDate', 16.213748931884766],
['register-hasNumber', 17.174604415893555],
['register-oneVisibleField', 0.23812611401081085],
['register-twoVisibleFields', 2.9827115535736084],
['register-threeOrMoreVisibleFields', -0.7077833414077759],
['register-noPasswords', -4.2407379150390625],
['register-onePassword', 1.8425089120864868],
['register-twoPasswords', 16.720924377441406],
['register-threeOrMorePasswords', -13.426392555236816],
['register-noIdentifiers', -9.049647331237793],
['register-oneIdentifier', 1.1870161294937134],
['register-twoIdentifiers', 14.631994247436523],
['register-threeOrMoreIdentifiers', 24.357791900634766],
['register-autofocusedIsIdentifier', 5.220548152923584],
['register-autofocusedIsPassword', 9.6756591796875],
['register-visibleRatio', -3.1590821743011475],
['register-inputRatio', -6.091838359832764],
['register-hiddenRatio', 1.232614517211914],
['register-identifierRatio', 1.6158268451690674],
['register-emailRatio', -2.6694180965423584],
['register-usernameRatio', -4.520468711853027],
['register-passwordRatio', 1.4269945621490479],
['register-requiredRatio', -13.119827270507812],
['register-checkboxRatio', -36.96697235107422],
['register-pageLogin', -7.428308486938477],
['register-formTextLogin', -6.030258655548096],
['register-formAttrsLogin', -6.180969715118408],
['register-headingsLogin', -15.461830139160156],
['register-layoutLogin', 11.504278182983398],
['register-rememberMeCheckbox', -13.274555206298828],
['register-troubleLink', -11.467988014221191],
['register-submitLogin', -9.911770820617676],
['register-pageRegister', 3.26921010017395],
['register-formTextRegister', 0.02179713547229767],
['register-formAttrsRegister', 9.021811485290527],
['register-headingsRegister', 16.266944885253906],
['register-layoutRegister', -10.42892074584961],
['register-pwNewRegister', 11.917451858520508],
['register-pwConfirmRegister', 0.8136529922485352],
['register-submitRegister', 26.98970603942871],
['register-TOSRef', 14.791913986206055],
['register-pagePwReset', -7.5938544273376465],
['register-formTextPwReset', -11.517178535461426],
['register-formAttrsPwReset', -6.282402038574219],
['register-headingsPwReset', -25.74250030517578],
['register-layoutPwReset', -47.1105842590332],
['register-pageRecovery', -8.460634231567383],
['register-formTextRecovery', 0.005665786564350128],
['register-formAttrsRecovery', -8.095630645751953],
['register-headingsRecovery', -16.120214462280273],
['register-layoutRecovery', -2.9045565128326416],
['register-identifierRecovery', -16.254348754882812],
['register-submitRecovery', -32.221370697021484],
['register-formTextMFA', -0.021640509366989136],
['register-formAttrsMFA', -10.20312786102295],
['register-headingsMFA', -13.534029006958008],
['register-layoutMFA', 1.495119571685791],
['register-buttonVerify', -5.0718278884887695],
['register-inputsMFA', -3.943760871887207],
['register-inputsOTP', -23.11526870727539],
['register-linkOTPOutlier', 0.9582937955856323],
['register-newsletterForm', -26.404504776000977],
['register-searchForm', -7.863440036773682],
['register-multiStepForm', 8.490460395812988],
['register-multiAuthForm', -14.590228080749512],
['register-visibleRatio,fieldsCount', -5.730635166168213],
['register-visibleRatio,identifierCount', 4.5280656814575195],
['register-visibleRatio,passwordCount', 12.067358016967773],
['register-visibleRatio,hiddenIdentifierCount', -3.656541109085083],
['register-visibleRatio,hiddenPasswordCount', -31.854700088500977],
['register-identifierRatio,fieldsCount', 4.788910388946533],
['register-identifierRatio,identifierCount', 3.06147837638855],
['register-identifierRatio,passwordCount', -33.6225471496582],
['register-identifierRatio,hiddenIdentifierCount', -41.53782653808594],
['register-identifierRatio,hiddenPasswordCount', 15.620370864868164],
['register-passwordRatio,fieldsCount', -0.6039175987243652],
['register-passwordRatio,identifierCount', -37.281211853027344],
['register-passwordRatio,passwordCount', -6.787042617797852],
['register-passwordRatio,hiddenIdentifierCount', 3.7560617923736572],
['register-passwordRatio,hiddenPasswordCount', -13.99930191040039],
['register-requiredRatio,fieldsCount', -1.0972027778625488],
['register-requiredRatio,identifierCount', -3.273120641708374],
['register-requiredRatio,passwordCount', -9.638973236083984],
['register-requiredRatio,hiddenIdentifierCount', 21.952537536621094],
['register-requiredRatio,hiddenPasswordCount', -9.304187774658203],
],
bias: 0.2229500263929367,
cutoff: 0.47,
};
const register = {
name: FormType.REGISTER,
coeffs: FORM_COMBINED_FEATURES.map((key) => {
var _a, _b;
return [
`register-${key}`,
(_b =
(_a = results$8.coeffs.find(([feature]) => feature === `register-${key}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$8.bias,
cutoff: results$8.cutoff,
getRules: () => [
rule(type('form'), type(FormType.REGISTER), {}),
...FORM_COMBINED_FEATURES.map((key) =>
rule(type(FormType.REGISTER), featureScore('form', key), {
name: `register-${key}`,
})
),
...outRuleWithCache('form-candidate', FormType.REGISTER),
],
};
const results$7 = {
coeffs: [
['recovery-fieldsCount', 3.1686480045318604],
['recovery-inputCount', 2.2515103816986084],
['recovery-fieldsetCount', -10.534419059753418],
['recovery-textCount', -2.8417246341705322],
['recovery-textareaCount', -18.28977394104004],
['recovery-selectCount', -13.245671272277832],
['recovery-optionsCount', -16.87846565246582],
['recovery-radioCount', -6.032057762145996],
['recovery-identifierCount', 0.9598401784896851],
['recovery-hiddenIdentifierCount', -9.419584274291992],
['recovery-usernameCount', 9.815361022949219],
['recovery-emailCount', 3.164804458618164],
['recovery-hiddenCount', 2.6905319690704346],
['recovery-hiddenPasswordCount', -11.591835975646973],
['recovery-submitCount', 7.926068305969238],
['recovery-hasTels', -15.413702011108398],
['recovery-hasOAuth', -13.806416511535645],
['recovery-hasCaptchas', 0.5163151025772095],
['recovery-hasFiles', -34.650333404541016],
['recovery-hasDate', -5.912387371063232],
['recovery-hasNumber', -5.987368106842041],
['recovery-oneVisibleField', -6.419887542724609],
['recovery-twoVisibleFields', -1.5245790481567383],
['recovery-threeOrMoreVisibleFields', 4.325897693634033],
['recovery-noPasswords', 1.1998769044876099],
['recovery-onePassword', -10.76146411895752],
['recovery-twoPasswords', -6.276216506958008],
['recovery-threeOrMorePasswords', -6.09953498840332],
['recovery-noIdentifiers', -13.318510055541992],
['recovery-oneIdentifier', 1.204313039779663],
['recovery-twoIdentifiers', 2.660702705383301],
['recovery-threeOrMoreIdentifiers', -7.297881126403809],
['recovery-autofocusedIsIdentifier', -1.659160852432251],
['recovery-autofocusedIsPassword', -6.072286605834961],
['recovery-visibleRatio', 0.3868098855018616],
['recovery-inputRatio', -4.502478122711182],
['recovery-hiddenRatio', -0.1950581967830658],
['recovery-identifierRatio', -0.6852729320526123],
['recovery-emailRatio', 0.05073688179254532],
['recovery-usernameRatio', 8.933812141418457],
['recovery-passwordRatio', -9.400286674499512],
['recovery-requiredRatio', 0.041554152965545654],
['recovery-checkboxRatio', -5.961899280548096],
['recovery-pageLogin', -2.07015323638916],
['recovery-formTextLogin', -6.084650993347168],
['recovery-formAttrsLogin', 0.3745183050632477],
['recovery-headingsLogin', 3.899892568588257],
['recovery-layoutLogin', -11.755548477172852],
['recovery-rememberMeCheckbox', -5.9327073097229],
['recovery-troubleLink', 6.62761116027832],
['recovery-submitLogin', -4.9484028816223145],
['recovery-pageRegister', -11.171113967895508],
['recovery-formTextRegister', -0.004259899258613586],
['recovery-formAttrsRegister', -11.08430290222168],
['recovery-headingsRegister', -3.8516147136688232],
['recovery-layoutRegister', -8.445761680603027],
['recovery-pwNewRegister', -6.089382171630859],
['recovery-pwConfirmRegister', -6.038159370422363],
['recovery-submitRegister', -6.921971797943115],
['recovery-TOSRef', -13.569132804870605],
['recovery-pagePwReset', 7.406122207641602],
['recovery-formTextPwReset', -6.428162097930908],
['recovery-formAttrsPwReset', 12.511506080627441],
['recovery-headingsPwReset', 13.299031257629395],
['recovery-layoutPwReset', 7.199288368225098],
['recovery-pageRecovery', 16.694597244262695],
['recovery-formTextRecovery', 0.02617131918668747],
['recovery-formAttrsRecovery', 21.711151123046875],
['recovery-headingsRecovery', 4.40916109085083],
['recovery-layoutRecovery', 1.7731317281723022],
['recovery-identifierRecovery', 16.085918426513672],
['recovery-submitRecovery', 16.651777267456055],
['recovery-formTextMFA', 0.051208652555942535],
['recovery-formAttrsMFA', 10.673234939575195],
['recovery-headingsMFA', -8.235397338867188],
['recovery-layoutMFA', -6.03088903427124],
['recovery-buttonVerify', 0.6126459240913391],
['recovery-inputsMFA', 6.485626697540283],
['recovery-inputsOTP', -0.4770396649837494],
['recovery-linkOTPOutlier', 0.4108854830265045],
['recovery-newsletterForm', -13.8137845993042],
['recovery-searchForm', -12.360559463500977],
['recovery-multiStepForm', 2.2651278972625732],
['recovery-multiAuthForm', -6.300940036773682],
['recovery-visibleRatio,fieldsCount', 3.260298490524292],
['recovery-visibleRatio,identifierCount', 0.21990321576595306],
['recovery-visibleRatio,passwordCount', -8.673775672912598],
['recovery-visibleRatio,hiddenIdentifierCount', -12.881649017333984],
['recovery-visibleRatio,hiddenPasswordCount', -13.354900360107422],
['recovery-identifierRatio,fieldsCount', 6.22084379196167],
['recovery-identifierRatio,identifierCount', 0.7349469065666199],
['recovery-identifierRatio,passwordCount', -10.594644546508789],
['recovery-identifierRatio,hiddenIdentifierCount', -22.928953170776367],
['recovery-identifierRatio,hiddenPasswordCount', -13.94097900390625],
['recovery-passwordRatio,fieldsCount', -9.976916313171387],
['recovery-passwordRatio,identifierCount', -10.677999496459961],
['recovery-passwordRatio,passwordCount', -8.918004035949707],
['recovery-passwordRatio,hiddenIdentifierCount', -6.067085266113281],
['recovery-passwordRatio,hiddenPasswordCount', -6.0812668800354],
['recovery-requiredRatio,fieldsCount', 6.242189884185791],
['recovery-requiredRatio,identifierCount', 0.7846741080284119],
['recovery-requiredRatio,passwordCount', -8.90123176574707],
['recovery-requiredRatio,hiddenIdentifierCount', 8.217477798461914],
['recovery-requiredRatio,hiddenPasswordCount', -9.673283576965332],
],
bias: -3.87492299079895,
cutoff: 0.5,
};
const recovery = {
name: FormType.RECOVERY,
coeffs: FORM_COMBINED_FEATURES.map((key) => {
var _a, _b;
return [
`recovery-${key}`,
(_b =
(_a = results$7.coeffs.find(([feature]) => feature === `recovery-${key}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$7.bias,
cutoff: results$7.cutoff,
getRules: () => [
rule(type('form'), type(FormType.RECOVERY), {}),
...FORM_COMBINED_FEATURES.map((key) =>
rule(type(FormType.RECOVERY), featureScore('form', key), {
name: `recovery-${key}`,
})
),
...outRuleWithCache('form-candidate', FormType.RECOVERY),
],
};
const results$6 = {
coeffs: [
['mfa-fieldsCount', -1.986028790473938],
['mfa-inputCount', -2.417893171310425],
['mfa-fieldsetCount', 8.618748664855957],
['mfa-textCount', 10.741029739379883],
['mfa-textareaCount', -21.107969284057617],
['mfa-selectCount', -6.036983013153076],
['mfa-optionsCount', -6.089150428771973],
['mfa-radioCount', -5.989146709442139],
['mfa-identifierCount', -2.976684808731079],
['mfa-hiddenIdentifierCount', -2.914689779281616],
['mfa-usernameCount', -3.2611923217773438],
['mfa-emailCount', -6.297138690948486],
['mfa-hiddenCount', -0.5899203419685364],
['mfa-hiddenPasswordCount', -1.1170684099197388],
['mfa-submitCount', 3.2955262660980225],
['mfa-hasTels', 13.675196647644043],
['mfa-hasOAuth', -6.1800312995910645],
['mfa-hasCaptchas', -2.140284776687622],
['mfa-hasFiles', -5.91282320022583],
['mfa-hasDate', -6.000078201293945],
['mfa-hasNumber', 14.798690795898438],
['mfa-oneVisibleField', 5.3741021156311035],
['mfa-twoVisibleFields', -5.333239555358887],
['mfa-threeOrMoreVisibleFields', -1.8359535932540894],
['mfa-noPasswords', -4.526628017425537],
['mfa-onePassword', -5.278433799743652],
['mfa-twoPasswords', -5.979758262634277],
['mfa-threeOrMorePasswords', -6.017874240875244],
['mfa-noIdentifiers', -7.453759670257568],
['mfa-oneIdentifier', -3.9392337799072266],
['mfa-twoIdentifiers', -0.1508341133594513],
['mfa-threeOrMoreIdentifiers', 0.9015580415725708],
['mfa-autofocusedIsIdentifier', -4.173874855041504],
['mfa-autofocusedIsPassword', 8.88188648223877],
['mfa-visibleRatio', 0.1725667119026184],
['mfa-inputRatio', -5.889572620391846],
['mfa-hiddenRatio', 4.6787800788879395],
['mfa-identifierRatio', -2.5309557914733887],
['mfa-emailRatio', -5.6209330558776855],
['mfa-usernameRatio', -4.058542728424072],
['mfa-passwordRatio', -5.722538471221924],
['mfa-requiredRatio', 3.3665359020233154],
['mfa-checkboxRatio', 10.59062385559082],
['mfa-pageLogin', 2.369318962097168],
['mfa-formTextLogin', -6.009958267211914],
['mfa-formAttrsLogin', -1.656536340713501],
['mfa-headingsLogin', -4.8079304695129395],
['mfa-layoutLogin', 0.8272684812545776],
['mfa-rememberMeCheckbox', 9.608478546142578],
['mfa-troubleLink', -4.030245304107666],
['mfa-submitLogin', 2.395260810852051],
['mfa-pageRegister', -0.050235673785209656],
['mfa-formTextRegister', 0.018041975796222687],
['mfa-formAttrsRegister', -4.002821445465088],
['mfa-headingsRegister', -7.619940757751465],
['mfa-layoutRegister', -1.8554503917694092],
['mfa-pwNewRegister', -6.025944232940674],
['mfa-pwConfirmRegister', -6.040721893310547],
['mfa-submitRegister', -6.058624267578125],
['mfa-TOSRef', -2.5561230182647705],
['mfa-pagePwReset', -6.049489498138428],
['mfa-formTextPwReset', -6.06840181350708],
['mfa-formAttrsPwReset', -5.907971382141113],
['mfa-headingsPwReset', -5.974218845367432],
['mfa-layoutPwReset', -5.9922099113464355],
['mfa-pageRecovery', 1.330160140991211],
['mfa-formTextRecovery', -0.0034301504492759705],
['mfa-formAttrsRecovery', -6.100997447967529],
['mfa-headingsRecovery', -6.0003981590271],
['mfa-layoutRecovery', 1.902138352394104],
['mfa-identifierRecovery', -6.056447505950928],
['mfa-submitRecovery', 5.776317119598389],
['mfa-formTextMFA', 0.053553156554698944],
['mfa-formAttrsMFA', 14.734620094299316],
['mfa-headingsMFA', 13.750317573547363],
['mfa-layoutMFA', 14.608585357666016],
['mfa-buttonVerify', 18.474651336669922],
['mfa-inputsMFA', 16.719091415405273],
['mfa-inputsOTP', 19.327695846557617],
['mfa-linkOTPOutlier', -1.056117296218872],
['mfa-newsletterForm', -6.025543212890625],
['mfa-searchForm', -6.527355670928955],
['mfa-multiStepForm', 3.8046202659606934],
['mfa-multiAuthForm', -6.06812858581543],
['mfa-visibleRatio,fieldsCount', 1.3153743743896484],
['mfa-visibleRatio,identifierCount', -2.8759515285491943],
['mfa-visibleRatio,passwordCount', -4.6935200691223145],
['mfa-visibleRatio,hiddenIdentifierCount', -6.843139171600342],
['mfa-visibleRatio,hiddenPasswordCount', -0.27420809864997864],
['mfa-identifierRatio,fieldsCount', -0.4094852805137634],
['mfa-identifierRatio,identifierCount', -1.8246272802352905],
['mfa-identifierRatio,passwordCount', -5.31271505355835],
['mfa-identifierRatio,hiddenIdentifierCount', 0.39803561568260193],
['mfa-identifierRatio,hiddenPasswordCount', 2.3596723079681396],
['mfa-passwordRatio,fieldsCount', -5.3759026527404785],
['mfa-passwordRatio,identifierCount', -5.346388339996338],
['mfa-passwordRatio,passwordCount', -5.632260799407959],
['mfa-passwordRatio,hiddenIdentifierCount', -8.22301197052002],
['mfa-passwordRatio,hiddenPasswordCount', -5.995488166809082],
['mfa-requiredRatio,fieldsCount', -3.7365427017211914],
['mfa-requiredRatio,identifierCount', -2.866434335708618],
['mfa-requiredRatio,passwordCount', -3.930940628051758],
['mfa-requiredRatio,hiddenIdentifierCount', -6.067808628082275],
['mfa-requiredRatio,hiddenPasswordCount', -6.0450439453125],
],
bias: -5.322455883026123,
cutoff: 0.5,
};
const mfa = {
name: FormType.MFA,
coeffs: FORM_COMBINED_FEATURES.map((key) => {
var _a, _b;
return [
`mfa-${key}`,
(_b =
(_a = results$6.coeffs.find(([feature]) => feature === `mfa-${key}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$6.bias,
cutoff: results$6.cutoff,
getRules: () => [
rule(type('form'), type(FormType.MFA), {}),
...FORM_COMBINED_FEATURES.map((key) =>
rule(type(FormType.MFA), featureScore('form', key), {
name: `mfa-${key}`,
})
),
...outRuleWithCache('form-candidate', FormType.MFA),
],
};
const getPasswordFieldFeatures = (fnode) => {
var _a, _b;
const fieldFeatures = fnode.noteFor('field');
const { fieldAttrs, fieldText, labelText, prevField, nextField } = fieldFeatures;
const attrCreate = any(matchPasswordCreateAttr)(fieldAttrs);
const attrCurrent = any(matchPasswordCurrentAttr)(fieldAttrs);
const attrConfirm = any(matchPasswordConfirmAttr)(fieldAttrs);
const attrReset = any(matchPasswordResetAttr)(fieldAttrs);
const textCreate = matchPasswordCreate(fieldText);
const textCurrent = matchPasswordCurrent(fieldText);
const textConfirm = matchPasswordConfirm(fieldText);
const textReset = matchPasswordReset(fieldText);
const labelCreate = matchPasswordCreate(labelText);
const labelCurrent = matchPasswordCurrent(labelText);
const labelConfirm = matchPasswordConfirm(labelText);
const labelReset = matchPasswordReset(labelText);
const passwordOutlier = any(matchPasswordOutlier)(fieldAttrs.concat(labelText, fieldText));
const prevPwHaystack =
prevField && prevField.getAttribute('type') === 'password' ? getAllFieldHaystacks(prevField) : [];
const nextPwHaystack =
nextField && nextField.getAttribute('type') === 'password' ? getAllFieldHaystacks(nextField) : [];
const prevPwCreate = any(matchPasswordCreate)(prevPwHaystack);
const prevPwCurrent = any(matchPasswordCurrent)(prevPwHaystack);
const prevPwConfirm = any(matchPasswordConfirm)(prevPwHaystack);
const nextPwCreate = any(matchPasswordCreate)(nextPwHaystack);
const nextPwCurrent = any(matchPasswordCurrent)(nextPwHaystack);
const nextPwConfirm = any(matchPasswordConfirm)(nextPwHaystack);
return {
loginScore: boolInt(fieldFeatures.isFormLogin),
registerScore: boolInt(fieldFeatures.isFormRegister),
pwChangeScore: boolInt(fieldFeatures.isFormPWChange),
exotic: boolInt(fieldFeatures.isFormNoop),
autocompleteNew: boolInt(fieldFeatures.autocomplete === 'new-password'),
autocompleteCurrent: boolInt(fieldFeatures.autocomplete === 'current-password'),
autocompleteOff: boolInt(fieldFeatures.autocomplete === 'off'),
isOnlyPassword:
(_b = (_a = fieldFeatures.formFeatures) === null || _a === void 0 ? void 0 : _a.onePassword) !== null &&
_b !== void 0
? _b
: 0,
prevPwField: boolInt(prevField !== null),
nextPwField: boolInt(nextField !== null),
attrCreate: boolInt(attrCreate),
attrCurrent: boolInt(attrCurrent),
attrConfirm: boolInt(attrConfirm),
attrReset: boolInt(attrReset),
textCreate: boolInt(textCreate),
textCurrent: boolInt(textCurrent),
textConfirm: boolInt(textConfirm),
textReset: boolInt(textReset),
labelCreate: boolInt(labelCreate),
labelCurrent: boolInt(labelCurrent),
labelConfirm: boolInt(labelConfirm),
labelReset: boolInt(labelReset),
passwordOutlier: boolInt(passwordOutlier),
prevPwCreate: boolInt(prevPwCreate),
prevPwCurrent: boolInt(prevPwCurrent),
prevPwConfirm: boolInt(prevPwConfirm),
nextPwCreate: boolInt(nextPwCreate),
nextPwCurrent: boolInt(nextPwCurrent),
nextPwConfirm: boolInt(nextPwConfirm),
};
};
const PW_FIELD_FEATURES = [
'loginScore',
'registerScore',
'pwChangeScore',
'exotic',
'autocompleteNew',
'autocompleteCurrent',
'autocompleteOff',
'isOnlyPassword',
'prevPwField',
'nextPwField',
'attrCreate',
'attrCurrent',
'attrConfirm',
'attrReset',
'textCreate',
'textCurrent',
'textConfirm',
'textReset',
'labelCreate',
'labelCurrent',
'labelConfirm',
'labelReset',
'prevPwCreate',
'prevPwCurrent',
'prevPwConfirm',
'passwordOutlier',
'nextPwCreate',
'nextPwCurrent',
'nextPwConfirm',
];
const results$5 = {
coeffs: [
['pw-loginScore', 12.8425931930542],
['pw-registerScore', -13.378499031066895],
['pw-pwChangeScore', 2.921213388442993],
['pw-exotic', -12.663826942443848],
['pw-autocompleteNew', -3.51690673828125],
['pw-autocompleteCurrent', 0.7590001821517944],
['pw-autocompleteOff', -4.523982524871826],
['pw-isOnlyPassword', 5.8820366859436035],
['pw-prevPwField', 5.306009292602539],
['pw-nextPwField', -6.745763301849365],
['pw-attrCreate', -5.484086990356445],
['pw-attrCurrent', 3.1155130863189697],
['pw-attrConfirm', -6.409403324127197],
['pw-attrReset', 0.07032205164432526],
['pw-textCreate', -2.6428706645965576],
['pw-textCurrent', 1.7301194667816162],
['pw-textConfirm', -6.27731990814209],
['pw-textReset', -0.1284354329109192],
['pw-labelCreate', -6.91628885269165],
['pw-labelCurrent', 13.543344497680664],
['pw-labelConfirm', -6.303647518157959],
['pw-labelReset', 0.09284727275371552],
['pw-prevPwCreate', -9.341208457946777],
['pw-prevPwCurrent', -12.110845565795898],
['pw-prevPwConfirm', 0.09804551303386688],
['pw-passwordOutlier', -6.297443866729736],
['pw-nextPwCreate', 15.074135780334473],
['pw-nextPwCurrent', -7.233329772949219],
['pw-nextPwConfirm', -6.696846961975098],
],
bias: -6.901088237762451,
cutoff: 0.5,
};
const password = {
name: FieldType.PASSWORD_CURRENT,
coeffs: PW_FIELD_FEATURES.map((key) => {
var _a, _b;
return [
`pw-${key}`,
(_b =
(_a = results$5.coeffs.find(([feature]) => feature === `pw-${key}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$5.bias,
cutoff: results$5.cutoff,
getRules: () => [
rule(type('password-field'), type(FieldType.PASSWORD_CURRENT), {}),
...PW_FIELD_FEATURES.map((key) =>
rule(type(FieldType.PASSWORD_CURRENT), featureScore('password-field', key), {
name: `pw-${key}`,
})
),
...outRuleWithCache('field-candidate', FieldType.PASSWORD_CURRENT),
],
};
const results$4 = {
coeffs: [
['pw[new]-loginScore', -11.79761791229248],
['pw[new]-registerScore', 13.207467079162598],
['pw[new]-pwChangeScore', 0.518919050693512],
['pw[new]-exotic', 15.661911010742188],
['pw[new]-autocompleteNew', 1.3702919483184814],
['pw[new]-autocompleteCurrent', -0.585719108581543],
['pw[new]-autocompleteOff', -1.0984125137329102],
['pw[new]-isOnlyPassword', -2.0054612159729004],
['pw[new]-prevPwField', 1.1099307537078857],
['pw[new]-nextPwField', 9.469817161560059],
['pw[new]-attrCreate', 3.6383402347564697],
['pw[new]-attrCurrent', 1.8213093280792236],
['pw[new]-attrConfirm', 7.772680759429932],
['pw[new]-attrReset', 0.057515159249305725],
['pw[new]-textCreate', 1.7611318826675415],
['pw[new]-textCurrent', -1.4192075729370117],
['pw[new]-textConfirm', -15.807029724121094],
['pw[new]-textReset', -0.022727981209754944],
['pw[new]-labelCreate', 7.953551292419434],
['pw[new]-labelCurrent', -13.997352600097656],
['pw[new]-labelConfirm', 7.937860488891602],
['pw[new]-labelReset', 0.02178335189819336],
['pw[new]-prevPwCreate', 11.071161270141602],
['pw[new]-prevPwCurrent', 9.047843933105469],
['pw[new]-prevPwConfirm', -0.0050661563873291016],
['pw[new]-passwordOutlier', -28.866724014282227],
['pw[new]-nextPwCreate', -11.700383186340332],
['pw[new]-nextPwCurrent', 8.510000228881836],
['pw[new]-nextPwConfirm', 9.286312103271484],
],
bias: -3.1783359050750732,
cutoff: 0.5,
};
const newPassword = {
name: FieldType.PASSWORD_NEW,
coeffs: PW_FIELD_FEATURES.map((key) => {
var _a, _b;
return [
`pw[new]-${key}`,
(_b =
(_a = results$4.coeffs.find(([feature]) => feature === `pw[new]-${key}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$4.bias,
cutoff: results$4.cutoff,
getRules: () => [
rule(type('password-field'), type(FieldType.PASSWORD_NEW), {}),
...PW_FIELD_FEATURES.map((key) =>
rule(type(FieldType.PASSWORD_NEW), featureScore('password-field', key), {
name: `pw[new]-${key}`,
})
),
...outRuleWithCache('field-candidate', FieldType.PASSWORD_NEW),
],
};
const getUsernameFieldFeatures = (fnode) => {
const fieldFeatures = fnode.noteFor('field');
const { fieldAttrs, fieldText, labelText, prevField } = fieldFeatures;
const attrUsername = any(matchUsernameAttr)(fieldAttrs);
const textUsername = matchUsername(fieldText);
const labelUsername = matchUsername(labelText);
const outlierUsername = any(matchUsernameOutlier)(fieldAttrs.concat(fieldText, labelText));
const haystack = fieldAttrs.concat(fieldText).concat(labelText);
const outlier = outlierUsername || any(matchEmailAttr)(haystack);
const loginForm = fieldFeatures.isFormLogin;
const isFirstField = prevField === null;
const loginUsername = loginForm && isFirstField && !outlier;
return {
autocompleteUsername: boolInt(fieldFeatures.autocomplete === 'username'),
autocompleteNickname: boolInt(fieldFeatures.autocomplete === 'nickname'),
autocompleteEmail: boolInt(fieldFeatures.autocomplete === 'email'),
autocompleteOff: boolInt(fieldFeatures.autocomplete === 'off'),
attrUsername: boolInt(attrUsername),
textUsername: boolInt(textUsername),
labelUsername: boolInt(labelUsername),
outlierUsername: boolInt(outlier),
loginUsername: boolInt(loginUsername),
searchField: boolInt(fieldFeatures.searchField),
};
};
const USERNAME_FIELD_FEATURES = [
'autocompleteUsername',
'autocompleteNickname',
'autocompleteEmail',
'autocompleteOff',
'attrUsername',
'textUsername',
'labelUsername',
'outlierUsername',
'loginUsername',
'searchField',
];
const results$3 = {
coeffs: [
['username-autocompleteUsername', 8.4799222946167],
['username-autocompleteNickname', 0.2949698269367218],
['username-autocompleteEmail', -6.826112747192383],
['username-autocompleteOff', -0.30067768692970276],
['username-attrUsername', 17.987205505371094],
['username-textUsername', 15.601824760437012],
['username-labelUsername', 17.35613441467285],
['username-outlierUsername', -0.11823385208845139],
['username-loginUsername', 18.332326889038086],
['username-searchField', -6.9408440589904785],
],
bias: -9.685441970825195,
cutoff: 0.5,
};
const username = {
name: FieldType.USERNAME,
coeffs: USERNAME_FIELD_FEATURES.map((key) => {
var _a, _b;
return [
`username-${key}`,
(_b =
(_a = results$3.coeffs.find(([feature]) => feature === `username-${key}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$3.bias,
cutoff: results$3.cutoff,
getRules: () => [
rule(type('username-field'), type(FieldType.USERNAME), {}),
...USERNAME_FIELD_FEATURES.map((key) =>
rule(type(FieldType.USERNAME), featureScore('username-field', key), {
name: `username-${key}`,
})
),
...outRuleWithCache('field-candidate', FieldType.USERNAME),
],
};
const getHiddenUserFieldFeatures = (fnode) => {
const field = fnode.element;
const fieldFeatures = fnode.noteFor('field');
const { fieldAttrs, autocomplete } = fieldFeatures;
const attrUsername = any(matchUsernameAttr)(fieldAttrs);
const attrEmail = any(matchEmailAttr)(fieldAttrs);
const usernameAttr = field.matches('[name="username"],[id="username"]');
const autocompleteUsername = autocomplete === 'username';
const visibleReadonly =
field.readOnly &&
isVisible(field, {
opacity: true,
}) &&
field.type !== 'hidden';
const valueEmail = matchEmailValue(fieldFeatures.value);
const valueTel = matchTelValue(fieldFeatures.value);
const valueUsername = matchUsernameValue(fieldFeatures.value);
return {
exotic: boolInt(fieldFeatures.isFormNoop),
attrUsername: boolInt(attrUsername),
attrEmail: boolInt(attrEmail),
usernameAttr: boolInt(usernameAttr),
autocompleteUsername: boolInt(autocompleteUsername),
visibleReadonly: boolInt(visibleReadonly),
hiddenEmailValue: boolInt(valueEmail),
hiddenTelValue: boolInt(valueTel),
hiddenUsernameValue: boolInt(valueUsername),
};
};
const HIDDEN_USER_FIELD_FEATURES = [
'exotic',
'attrUsername',
'attrEmail',
'usernameAttr',
'autocompleteUsername',
'visibleReadonly',
'hiddenEmailValue',
'hiddenTelValue',
'hiddenUsernameValue',
];
const results$2 = {
coeffs: [
['username[hidden]-exotic', -7.268867015838623],
['username[hidden]-attrUsername', 14.68941879272461],
['username[hidden]-attrEmail', 13.718717575073242],
['username[hidden]-usernameAttr', 15.945220947265625],
['username[hidden]-autocompleteUsername', 1.195915699005127],
['username[hidden]-visibleReadonly', 13.705889701843262],
['username[hidden]-hiddenEmailValue', 15.474560737609863],
['username[hidden]-hiddenTelValue', 6.844428539276123],
['username[hidden]-hiddenUsernameValue', -0.6306125521659851],
],
bias: -21.708499908447266,
cutoff: 0.5,
};
const usernameHidden = {
name: FieldType.USERNAME_HIDDEN,
coeffs: HIDDEN_USER_FIELD_FEATURES.map((key) => {
var _a, _b;
return [
`username[hidden]-${key}`,
(_b =
(_a = results$2.coeffs.find(([feature]) => feature === `username[hidden]-${key}`)) === null ||
_a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$2.bias,
cutoff: results$2.cutoff,
getRules: () => [
rule(type('username-hidden-field'), type(FieldType.USERNAME_HIDDEN), {}),
...HIDDEN_USER_FIELD_FEATURES.map((key) =>
rule(type(FieldType.USERNAME_HIDDEN), featureScore('username-hidden-field', key), {
name: `username[hidden]-${key}`,
})
),
...outRuleWithCache('field-candidate', FieldType.USERNAME_HIDDEN),
],
};
const getEmailFieldFeatures = (fnode) => {
const field = fnode.element;
const fieldFeatures = fnode.noteFor('field');
const { fieldAttrs, fieldText, labelText } = fieldFeatures;
const typeEmail = fieldFeatures.type === 'email';
const exactAttrEmail = field.matches(kEmailSelector);
const attrEmail = any(matchEmailAttr)(fieldAttrs);
const textEmail = matchEmail(fieldText);
const labelEmail = matchEmail(labelText);
const placeholderEmail = any(or([matchEmailValue, matchEmail]))(field.placeholder.split(' '));
return {
autocompleteUsername: boolInt(fieldFeatures.autocomplete === 'username'),
autocompleteNickname: boolInt(fieldFeatures.autocomplete === 'nickname'),
autocompleteEmail: boolInt(fieldFeatures.autocomplete === 'email'),
autocompleteOff: boolInt(fieldFeatures.autocomplete === 'off'),
typeEmail: boolInt(typeEmail),
exactAttrEmail: boolInt(exactAttrEmail),
attrEmail: boolInt(attrEmail),
textEmail: boolInt(textEmail),
labelEmail: boolInt(labelEmail),
placeholderEmail: boolInt(placeholderEmail),
searchField: boolInt(fieldFeatures.searchField),
};
};
const EMAIL_FIELD_FEATURES = [
'autocompleteUsername',
'autocompleteNickname',
'autocompleteEmail',
'typeEmail',
'exactAttrEmail',
'attrEmail',
'textEmail',
'labelEmail',
'placeholderEmail',
'searchField',
];
const results$1 = {
coeffs: [
['email-autocompleteUsername', 1.1164394617080688],
['email-autocompleteNickname', -0.11852008104324341],
['email-autocompleteEmail', 6.255153656005859],
['email-typeEmail', 14.818696022033691],
['email-exactAttrEmail', 12.930174827575684],
['email-attrEmail', 2.435703992843628],
['email-textEmail', 13.969071388244629],
['email-labelEmail', 16.99106216430664],
['email-placeholderEmail', 14.20310115814209],
['email-searchField', -24.339866638183594],
],
bias: -9.423550605773926,
cutoff: 0.5,
};
const email = {
name: FieldType.EMAIL,
coeffs: EMAIL_FIELD_FEATURES.map((key) => {
var _a, _b;
return [
`email-${key}`,
(_b =
(_a = results$1.coeffs.find(([feature]) => feature === `email-${key}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results$1.bias,
cutoff: results$1.cutoff,
getRules: () => [
rule(type('email-field'), type(FieldType.EMAIL), {}),
...EMAIL_FIELD_FEATURES.map((key) =>
rule(type(FieldType.EMAIL), featureScore('email-field', key), {
name: `email-${key}`,
})
),
...outRuleWithCache('field-candidate', FieldType.EMAIL),
],
};
const { linearScale } = utils;
const getOTPFieldFeatures = (fnode) => {
var _a, _b, _c, _d;
const field = fnode.element;
const fieldFeatures = fnode.noteFor('field');
const { fieldAttrs, fieldText, labelText, prevField, nextField, type, minLength, maxLength } = fieldFeatures;
const form = (_a = fieldFeatures.formFnode) === null || _a === void 0 ? void 0 : _a.element;
const formMfa = fieldFeatures.isFormMFA;
const linkOTPOutlier = Boolean(
(_b = fieldFeatures === null || fieldFeatures === void 0 ? void 0 : fieldFeatures.formFeatures) === null ||
_b === void 0
? void 0
: _b.linkOTPOutlier
);
const formCheckboxCount =
(_d =
(_c = fieldFeatures === null || fieldFeatures === void 0 ? void 0 : fieldFeatures.formFeatures) === null ||
_c === void 0
? void 0
: _c.checkboxCount) !== null && _d !== void 0
? _d
: 0;
const formInnerText = form && formMfa ? form.innerText : '';
const patternOTP = OTP_PATTERNS.some(
([maxLength, pattern]) => field.pattern.includes(pattern) && maxLength === field.maxLength
);
const exactAttr = ['code', 'token', 'otp', 'otc', 'totp'];
const nameMatch = exactAttr.some((match) => field.name === match);
const idMatch = exactAttr.some((match) => field.id === match);
const { area, top, bottom, width } = getNodeRect(field);
const maybeGroup = width < 100;
const prevRect = prevField ? getNodeRect(prevField) : null;
const nextRect = nextField ? getNodeRect(nextField) : null;
const prevCheck =
maybeGroup &&
prevField &&
(prevField === null || prevField === void 0 ? void 0 : prevField.getAttribute('type')) === type;
const nextCheck =
maybeGroup &&
nextField &&
(nextField === null || nextField === void 0 ? void 0 : nextField.getAttribute('type')) === type;
const prevAligned = prevCheck
? top === (prevRect === null || prevRect === void 0 ? void 0 : prevRect.top) &&
bottom === (prevRect === null || prevRect === void 0 ? void 0 : prevRect.bottom)
: false;
const prevArea = prevCheck ? area === (prevRect === null || prevRect === void 0 ? void 0 : prevRect.area) : false;
const nextAligned = nextCheck
? top === (nextRect === null || nextRect === void 0 ? void 0 : nextRect.top) &&
bottom === (nextRect === null || nextRect === void 0 ? void 0 : nextRect.top)
: false;
const nextArea = nextCheck ? area === (nextRect === null || nextRect === void 0 ? void 0 : nextRect.area) : false;
const attrOTP = any(matchOtpAttr)(fieldAttrs);
const attrMFA = any(matchMfaAttr)(fieldAttrs);
const attrOutlier = any(matchOtpOutlier)(fieldAttrs);
const textOTP = matchOtpAttr(fieldText);
const textMFA = matchMfa(fieldText);
const labelOTP = matchOtpAttr(labelText);
const labelMFA = matchMfa(labelText);
const labelOutlier = matchOtpOutlier(labelText);
const parents = [getNthParent(field)(1), getNthParent(field)(2)];
const wrapperAttrs = parents.flatMap(getBaseAttributes);
const wrapperOTP = any(matchOtpAttr)(wrapperAttrs);
const wrapperOutlier = any(matchOtpOutlier)(wrapperAttrs);
const emailOutlierCount = (formInnerText.match(/@/g) || []).length;
return {
mfaScore: boolInt(formMfa),
exotic: boolInt(fieldFeatures.isFormNoop),
linkOTPOutlier: boolInt(formMfa && linkOTPOutlier),
hasCheckboxes: boolInt(formMfa && formCheckboxCount > 0),
hidden: boolInt(!fieldFeatures.visible),
required: boolInt(fieldFeatures.required),
nameMatch: boolInt(nameMatch),
idMatch: boolInt(idMatch),
numericMode: boolInt(field.inputMode === 'numeric'),
autofocused: boolInt(field.autofocus),
tabIndex1: boolInt(field.tabIndex === 1),
patternOTP: boolInt(patternOTP),
maxLength1: boolInt(maxLength === 1),
maxLength5: boolInt(maxLength === 5),
minLength6: boolInt(minLength === 6),
maxLength6: boolInt(maxLength === 6),
maxLength20: boolInt(maxLength === 20),
autocompleteOTC: boolInt(fieldFeatures.autocomplete === 'one-time-code'),
autocompleteOff: boolInt(fieldFeatures.autocomplete === 'off'),
prevAligned: boolInt(prevAligned),
prevArea: boolInt(prevArea),
nextAligned: boolInt(nextAligned),
nextArea: boolInt(nextArea),
attrMFA: boolInt(attrMFA),
attrOTP: boolInt(attrOTP),
attrOutlier: boolInt(attrOutlier),
textMFA: boolInt(textMFA),
textOTP: boolInt(textOTP),
labelMFA: boolInt(labelMFA),
labelOTP: boolInt(labelOTP),
labelOutlier: boolInt(labelOutlier),
wrapperOTP: boolInt(wrapperOTP),
wrapperOutlier: boolInt(wrapperOutlier),
emailOutlierCount: linearScale(emailOutlierCount, 0, 2),
};
};
const OTP_FIELD_FEATURES = [
'mfaScore',
'exotic',
'linkOTPOutlier',
'hasCheckboxes',
'hidden',
'required',
'nameMatch',
'idMatch',
'numericMode',
'autofocused',
'tabIndex1',
'patternOTP',
'maxLength1',
'maxLength5',
'minLength6',
'maxLength6',
'maxLength20',
'autocompleteOTC',
'autocompleteOff',
'prevAligned',
'prevArea',
'nextAligned',
'nextArea',
'attrMFA',
'attrOTP',
'attrOutlier',
'textMFA',
'textOTP',
'labelMFA',
'labelOTP',
'labelOutlier',
'wrapperOTP',
'wrapperOutlier',
'emailOutlierCount',
];
const results = {
coeffs: [
['otp-mfaScore', 34.24491500854492],
['otp-exotic', -7.1488356590271],
['otp-linkOTPOutlier', -30.66411590576172],
['otp-hasCheckboxes', 7.240150451660156],
['otp-hidden', -0.007220640778541565],
['otp-required', -3.7672529220581055],
['otp-nameMatch', 2.5392072200775146],
['otp-idMatch', 8.873919486999512],
['otp-numericMode', -8.184645652770996],
['otp-autofocused', 1.1361602544784546],
['otp-tabIndex1', 3.0903444290161133],
['otp-patternOTP', 6.962174415588379],
['otp-maxLength1', 5.160733699798584],
['otp-maxLength5', -8.207122802734375],
['otp-minLength6', 16.07337760925293],
['otp-maxLength6', 8.32022762298584],
['otp-maxLength20', -1.140841007232666],
['otp-autocompleteOTC', 0.1409512609243393],
['otp-autocompleteOff', -3.0876314640045166],
['otp-prevAligned', -0.35210293531417847],
['otp-prevArea', -0.3188312351703644],
['otp-nextAligned', 0.16715140640735626],
['otp-nextArea', -0.051897935569286346],
['otp-attrMFA', 7.639617919921875],
['otp-attrOTP', 1.7246224880218506],
['otp-attrOutlier', -10.390393257141113],
['otp-textMFA', 6.657490253448486],
['otp-textOTP', -16.34011459350586],
['otp-labelMFA', -1.3743057250976562],
['otp-labelOTP', -0.07948236167430878],
['otp-labelOutlier', -6.6860761642456055],
['otp-wrapperOTP', 6.924853801727295],
['otp-wrapperOutlier', -6.270834922790527],
['otp-emailOutlierCount', -18.866779327392578],
],
bias: -11.855243682861328,
cutoff: 0.51,
};
const otp = {
name: FieldType.OTP,
coeffs: OTP_FIELD_FEATURES.map((key) => {
var _a, _b;
return [
`otp-${key}`,
(_b =
(_a = results.coeffs.find(([feature]) => feature === `otp-${key}`)) === null || _a === void 0
? void 0
: _a[1]) !== null && _b !== void 0
? _b
: 0,
];
}),
bias: results.bias,
cutoff: results.cutoff,
getRules: () => [
rule(type('otp-field'), type(FieldType.OTP), {}),
...OTP_FIELD_FEATURES.map((key) =>
rule(type(FieldType.OTP), featureScore('otp-field', key), {
name: `otp-${key}`,
})
),
...outRuleWithCache('field-candidate', FieldType.OTP),
],
};
const getFieldFeature = (fnode) => {
var _a, _b;
const field = fnode.element;
const fieldHaystacks = getFieldHaystacks(field);
const formFnode = getParentFormFnode(fnode);
if (formFnode !== null && !formFnode.hasNoteFor('form')) formFnode.setNoteFor('form', getFormFeatures(formFnode));
const formFeatures = formFnode === null || formFnode === void 0 ? void 0 : formFnode.noteFor('form');
const formClassification = getFormClassification(formFnode);
const value = field.value;
const type = field.getAttribute('type');
const readonly = field.readOnly;
const required = field.required;
const minLength = safeInt(field.minLength, 0);
const maxLength = safeInt(field.maxLength, 250);
const pattern = field.pattern;
const autocomplete = field.autocomplete;
const disabled = field.disabled;
const typeValid = type !== 'hidden';
const tabIndex = field.tabIndex;
const visible = typeValid
? isVisibleField(field) &&
isVisible(field, {
opacity: false,
})
: false;
const searchField = visible && any(matchSearchAction)(fieldHaystacks.fieldAttrs.concat(fieldHaystacks.fieldText));
const prevField = typeValid
? (_a =
formFeatures === null || formFeatures === void 0
? void 0
: formFeatures.formInputIterator.prev(field)) !== null && _a !== void 0
? _a
: null
: null;
const nextField = typeValid
? (_b =
formFeatures === null || formFeatures === void 0
? void 0
: formFeatures.formInputIterator.next(field)) !== null && _b !== void 0
? _b
: null
: null;
return Object.assign(
{
formFnode,
formFeatures,
isFormLogin: formClassification.login,
isFormRegister: formClassification.register,
isFormPWChange: formClassification.pwChange,
isFormRecovery: formClassification.recovery,
isFormMFA: formClassification.mfa,
isFormNoop: formClassification.noop,
value,
visible,
type,
readonly,
required,
disabled,
pattern,
autocomplete,
minLength,
maxLength,
tabIndex,
prevField,
nextField,
searchField,
},
fieldHaystacks
);
};
const { clusters } = clusters$1;
const CLUSTER_MAX_X_DIST = 50;
const CLUSTER_MAX_Y_DIST = 275;
const CLUSTER_ALIGNMENT_TOLERANCE = 0.05;
const CLUSTER_MAX_ELEMENTS = 50;
const context = {
cache: new WeakMap(),
};
const getElementData = (el) => {
var _a;
const data =
(_a = context.cache.get(el)) !== null && _a !== void 0
? _a
: {
isField: el.matches(kFieldSelector) && el.matches(':not([type="submit"])'),
rect: el.getBoundingClientRect(),
};
context.cache.set(el, data);
return data;
};
const compare = (elA, elB) => {
const a = getElementData(elA);
const b = getElementData(elB);
const maxDx = CLUSTER_MAX_X_DIST;
const maxDy = CLUSTER_MAX_Y_DIST / (a.isField && b.isField ? 2 : 1);
const { dx, dy } = getRectMinDistance(a.rect, b.rect);
const leftRatio = Math.abs(a.rect.left / b.rect.left);
const topRatio = Math.abs(a.rect.top / b.rect.top);
const xAlign = leftRatio > 1 - CLUSTER_ALIGNMENT_TOLERANCE && leftRatio < 1 + CLUSTER_ALIGNMENT_TOLERANCE;
const yAlign = topRatio > 1 - CLUSTER_ALIGNMENT_TOLERANCE && topRatio < 1 + CLUSTER_ALIGNMENT_TOLERANCE;
if (xAlign && yAlign) return true;
if (xAlign && dy < maxDy) return true;
if (yAlign && dx < maxDx) return true;
if (dx < maxDx && dy < maxDy) return true;
return false;
};
const handleSingletonCluster = (cluster) => {
const node = cluster[0];
return walkUpWhile(
node,
5
)((_, candidate) => candidate === node || candidate.querySelectorAll(buttonSelector).length === 0);
};
const resolveFormClusters = (doc) => {
const forms = selectFormCandidates(doc);
const clusterable = (els) => els.filter((el) => !forms.some((ex) => ex.contains(el)) && isVisibleField(el));
const fields = Array.from(doc.querySelectorAll(kFieldSelector));
const fieldsOfInterest = clusterable(
fields.filter((el) => isClassifiable(el) && el.getAttribute('type') !== 'hidden')
);
const inputs = fieldsOfInterest.filter((field) => field.matches(inputCandidateSelector));
if (inputs.length === 0 || inputs.length > CLUSTER_MAX_ELEMENTS) return [];
const domGroups = Array.from(doc.querySelectorAll(kDomGroupSelector)).filter((el) => el !== document.body);
const positionedEls = findStackedParents(inputs, 20);
const groups = pruneNested(
domGroups.filter((el) => !positionedEls.some((stack) => el.contains(stack))).concat(positionedEls)
);
const buttons = clusterable(
Array.from(document.querySelectorAll(kButtonSubmitSelector)).filter(isSubmitBtnCandidate)
);
const candidates = uniqueNodes(fieldsOfInterest, buttons);
if (candidates.length > CLUSTER_MAX_ELEMENTS) return [];
const groupByInput = new WeakMap(candidates.map((el) => [el, groups.find((group) => group.contains(el))]));
const theClusters = clusters(candidates, 1, (a, b) => {
if (a.parentElement === b.parentElement) return 0;
const groupA = groupByInput.get(a);
const groupB = groupByInput.get(b);
if (groupA !== groupB) return Number.MAX_SAFE_INTEGER;
if (groupA && groupA === groupB) return 0;
return compare(a, b) ? 0 : Number.MAX_SAFE_INTEGER;
});
const ancestors = theClusters
.map((cluster) => (cluster.length === 1 ? handleSingletonCluster(cluster) : cluster.reduce(getCommonAncestor)))
.filter(
(ancestor) => document.body !== ancestor && ancestor.querySelectorAll(inputCandidateSelector).length > 0
);
const result = pruneNested(ancestors);
result.forEach(flagCluster);
context.cache = new WeakMap();
return result;
};
const TABLE_MAX_COLS = 3;
const TABLE_MAX_AREA = 15e4;
const nodeOfInterest = (el) => isClassifiable(el) && el.querySelector('input') !== null;
const excludeForms = (doc = document) => {
const bodyElCount = document.body.querySelectorAll('*').length;
return doc.querySelectorAll('form').forEach((form) => {
if (nodeOfInterest(form)) {
const fieldCount = form.querySelectorAll(kFieldSelector).length;
const inputCount = form.querySelectorAll(inputCandidateSelector).length;
const invalidFieldCount =
inputCount === 0 || inputCount > MAX_INPUTS_PER_FORM || fieldCount > MAX_FIELDS_PER_FORM;
const pageForm = form.matches('body > form');
const formElCount = form.querySelectorAll('*').length;
const invalidPageForm = pageForm && formElCount >= bodyElCount * 0.8;
const invalidCount = invalidFieldCount || invalidPageForm;
if (invalidCount && !pageForm) return flagSubtreeAsIgnored(form);
if (invalidCount && pageForm) return flagAsIgnored(form);
if (form.matches('table form') && form.closest('table').querySelectorAll('form').length > 2)
return flagAsIgnored(form);
}
});
};
const excludeClusterableNodes = (doc = document) => {
doc.querySelectorAll('table').forEach((table) => {
if (nodeOfInterest(table) && !table.querySelector('table') && table.closest('form') === null) {
const nestedForms = table.querySelectorAll('form');
if (nestedForms.length > 2) return flagSubtreeAsIgnored(table);
if (!nestedForms.length) {
if (table.querySelector('thead') !== null) return flagSubtreeAsIgnored(table);
const cellCount = Math.max(...Array.from(table.rows).map((row) => row.cells.length));
if (cellCount > TABLE_MAX_COLS || getNodeRect(table).area > TABLE_MAX_AREA)
return flagSubtreeAsIgnored(table);
}
}
});
doc.querySelectorAll(kEditorSelector).forEach(flagSubtreeAsIgnored);
};
const excludeFields = (doc = document) => {
doc.querySelectorAll('input').forEach((input) => {
if (!isClassifiable(input)) return;
const invalidType = !VALID_INPUT_TYPES.includes(input.type);
const listElement = input.getAttribute('aria-autocomplete') === 'list';
if (invalidType || listElement) return flagAsIgnored(input);
if (input.type === 'hidden') {
const value = input.value.trim();
const invalidValueLength = !value.length || value.length > MAX_HIDDEN_FIELD_VALUE_LENGTH;
if (
invalidValueLength ||
HIDDEN_FIELD_IGNORE_VALUES.includes(value) ||
!input.matches(kHiddenUsernameSelector)
)
return flagAsIgnored(input);
}
});
};
const prepass = (doc = document) => {
excludeForms(doc);
excludeClusterableNodes(doc);
excludeFields(doc);
resolveFormClusters(doc);
};
const shouldRunClassifier = () => {
const runForForms = selectFormCandidates().reduce((runDetection, form) => {
if (isProcessed(form)) {
const unprocessedFields = selectInputCandidates(form).some(isProcessableField);
if (unprocessedFields) removeClassifierFlags(form);
return runDetection || unprocessedFields;
}
if (isVisibleForm(form)) return true;
return runDetection;
}, false);
if (runForForms) return true;
const runForFields = selectInputCandidates().some(isProcessableField);
return runForFields;
};
const definitions = [
login,
register,
passwordChange,
recovery,
mfa,
username,
usernameHidden,
email,
password,
newPassword,
otp,
];
const trainees = {
forms: {
login,
register,
passwordChange,
recovery,
mfa,
},
fields: {
username,
usernameHidden,
email,
password,
newPassword,
otp,
},
};
const rulesetMaker = () => {
const aggregation = definitions.reduce(
(acc, curr) => ({
rules: [...acc.rules, ...curr.getRules()],
coeffs: [...acc.coeffs, ...curr.coeffs],
biases: [...acc.biases, [curr.name, curr.bias]],
}),
{
rules: [
rule(dom(formCandidateSelector), type('form-candidate'), {}),
rule(dom('input'), type('field-candidate'), {}),
rule(type('form-candidate').when(withFnodeEl(isClassifiable)), type('form-element'), {}),
rule(type('form-element').when(withFnodeEl(isVisibleForm)), type('form').note(getFormFeatures), {}),
rule(type('form-element'), out('form').through(processFormEffect), {}),
rule(type('form').when(isNoopForm), type(FormType.NOOP), {}),
rule(type(FormType.NOOP), out(FormType.NOOP), {}),
rule(type('field-candidate').when(isClassifiableField), type('field').note(getFieldFeature), {}),
rule(type('field').when(maybeUsername), type('username-field').note(getUsernameFieldFeatures), {}),
rule(
type('field').when(maybeHiddenUsername),
type('username-hidden-field').note(getHiddenUserFieldFeatures),
{}
),
rule(type('field').when(maybeEmail), type('email-field').note(getEmailFieldFeatures), {}),
rule(type('field').when(maybePassword), type('password-field').note(getPasswordFieldFeatures), {}),
rule(type('field').when(maybeOTP), type('otp-field').note(getOTPFieldFeatures), {}),
rule(type('field'), out('field').through(processFieldEffect), {}),
],
coeffs: [],
biases: [],
}
);
const rules = ruleset(aggregation.rules, aggregation.coeffs, aggregation.biases);
return rules;
};
const clearDetectionCache = () => clearVisibilityCache();
export {
EL_ATTRIBUTES,
FIELD_ATTRIBUTES,
FORM_ATTRIBUTES,
FORM_CLUSTER_ATTR,
FieldType,
FormType,
TEXT_ATTRIBUTES,
buttonSelector,
cacheContext,
clearDetectionCache,
clearVisibilityCache,
createInputIterator,
fieldTypes,
flagAsIgnored,
flagAsProcessed,
flagCluster,
flagSubtreeAsIgnored,
formCandidateSelector,
formTypes,
getAttributes,
getBaseAttributes,
getFieldAttributes,
getFormAttributes,
getFormParent,
getIgnoredParent,
getParentFormPrediction,
getTextAttributes,
getVisibilityCache,
inputCandidateSelector,
isClassifiable,
isClassifiableField,
isCluster,
isEmailCandidate,
isIgnored,
isOAuthCandidate,
isPredictedType,
isPrediction,
isProcessableField,
isProcessed,
isSubmitBtnCandidate,
isUsernameCandidate,
isVisible,
isVisibleEl,
isVisibleField,
isVisibleForm,
kAnchorLinkSelector,
kButtonSubmitSelector,
kCaptchaSelector,
kDomGroupSelector,
kEditorSelector,
kEmailSelector,
kFieldSelector,
kHeadingSelector,
kHiddenUsernameSelector,
kLayoutSelector,
kPasswordSelector,
kSocialSelector,
kUsernameSelector,
maybeEmail,
maybeHiddenUsername,
maybeOTP,
maybePassword,
maybeUsername,
otpSelector,
prepass,
removeClassifierFlags,
removeIgnoredFlag,
removePredictionFlag,
removeProcessedFlag,
rulesetMaker,
selectFormCandidates,
selectInputCandidates,
setPrediction,
shouldRunClassifier,
splitFieldsByVisibility,
trainees,
};
| 7,704
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useActionRequest.spec.tsx
|
import { Provider as ReduxProvider } from 'react-redux';
import { type AnyAction, configureStore, createAction } from '@reduxjs/toolkit';
import { act, renderHook } from '@testing-library/react-hooks';
import { requestMiddleware } from '@proton/pass/store/middlewares/request-middleware';
import request from '@proton/pass/store/reducers/request';
import withRequest from '../store/actions/with-request';
import { useActionRequest } from './useActionRequest';
const requestId = 'test::id';
const start = createAction('test::start', () => withRequest({ type: 'start', id: requestId })({ payload: {} }));
const success = createAction('test::success', () => withRequest({ type: 'success', id: requestId })({ payload: {} }));
const failure = createAction('test::failure', () => withRequest({ type: 'failure', id: requestId })({ payload: {} }));
const successCache = createAction('test::success::cache', () =>
withRequest({ type: 'success', id: requestId, maxAge: 1 })({ payload: {} })
);
const buildHook = (useInitialRequestId: boolean = true, initialActions: AnyAction[] = []) => {
const store = configureStore({ reducer: { request }, middleware: [requestMiddleware] });
initialActions.forEach((action) => store.dispatch(action));
const onStart = jest.fn();
const onSuccess = jest.fn();
const onFailure = jest.fn();
return {
store,
onStart,
onSuccess,
onFailure,
hook: renderHook(
() =>
useActionRequest({
action: start,
initialRequestId: useInitialRequestId ? requestId : undefined,
onStart,
onSuccess,
onFailure,
}),
{
wrapper: ({ children }) => <ReduxProvider store={store}>{children}</ReduxProvider>,
}
),
};
};
describe('useActionRequest', () => {
it('Handles request sequence', async () => {
const { hook, onStart, onSuccess, onFailure, store } = buildHook();
expect(hook.result.current.loading).toBe(false);
expect(hook.result.current.progress).toEqual(0);
expect(onStart).not.toHaveBeenCalled();
expect(onSuccess).not.toHaveBeenCalled();
expect(onFailure).not.toHaveBeenCalled();
act(() => {
hook.result.current.dispatch();
});
expect(hook.result.current.loading).toBe(true);
expect(hook.result.current.progress).toEqual(0);
expect(onStart).toHaveBeenCalledTimes(1);
expect(onSuccess).not.toHaveBeenCalled();
expect(onFailure).not.toHaveBeenCalled();
act(() => {
store.dispatch(success());
});
expect(hook.result.current.loading).toBe(false);
expect(hook.result.current.progress).toBe(100);
expect(onStart).toHaveBeenCalledTimes(1);
expect(onSuccess).toHaveBeenCalledTimes(1);
expect(onFailure).not.toHaveBeenCalled();
act(() => {
hook.result.current.dispatch();
});
expect(hook.result.current.loading).toBe(true);
expect(hook.result.current.progress).toEqual(0);
expect(onStart).toHaveBeenCalledTimes(2);
expect(onSuccess).toHaveBeenCalledTimes(1);
expect(onFailure).not.toHaveBeenCalled();
act(() => {
store.dispatch(failure());
});
expect(hook.result.current.loading).toBe(false);
expect(hook.result.current.progress).toBe(100);
expect(onStart).toHaveBeenCalledTimes(2);
expect(onSuccess).toHaveBeenCalledTimes(1);
expect(onFailure).toHaveBeenCalledTimes(1);
});
test('Revalidate should re-trigger sequence', () => {
const { hook, onStart, onSuccess, onFailure } = buildHook(true, [successCache()]);
act(() => {
hook.result.current.revalidate();
});
expect(hook.result.current.loading).toBe(true);
expect(hook.result.current.progress).toEqual(0);
expect(onStart).toHaveBeenCalledTimes(1);
expect(onSuccess).toHaveBeenCalledTimes(1);
expect(onFailure).not.toHaveBeenCalled();
});
test('dispatching should noop if request success with maxAge', () => {
const { hook, onStart, onSuccess, onFailure } = buildHook(false, [successCache()]);
act(() => {
hook.result.current.dispatch();
});
expect(hook.result.current.loading).toBe(false);
expect(hook.result.current.progress).toEqual(100);
expect(onStart).not.toHaveBeenCalled();
expect(onSuccess).toHaveBeenCalledTimes(1);
expect(onFailure).not.toHaveBeenCalled();
});
test('dispatching the same action should only trigger effect once', () => {
const { hook, onStart, onSuccess, onFailure } = buildHook(false, []);
act(() => {
hook.result.current.dispatch();
hook.result.current.dispatch();
hook.result.current.dispatch();
hook.result.current.dispatch();
});
expect(hook.result.current.loading).toBe(true);
expect(hook.result.current.progress).toEqual(0);
expect(onStart).toHaveBeenCalledTimes(1);
expect(onSuccess).not.toHaveBeenCalled();
expect(onFailure).not.toHaveBeenCalled();
});
test('Setting `initialRequestId` should trigger `onStart`', () => {
const { hook, onStart, onSuccess, onFailure } = buildHook(true, [start()]);
expect(hook.result.current.loading).toBe(true);
expect(hook.result.current.progress).toEqual(0);
expect(onStart).toHaveBeenCalledTimes(1);
expect(onSuccess).not.toHaveBeenCalled();
expect(onFailure).not.toHaveBeenCalled();
});
test('Setting `initialRequestId` should trigger `onSuccess`', () => {
const { hook, onStart, onSuccess, onFailure } = buildHook(true, [success()]);
expect(hook.result.current.loading).toBe(false);
expect(hook.result.current.progress).toEqual(100);
expect(onStart).not.toHaveBeenCalled();
expect(onSuccess).toHaveBeenCalledTimes(1);
expect(onFailure).not.toHaveBeenCalled();
});
test('Setting `initialRequestId` should trigger `onFailure`', () => {
const { hook, onStart, onSuccess, onFailure } = buildHook(true, [failure()]);
expect(hook.result.current.loading).toBe(false);
expect(hook.result.current.progress).toEqual(100);
expect(onStart).not.toHaveBeenCalled();
expect(onSuccess).not.toHaveBeenCalled();
expect(onFailure).toHaveBeenCalledTimes(1);
});
});
| 7,705
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useActionRequest.ts
|
import { useMemo, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import type { AnyAction } from 'redux';
import type { RequestOptions } from '@proton/pass/store/actions/with-request';
import { type WithRequest, withRevalidate } from '@proton/pass/store/actions/with-request';
import type { RequestEntry } from '@proton/pass/store/reducers';
import { useActionRequestEffect } from './useActionRequestEffect';
export type RequestEntryFromAction<A extends WithRequest<AnyAction, any>> = A['meta']['request'] extends RequestOptions<
infer T,
infer D
>
? RequestEntry<T, D>
: never;
type UseActionWithRequestOptions<P extends any[], A extends WithRequest<AnyAction, 'start'>> = {
action: (...args: P) => A;
initialRequestId?: string;
onStart?: <R extends RequestEntry<'start', any>>(request: R) => void;
onSuccess?: <R extends RequestEntry<'success', any>>(request: R) => void;
onFailure?: <R extends RequestEntry<'failure', any>>(request: R) => void;
};
/*
* Passing `initialRequestId` allows tracking the action request immediately before any dispatch.
* The passed-in callbacks `onStart`, `onSuccess`, and `onFailure`, can be used to perform tasks
* like controlling loading spinners or handling request responses or errors.
*/
export const useActionRequest = <P extends any[], R extends WithRequest<AnyAction, 'start'>>(
options: UseActionWithRequestOptions<P, R>
) => {
const dispatch = useDispatch();
const optionsRef = useRef<UseActionWithRequestOptions<P, R>>(options);
optionsRef.current = options;
const [requestId, setRequestId] = useState<string>(options.initialRequestId ?? '');
const { request, loading, progress } = useActionRequestEffect(requestId, {
onStart: optionsRef.current.onStart,
onSuccess: optionsRef.current.onSuccess,
onFailure: optionsRef.current.onFailure,
});
return useMemo(() => {
const actionCreator = (...args: P) => {
const action = options.action(...args);
setRequestId(action.meta.request.id);
return action;
};
return {
dispatch: (...args: P) => dispatch(actionCreator(...args)),
revalidate: (...args: P) => dispatch(withRevalidate(actionCreator(...args))),
progress,
loading,
};
}, [request, progress, loading]);
};
| 7,706
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useActionRequestEffect.ts
|
import { useEffect, useMemo, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import type { RequestEntry } from '@proton/pass/store/reducers';
import { selectRequest } from '@proton/pass/store/selectors';
type Options = {
onStart?: <R extends RequestEntry<'start', any>>(request: R) => void;
onSuccess?: <R extends RequestEntry<'success', any>>(request: R) => void;
onFailure?: <R extends RequestEntry<'failure', any>>(request: R) => void;
};
/* `options` is wrapped in a ref to avoid setting it as
* a dependency to the status change effect. We only want
* to trigger the callbacks once. */
export const useActionRequestEffect = (requestId: string, options: Options) => {
const request = useSelector(selectRequest(requestId));
const optionsRef = useRef<Options>(options);
optionsRef.current = options;
const [loading, setLoading] = useState(false);
const progress = (() => {
if (!request) return 0;
return request?.status === 'start' ? request.progress ?? 0 : 100;
})();
useEffect(() => {
if (!request) return;
switch (request.status) {
case 'start':
setLoading(true);
return optionsRef.current.onStart?.(request);
case 'success':
setLoading(false);
return optionsRef.current.onSuccess?.(request);
case 'failure':
setLoading(false);
return optionsRef.current.onFailure?.(request);
}
}, [request]);
return useMemo(() => ({ request, loading, progress }), [request, loading, progress]);
};
| 7,707
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useActivityProbe.ts
|
import { useRef } from 'react';
import type { MessageWithSenderFactory } from '@proton/pass/lib/extension/message';
import { sendMessage } from '@proton/pass/lib/extension/message';
import { WorkerMessageType } from '@proton/pass/types';
import noop from '@proton/utils/noop';
export type ActivityProbe = ReturnType<typeof createActivityProbe>;
const ACTIVITY_PROBE_TIMEOUT = 5_000;
const createActivityProbe = (messageFactory: MessageWithSenderFactory) => {
const timer: { interval?: ReturnType<typeof setInterval> } = {};
const cancel = () => clearInterval(timer?.interval);
const ping = () => sendMessage(messageFactory({ type: WorkerMessageType.ACTIVITY_PROBE })).catch(noop);
const start = () => {
cancel();
timer.interval = setInterval(ping, ACTIVITY_PROBE_TIMEOUT);
void ping();
};
return { start, cancel };
};
export const useActivityProbe = (messageFactory: MessageWithSenderFactory): ActivityProbe =>
useRef(createActivityProbe(messageFactory)).current;
| 7,708
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useAliasDetails.ts
|
import { useEffect, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { c } from 'ttag';
import useNotifications from '@proton/components/hooks/useNotifications';
import { getAliasDetailsIntent } from '@proton/pass/store/actions';
import { aliasDetailsRequest } from '@proton/pass/store/actions/requests';
import { selectAliasDetails } from '@proton/pass/store/selectors';
import type { AliasMailbox, Maybe } from '@proton/pass/types';
import { useActionRequest } from './useActionRequest';
type UseAliasDetailsConfig = {
aliasEmail: string;
itemId: string;
shareId: string;
onAliasDetailsLoaded?: (mailboxes: Maybe<AliasMailbox[]>) => void;
};
export const useAliasDetails = ({ aliasEmail, itemId, shareId, onAliasDetailsLoaded }: UseAliasDetailsConfig) => {
const { createNotification } = useNotifications();
const aliasDetails = useSelector(selectAliasDetails(aliasEmail));
const getAliasDetails = useActionRequest({
action: getAliasDetailsIntent,
initialRequestId: aliasDetailsRequest(aliasEmail),
onSuccess: () => onAliasDetailsLoaded?.(aliasDetails),
onFailure: () =>
createNotification({
type: 'warning',
text: c('Warning').t`Cannot retrieve mailboxes for this alias right now`,
}),
});
useEffect(() => {
getAliasDetails.dispatch({ shareId, itemId, aliasEmail });
}, [shareId, itemId, aliasEmail]);
return useMemo(
() => ({ value: aliasDetails ?? [], loading: getAliasDetails.loading }),
[aliasDetails, getAliasDetails.loading]
);
};
| 7,709
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useAliasForLoginModal.ts
|
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import type { FormikContextType } from 'formik';
import { selectAliasByAliasEmail } from '@proton/pass/store/selectors';
import type { LoginItemFormValues } from '@proton/pass/types';
import { merge } from '@proton/pass/utils/object/merge';
import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
import { useAliasOptions } from './useAliasOptions';
export const useAliasForLoginModal = <T extends LoginItemFormValues>(
form: FormikContextType<T>,
options: { lazy: boolean }
) => {
const [aliasModalOpen, setAliasModalOpen] = useState(false);
const { values } = form;
const { withAlias, username, aliasPrefix } = values;
const aliasOptions = useAliasOptions({ shareId: form.values.shareId, lazy: options.lazy });
const relatedAlias = useSelector(selectAliasByAliasEmail(username));
const canCreateAlias = !relatedAlias && !withAlias;
const willCreateAlias = !relatedAlias && withAlias && !isEmptyString(aliasPrefix);
const usernameIsAlias = relatedAlias || willCreateAlias;
useEffect(() => {
if (relatedAlias) {
void form.setValues((values) =>
merge(values, {
withAlias: false,
aliasPrefix: '',
aliasSuffix: undefined,
mailboxes: [],
})
);
}
}, [relatedAlias]);
useEffect(() => {
if (options.lazy && aliasModalOpen) aliasOptions.request();
}, [aliasModalOpen]);
return {
setOpen: setAliasModalOpen,
open: aliasModalOpen,
relatedAlias,
canCreate: canCreateAlias,
willCreate: willCreateAlias,
usernameIsAlias,
aliasOptions: aliasOptions.value,
loading: aliasOptions.loading,
};
};
| 7,710
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useAliasOptions.ts
|
import { useEffect, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { getAliasOptionsIntent } from '@proton/pass/store/actions';
import { aliasOptionsRequest } from '@proton/pass/store/actions/requests';
import { selectAliasOptions } from '@proton/pass/store/selectors';
import type { MaybeNull } from '@proton/pass/types';
import type { AliasMailbox } from '@proton/pass/types/data/alias';
import { useActionRequest } from './useActionRequest';
export type SanitizedAliasOptions = {
suffixes: { value: string; signature: string }[];
mailboxes: AliasMailbox[];
};
export type UseAliasOptionsParams = {
lazy?: boolean /* defer the alias options dispatch */;
shareId: string;
onAliasOptionsLoaded?: (aliasOptions: SanitizedAliasOptions) => any;
};
export type UseAliasOptionsResult = {
loading: boolean;
request: () => void;
value: MaybeNull<SanitizedAliasOptions>;
};
export const useAliasOptions = ({
shareId,
lazy = false,
onAliasOptionsLoaded,
}: UseAliasOptionsParams): UseAliasOptionsResult => {
const aliasOptions = useSelector(selectAliasOptions);
const sanitizedAliasOptions = useMemo(
() =>
aliasOptions !== null
? {
suffixes: aliasOptions.suffixes.map(({ suffix, signedSuffix }) => ({
value: suffix,
signature: signedSuffix,
})),
mailboxes: aliasOptions.mailboxes,
}
: null,
[aliasOptions]
);
const getAliasOptions = useActionRequest({
action: getAliasOptionsIntent,
initialRequestId: aliasOptionsRequest(shareId),
onSuccess: () => sanitizedAliasOptions && onAliasOptionsLoaded?.(sanitizedAliasOptions),
});
useEffect(() => {
if (!lazy) getAliasOptions.dispatch({ shareId });
}, [lazy]);
return useMemo(
() => ({
loading: getAliasOptions.loading,
request: () => getAliasOptions.dispatch({ shareId }),
value: sanitizedAliasOptions,
}),
[sanitizedAliasOptions, getAliasOptions.loading, shareId]
);
};
| 7,711
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useAsyncModalHandles.ts
|
/**
* FIXME: split the responsibilities into 2 separate
* building blocks that consumers can compose :
* 1. a component for handling the modal
* 2. a hook for handling the async resolver
*/
import { useCallback, useMemo, useRef, useState } from 'react';
import type { ModalProps } from '@proton/components/components/modalTwo/Modal';
import noop from '@proton/utils/noop';
export class AsyncModalAbortedError extends Error {}
type ModalState<T> = T & Omit<ModalProps, 'onSubmit'>;
type HookOptions<T> = { getInitialModalState: () => T };
export type UseAsyncModalHandle<V, T> = (options: UseAsyncModalHandlerOptions<V, T>) => Promise<void>;
type UseAsyncModalHandlerOptions<V, T> = Partial<T> & {
onError?: (error: unknown) => any | Promise<any>;
onAbort?: () => any | Promise<any>;
onSubmit: (value: V) => any | Promise<any>;
};
export const useAsyncModalHandles = <V, T>({ getInitialModalState }: HookOptions<T>) => {
const getInitialState = useCallback(
(): ModalState<T> => ({ ...getInitialModalState(), open: false, disabled: false }),
[getInitialModalState]
);
const [state, setState] = useState<ModalState<T>>(getInitialState());
const resolver = useRef<(value: V) => void>(noop);
const rejector = useRef<(error: unknown) => void>(noop);
const resolve = useCallback((value: V) => resolver.current?.(value), []);
const abort = useCallback(() => {
rejector.current?.(new AsyncModalAbortedError());
setState(getInitialState());
}, [getInitialState]);
const handler = useCallback<UseAsyncModalHandle<V, T>>(
async (opts) => {
const { onSubmit, onError, onAbort, ...modalOptions } = opts;
setState((state) => ({ ...state, ...modalOptions, open: true }));
try {
const value = await new Promise<V>((resolve, reject) => {
resolver.current = resolve;
rejector.current = reject;
});
setState((state) => ({ ...state, disabled: true }));
await onSubmit(value);
} catch (e) {
setState((state) => ({ ...state, disabled: false }));
if (e instanceof AsyncModalAbortedError) {
await onAbort?.();
} else {
await onError?.(e);
}
} finally {
setState({ ...getInitialState(), ...modalOptions });
}
},
[getInitialState]
);
return useMemo(() => ({ handler, abort, state, resolver: resolve }), [handler, abort, state]);
};
| 7,712
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useConfirm.ts
|
import { useCallback, useState } from 'react';
import type { MaybeNull } from '@proton/pass/types';
/**
* The `useConfirm` hook lets you manage and confirm the execution of a callback.
* It allows you to initiate an action, confirm it when ready, and cancel it if
* necessary. This hook is particularly useful when you want to confirm a potentially
* destructive action, such as deleting an item, before executing it. Typically you
* would use the `pending` state to toggle the visiblity of a prompt, ie :
*
* ```typescript
* const action = useConfirm((id: string) => items.remove(id))
* // call `action.prompt('some-id')` to initiate
*
* <Prompt
* open={action.pending}
* onClose={action.cancel}
* onSubmit={action.confirm}
* />
* ```
*/
export const useConfirm = <P extends any[], R extends any>(action: (...args: P) => R) => {
const [pendingArgs, setPendingArgs] = useState<MaybeNull<P>>(null);
const confirm = useCallback(() => {
if (pendingArgs === null) {
console.warn('No pending action');
return;
}
return action(...pendingArgs);
}, [pendingArgs, action]);
const prompt = useCallback((...args: P) => setPendingArgs(args), []);
const cancel = useCallback(() => setPendingArgs(null), []);
return { pending: pendingArgs !== null, confirm, prompt, cancel };
};
| 7,713
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useCopyToClipboard.ts
|
import { c } from 'ttag';
import { useNotifications } from '@proton/components';
import { logger } from '@proton/pass/utils/logger';
export const useCopyToClipboard = () => {
const { createNotification } = useNotifications();
return async (value: string) => {
try {
await navigator.clipboard.writeText(value);
createNotification({ type: 'success', text: c('Info').t`Copied to clipboard`, showCloseButton: false });
} catch (err) {
createNotification({ type: 'error', text: c('Info').t`Unable to copy to clipboard` });
logger.error(`[Popup] unable to copy to clipboard`);
}
};
};
| 7,714
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useCurrentTabURL.ts
|
import { useTabsQuery } from './useTabsQuery';
export const useCurrentTabURL = (onURLResult: (url?: URL) => void) => {
useTabsQuery({ active: true, currentWindow: true }, (tabs) => {
const currentURL = tabs?.[0]?.url;
onURLResult(currentURL !== undefined ? new URL(currentURL) : undefined);
});
};
| 7,715
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useDebouncedValue.ts
|
import { useCallback, useEffect, useState } from 'react';
import _debounce from '@proton/utils/debounce';
export const useDebouncedValue = <T extends string | number>(valueIn: T, time: number): T => {
const [valueOut, setValueOut] = useState(valueIn);
const debounce = useCallback(
_debounce((value) => setValueOut(value), time, { leading: true }),
[time]
);
useEffect(() => debounce(valueIn), [valueIn]);
useEffect(() => () => debounce.cancel(), []);
return valueOut;
};
| 7,716
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useDeobfuscatedItem.ts
|
import { useMemo } from 'react';
import { deobfuscateItem } from '@proton/pass/lib/items/item.obfuscation';
import type { Item, ItemType, UnsafeItem } from '@proton/pass/types';
export const useDeobfuscatedItem = <T extends ItemType>(item: Item<T>) =>
useMemo(() => deobfuscateItem(item as Item) as UnsafeItem<T>, [item]);
| 7,717
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useDeobfuscatedValue.ts
|
import { useMemo } from 'react';
import { type XorObfuscation, deobfuscate } from '@proton/pass/utils/obfuscate/xor';
export const useDeobfuscatedValue = (value: XorObfuscation) => useMemo(() => deobfuscate(value), [value.m, value.v]);
| 7,718
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useEnsureMounted.ts
|
import { useCallback } from 'react';
import useIsMounted from '@proton/hooks/useIsMounted';
import type { Callback, Maybe } from '@proton/pass/types';
export const useEnsureMounted = () => {
const isMounted = useIsMounted();
return useCallback(
<T extends Callback>(fn: T) =>
((...args: Parameters<T>): Maybe<ReturnType<T>> => {
if (isMounted()) return fn(...args);
}) as T,
[]
);
};
| 7,719
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useFeatureFlag.ts
|
import { useSelector } from 'react-redux';
import { selectFeatureFlag } from '@proton/pass/store/selectors';
import type { PassFeature } from '@proton/pass/types/api/features';
export const useFeatureFlag = (feature: PassFeature): boolean => useSelector(selectFeatureFlag(feature));
| 7,720
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useFieldControl.ts
|
import type { FieldProps } from 'formik';
export const useFieldControl = (props: FieldProps) => {
const { field, form } = props;
const { name } = field;
const { touched, errors } = form;
const error = touched[name] && errors[name];
return { error };
};
| 7,721
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useFieldMask.ts
|
import { useEffect, useRef, useState } from 'react';
import type { FieldProps } from 'formik';
import type { InputMask, InputMaskElement } from 'imask';
import IMask from 'imask/esm/imask';
import type { FactoryOpts } from 'imask/masked/factory';
import type { MaybeNull } from '@proton/pass/types';
import noop from '@proton/utils/noop';
export const useFieldMask = <Opts extends FactoryOpts>({ form, field }: FieldProps, options: Opts) => {
const { value, name } = field;
const [maskedValue, setMaskedValue] = useState<string>('');
const maskRef = useRef<MaybeNull<InputMask<Opts>>>();
const inputRef = useRef<InputMaskElement>();
useEffect(() => {
if (inputRef.current) {
maskRef.current = maskRef.current ?? IMask<Opts>(inputRef.current, options);
maskRef.current.updateOptions(options as any);
}
}, [options]);
useEffect(() => {
if (maskRef.current) {
maskRef.current.on('accept', () => {
setMaskedValue(maskRef.current!.value);
form.setFieldValue(name, maskRef.current!.unmaskedValue).catch(noop);
});
}
}, []);
useEffect(() => {
/* if the current unmasked value doesn't match our field's value
* then we have programatically set the field's value. In this case
* we need to reconciliate imask with the new values */
if (maskRef.current && value !== maskRef.current?.unmaskedValue) {
maskRef.current.typedValue = value;
maskRef.current.unmaskedValue = value;
maskRef.current.updateValue();
setMaskedValue(maskRef.current.value);
}
}, [value]);
useEffect(() => () => maskRef.current?.destroy(), []);
return { inputRef, maskedValue };
};
| 7,722
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useFilteredItems.ts
|
import { useSelector } from 'react-redux';
import { selectItemsSearchResult } from '@proton/pass/store/selectors';
import type { ItemFilters } from '@proton/pass/types';
export const useFilteredItems = (filters: ItemFilters & { trashed?: boolean }) =>
useSelector(
selectItemsSearchResult(
filters.trashed
? {
search: filters.search,
trashed: true,
}
: {
type: filters.type === '*' ? null : filters.type,
search: filters.search,
shareId: filters.selectedShareId,
sort: filters.sort,
}
)
);
| 7,723
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useFilters.ts
|
import { useEffect, useMemo, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import type { ItemFilters } from '@proton/pass/types';
import { partialMerge } from '@proton/pass/utils/object/merge';
const INITIAL_FILTERS: ItemFilters = { search: '', sort: 'recent', type: '*', selectedShareId: null };
const parseFilters = (search: string): ItemFilters =>
partialMerge(
INITIAL_FILTERS,
(() => {
try {
const params = new URLSearchParams(search);
const filters = params.get('filters');
if (!filters) return {};
return JSON.parse(atob(filters));
} catch {
return {};
}
})()
);
export const useFilters = () => {
const history = useHistory();
const location = useLocation();
const [filters, setFilters] = useState(() => parseFilters(location.search));
useEffect(() => history.listen(({ search }) => setFilters(parseFilters(search))), []);
return useMemo(
() => ({
filters,
setFilters: (update: Partial<ItemFilters>, pathname?: string) => {
const encodedFilter = btoa(JSON.stringify({ ...filters, ...update }));
const params = new URLSearchParams(history.location.search);
params.set('filters', encodedFilter);
history.replace({ pathname, search: `?${params.toString()}` });
},
}),
[filters]
);
};
| 7,724
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useImportForm.ts
|
import type { ComponentProps } from 'react';
import { useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import type { FormikContextType, FormikErrors } from 'formik';
import { useFormik } from 'formik';
import { c } from 'ttag';
import type { Dropzone, FileInput } from '@proton/components/components';
import { useNotifications } from '@proton/components/hooks';
import { extractFileExtension, fileReader } from '@proton/pass/lib/import/reader';
import type { ImportPayload, ImportReaderPayload } from '@proton/pass/lib/import/types';
import { ImportProvider } from '@proton/pass/lib/import/types';
import { importItemsIntent } from '@proton/pass/store/actions';
import type { ImportState } from '@proton/pass/store/reducers';
import { selectLatestImport, selectUser } from '@proton/pass/store/selectors';
import type { MaybeNull } from '@proton/pass/types';
import { first } from '@proton/pass/utils/array/first';
import { orThrow, pipe } from '@proton/pass/utils/fp/pipe';
import { splitExtension } from '@proton/shared/lib/helpers/file';
import identity from '@proton/utils/identity';
import { importItemsRequest } from '../store/actions/requests';
import { useActionRequest } from './useActionRequest';
type DropzoneProps = ComponentProps<typeof Dropzone>;
type FileInputProps = ComponentProps<typeof FileInput>;
export type ImportFormValues = { file: MaybeNull<File>; provider: MaybeNull<ImportProvider>; passphrase?: string };
export type ImportFormContext = {
form: FormikContextType<ImportFormValues>;
busy: boolean;
result: ImportState;
dropzone: {
hovered: boolean;
onDrop: DropzoneProps['onDrop'];
onAttach: FileInputProps['onChange'];
};
};
export type UseImportFormBeforeSubmitValue = { ok: true; payload: ImportPayload } | { ok: false };
export type UseImportFormBeforeSubmit = (payload: ImportPayload) => Promise<UseImportFormBeforeSubmitValue>;
export type UseImportFormOptions = {
beforeSubmit?: UseImportFormBeforeSubmit;
onSubmit?: (payload: ImportPayload) => void;
};
export const SUPPORTED_IMPORT_FILE_TYPES = ['json', '1pif', '1pux', 'pgp', 'zip', 'csv', 'xml'];
const createFileValidator = (allow: string[]) =>
pipe(
(files: File[]) => first(files)!,
orThrow('Unsupported file type', (file) => allow.includes(splitExtension(file?.name)[1]), identity)
);
const getInitialFormValues = (): ImportFormValues => ({
file: null,
provider: null,
passphrase: '',
});
const validateImportForm = ({ provider, file, passphrase }: ImportFormValues): FormikErrors<ImportFormValues> => {
const errors: FormikErrors<ImportFormValues> = {};
if (provider === null) errors.provider = c('Warning').t`No password manager selected`;
if (file === null) errors.file = '';
if (file && provider === ImportProvider.PROTONPASS) {
const fileExtension = extractFileExtension(file.name);
if (fileExtension === 'pgp' && !Boolean(passphrase)) {
errors.passphrase = c('Warning').t`PGP encrypted export file requires passphrase`;
}
}
return errors;
};
const isNonEmptyImportPayload = (payload: ImportPayload) =>
payload.vaults.length > 0 && payload.vaults.some(({ items }) => items.length > 0);
export const useImportForm = ({
beforeSubmit = (payload) => Promise.resolve({ ok: true, payload }),
onSubmit,
}: UseImportFormOptions): ImportFormContext => {
const [busy, setBusy] = useState(false);
const [dropzoneHovered, setDropzoneHovered] = useState(false);
const { createNotification } = useNotifications();
const result = useSelector(selectLatestImport);
const user = useSelector(selectUser);
const formRef = useRef<FormikContextType<ImportFormValues>>();
const importItems = useActionRequest({
action: importItemsIntent,
initialRequestId: importItemsRequest(),
onSuccess: () => {
setBusy(false);
void formRef.current?.setValues(getInitialFormValues());
},
onFailure: () => setBusy(false),
});
const form = useFormik<ImportFormValues>({
initialValues: getInitialFormValues(),
initialErrors: { file: '' },
validateOnChange: true,
validateOnMount: true,
validate: validateImportForm,
onSubmit: async (values) => {
try {
setBusy(true);
if (!values.provider) return setBusy(false);
const payload: ImportReaderPayload = {
file: values.file!,
provider: values.provider,
passphrase: values.passphrase,
userId: user?.ID,
};
const importPayload = await fileReader(payload);
if (!isNonEmptyImportPayload(importPayload)) {
createNotification({
type: 'error',
text: c('Error').t`The file you are trying to import is empty`,
});
return setBusy(false);
}
const result = await beforeSubmit(importPayload);
if (!result.ok) return setBusy(false);
onSubmit?.(result.payload);
importItems.dispatch({ data: result.payload, provider: values.provider });
} catch (e) {
setBusy(false);
if (e instanceof Error) {
createNotification({ type: 'error', text: e.message });
}
}
},
});
formRef.current = form;
const onAddFiles = (files: File[]) => {
try {
const file = createFileValidator(SUPPORTED_IMPORT_FILE_TYPES)(files);
void form.setValues((values) => ({ ...values, file }));
} catch (e: any) {
form.setErrors({ file: e.message });
}
};
const onDrop = (files: File[]) => {
setDropzoneHovered(false);
onAddFiles([...files]);
};
const onAttach: FileInputProps['onChange'] = (event) => onAddFiles((event.target.files as File[] | null) ?? []);
return {
form,
busy,
result,
dropzone: {
hovered: dropzoneHovered,
onAttach,
onDrop,
},
};
};
| 7,725
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useItemDraft.ts
|
import { useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import type { FormikTouched } from 'formik';
import { type FormikContextType } from 'formik';
import { itemDraftDiscard, itemDraftSave } from '@proton/pass/store/actions';
import type { ItemDraft } from '@proton/pass/store/reducers';
import type { Maybe, MaybeNull } from '@proton/pass/types';
import { omit } from '@proton/shared/lib/helpers/object';
import debounce from '@proton/utils/debounce';
const SAVE_DRAFT_TIMEOUT = 500;
export type ItemDraftState<V extends {} = {}> = Maybe<{ draft?: ItemDraft<V> }>;
type UseItemDraftOptions<V extends {}> = Pick<ItemDraft, 'type' | 'mode' | 'itemId' | 'shareId'> & {
/* Apply sanitization over the draft values */
sanitizeHydration?: (formData: ItemDraft<V>['formData']) => ItemDraft<V>['formData'];
sanitizeSave?: (formData: ItemDraft<V>['formData']) => ItemDraft<V>['formData'];
/* Retrieve the sanitized draft values after form hydration.
* This may be useful when chaining multiple form `setValue`
* calls inside the same render cycle to avoid `form.values`
* containing stale values (ie: see `Alias.new`) */
onHydrated?: (hydration: MaybeNull<ItemDraft<V>['formData']>) => void;
};
export const useItemDraft = <V extends {}>() => {
const location = useLocation<ItemDraftState<V>>();
return location.state?.draft;
};
/* Everytime the passed values change, this hook triggers
* a debounced dispatch with the form data. The `itemDraft`
* action is cache blocking to avoid swarming the service
* worker with encryption requests. The draft data should
* only be encrypted & cached when the pop-up is closed.*/
export const useDraftSync = <V extends {}>(form: FormikContextType<V>, options: UseItemDraftOptions<V>) => {
const [ready, setReady] = useState<boolean>(false);
const draft = useItemDraft<V>();
const { values, dirty } = form;
const dispatch = useDispatch();
const saveDraft = useCallback(
debounce(
(formData: V) =>
dispatch(
itemDraftSave({
...omit(options, ['onHydrated', 'sanitizeHydration', 'sanitizeSave']),
formData: options.sanitizeSave?.(formData) ?? formData,
})
),
SAVE_DRAFT_TIMEOUT
),
[]
);
useEffect(() => {
if (ready) {
if (dirty) saveDraft(values);
else {
saveDraft.cancel();
dispatch(itemDraftDiscard());
}
}
return () => saveDraft.cancel();
}, [ready, values, dirty]);
useEffect(() => {
void (async () => {
if (draft) {
const formValues = options.sanitizeHydration?.(draft.formData) ?? draft.formData;
await form.setTouched(
Object.keys(formValues).reduce<FormikTouched<any>>((touched, field) => {
touched[field] = true;
return touched;
}, {}),
false
);
await form.setValues(formValues, true);
form.setErrors(await form.validateForm(draft.formData));
options.onHydrated?.(formValues);
} else options.onHydrated?.(null);
setReady(true);
})();
return () => {
/* discard the draft if the component is unmounted :
* this either means the item was successfully saved or
* that the edit/creation discarded */
dispatch(itemDraftDiscard());
};
}, []);
return draft;
};
| 7,726
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useMaxLengthLimiter.ts
|
import type { KeyboardEventHandler } from 'react';
import { c } from 'ttag';
import { useNotifications } from '@proton/components/hooks';
export const useMaxLengthLimiter = () => {
const { createNotification } = useNotifications();
return (
maxLength: number,
originalOnKeyDown?: KeyboardEventHandler<HTMLInputElement | HTMLTextAreaElement>
): KeyboardEventHandler<HTMLInputElement | HTMLTextAreaElement> =>
(event) => {
if (event.key.length === 1 && event.currentTarget.value.length >= maxLength) {
createNotification({
key: 'max-length-limiter',
type: 'warning',
deduplicate: true,
text: c('Info').t`You have reached the maximum allowed length of ${maxLength} characters.`,
});
}
originalOnKeyDown?.(event);
};
};
| 7,727
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useMenuItems.ts
|
import { useDispatch } from 'react-redux';
import { c } from 'ttag';
import type { IconName } from '@proton/components';
import { usePasswordContext } from '@proton/pass//components/PasswordGenerator/PasswordContext';
import { syncIntent } from '@proton/pass//store/actions';
import { usePassCore } from '@proton/pass/components/Core/PassCoreProvider';
import {
PASS_ANDROID_URL,
PASS_GITHUB_URL,
PASS_IOS_URL,
PASS_REDDIT_URL,
PASS_REQUEST_URL,
PASS_X_URL,
} from '@proton/pass/constants';
import { withTap } from '@proton/pass/utils/fp/pipe';
import noop from '@proton/utils/noop';
export type MenuItem = {
icon: IconName;
label: string;
url?: string;
onClick?: () => void;
};
type MenuItemsOptions = { onAction?: () => void };
export const useMenuItems = ({
onAction = noop,
}: MenuItemsOptions): Record<'feedback' | 'download' | 'advanced', MenuItem[]> => {
const { openSettings } = usePassCore();
const { openPasswordHistory } = usePasswordContext();
const dispatch = useDispatch();
const withAction = withTap(onAction);
return {
feedback: [
{
icon: 'paper-plane',
label: c('Action').t`Send us a message`,
onClick: withAction(() => openSettings?.('support')),
},
{
icon: 'brand-twitter',
label: c('Action').t`Write us on Twitter`,
url: PASS_X_URL,
},
{
icon: 'brand-reddit',
label: c('Action').t`Write us on Reddit`,
url: PASS_REDDIT_URL,
},
{
icon: 'brand-github',
label: c('Action').t`Help us improve`,
url: PASS_GITHUB_URL,
},
{
icon: 'rocket',
label: c('Action').t`Request a feature`,
url: PASS_REQUEST_URL,
},
],
download: [
{
icon: 'brand-android',
label: c('Action').t`Pass for Android`,
url: PASS_ANDROID_URL,
},
{
icon: 'brand-apple',
label: c('Action').t`Pass for iOS`,
url: PASS_IOS_URL,
},
],
advanced: [
{
icon: 'key-history',
label: c('Action').t`Generated passwords`,
onClick: withAction(openPasswordHistory),
},
{
icon: 'arrow-rotate-right',
label: c('Action').t`Manually sync your data`,
onClick: withAction(() => dispatch(syncIntent())),
},
],
};
};
| 7,728
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useNavigateToUpgrade.ts
|
import { usePassCore } from '@proton/pass/components/Core/PassCoreProvider';
export const useNavigateToUpgrade = () => {
const { onLink, config } = usePassCore();
return () => onLink(`${config.SSO_URL}/pass/upgrade`);
};
| 7,729
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useNotificationEnhancer.tsx
|
import { type FC, useCallback } from 'react';
import { c } from 'ttag';
import { CircleLoader } from '@proton/atoms/CircleLoader';
import { Icon, InlineLinkButton } from '@proton/components/components';
import type { Notification } from '@proton/pass/store/actions/with-notification';
import { NotificationKey } from '@proton/pass/types/worker/notification';
import { usePassConfig } from './usePassConfig';
type NotificationEnhancerOptions = { onLink: (url: string) => void };
const ReactivateLink: FC<NotificationEnhancerOptions> = ({ onLink }) => {
const { SSO_URL } = usePassConfig();
return (
<InlineLinkButton
key="reactivate-link"
className="text-semibold"
onClick={() => onLink(`${SSO_URL}/encryption-keys`)}
>
{c('Action').t`Learn more`} <Icon name="arrow-out-square" />{' '}
</InlineLinkButton>
);
};
export const useNotificationEnhancer = (options: NotificationEnhancerOptions) =>
useCallback((notification: Notification): Notification => {
const reactivateLink = <ReactivateLink {...options} />;
switch (notification.key) {
case NotificationKey.INACTIVE_SHARES: {
return {
...notification,
text: (
<div>
{c('Error')
.jt`Some vaults are no longer accessible due to a password reset. Reactivate your account keys in order to regain access. ${reactivateLink}`}
</div>
),
};
}
default:
return {
...notification,
showCloseButton: notification.showCloseButton && !notification.loading,
text: notification.loading ? (
<>
{notification.text} <CircleLoader />
</>
) : (
notification.text
),
};
}
}, []);
| 7,730
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/usePassConfig.ts
|
import { useContext } from 'react';
import ConfigContext from '@proton/components/containers/config/configContext';
import type { ProtonConfig } from '@proton/shared/lib/interfaces';
export type PassConfig = ProtonConfig & { SSO_URL: string };
export const usePassConfig = () => useContext(ConfigContext) as PassConfig;
| 7,731
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/usePasswordGenerator.tsx
|
import { useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { DEFAULT_PASSWORD_LENGTH, alphabeticChars, digitChars } from '@proton/pass/lib/password/constants';
import type { GeneratePasswordOptions } from '@proton/pass/lib/password/generator';
import { generatePassword } from '@proton/pass/lib/password/generator';
import { SeperatorOptions } from '@proton/pass/lib/password/memorable';
import { popupPasswordOptionsSave } from '@proton/pass/store/actions/creators/popup';
import type { MaybeNull } from '@proton/pass/types';
import { merge } from '@proton/pass/utils/object/merge';
import debounce from '@proton/utils/debounce';
export enum CharType {
Alphabetic,
Digit,
Special,
}
/* Designers mixed the colors of different ui-${type}
* sub-themes for the character colors.. */
export const charTypeToClassName = {
[CharType.Alphabetic]: '',
[CharType.Digit]: 'ui-violet pass-password-generator--char-digit',
[CharType.Special]: 'ui-teal pass-password-generator--char-special',
};
export const getTypeFromChar = (char: string) => {
if (alphabeticChars.includes(char)) return CharType.Alphabetic;
if (digitChars.includes(char)) return CharType.Digit;
return CharType.Special;
};
export const getCharsGroupedByColor = (password: string) => {
if (password.length === 0) return [];
const [head, ...chars] = Array.from(password);
const startType = getTypeFromChar(head);
return chars
.reduce(
(state, currentChar) => {
const currentElement = state[state.length - 1];
const previousType = currentElement.color;
const currentType = getTypeFromChar(currentChar);
return previousType !== currentType
? [...state, { color: currentType, content: currentChar }]
: [...state.slice(0, -1), { color: previousType, content: currentElement.content + currentChar }];
},
[{ color: startType, content: head }]
)
.map(({ color, content }, index) => (
<span className={charTypeToClassName[color]} key={index}>
{content}
</span>
));
};
export const DEFAULT_MEMORABLE_PW_OPTIONS: GeneratePasswordOptions = {
type: 'memorable',
options: {
wordCount: 4,
seperator: SeperatorOptions.HYPHEN,
capitalize: true,
extraNumbers: true,
},
};
export const DEFAULT_RANDOM_PW_OPTIONS: GeneratePasswordOptions = {
type: 'random',
options: {
length: DEFAULT_PASSWORD_LENGTH,
useDigits: true,
useSpecialChars: true,
useUppercase: true,
},
};
export const usePasswordGenerator = (initial: MaybeNull<GeneratePasswordOptions>) => {
const dispatch = useDispatch();
const [passwordOptions, setOptions] = useState<GeneratePasswordOptions>(initial ?? DEFAULT_MEMORABLE_PW_OPTIONS);
const [password, setPassword] = useState(() => generatePassword(passwordOptions));
const regeneratePassword = () => setPassword(generatePassword(passwordOptions));
const setPasswordOptions = <T extends GeneratePasswordOptions['type']>(
type: T,
update?: Partial<Extract<GeneratePasswordOptions, { type: T }>['options']>
) =>
setOptions((options) => {
if (update) return merge(options, { options: update });
if (type === 'memorable') return DEFAULT_MEMORABLE_PW_OPTIONS;
if (type === 'random') return DEFAULT_RANDOM_PW_OPTIONS;
return options;
});
const options = Object.values(passwordOptions.options);
const savePasswordOptions = useCallback(
debounce((opts: GeneratePasswordOptions) => dispatch(popupPasswordOptionsSave(opts)), 250),
[]
);
useEffect(() => {
regeneratePassword();
savePasswordOptions(passwordOptions);
}, [...options]);
return {
password,
passwordOptions,
setPassword,
setPasswordOptions,
regeneratePassword,
};
};
export type UsePasswordGeneratorResult = ReturnType<typeof usePasswordGenerator>;
| 7,732
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/usePasteLengthLimiter.ts
|
import type { ClipboardEventHandler } from 'react';
import { c } from 'ttag';
import { useNotifications } from '@proton/components/hooks';
export const usePasteLengthLimiter = () => {
const { createNotification } = useNotifications();
return (
maxLength: number,
originalOnPaste?: ClipboardEventHandler<HTMLInputElement | HTMLTextAreaElement>
): ClipboardEventHandler<HTMLInputElement | HTMLTextAreaElement> =>
(event) => {
const text = event.clipboardData?.getData('text') ?? '';
const { value, selectionStart, selectionEnd } = event.currentTarget;
const base = value.length - ((selectionEnd ?? 0) - (selectionStart ?? 0));
if (base + text.length > maxLength) {
createNotification({
key: 'max-length-limiter',
type: 'warning',
deduplicate: true,
text: c('Info')
.t`The text you're trying to paste is longer than the maximum allowed length of ${maxLength} characters.`,
});
}
originalOnPaste?.(event);
};
};
| 7,733
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/usePeriodicOtpCode.ts
|
import { useCallback, useEffect, useRef, useState } from 'react';
import { c } from 'ttag';
import { useNotifications } from '@proton/components';
import type { MaybeNull, MaybePromise, OtpCode, OtpRequest } from '@proton/pass/types';
import { useEnsureMounted } from './useEnsureMounted';
export type UsePeriodOtpCodeOptions = {
/** defines how you want to resolve the OTP Code. In the case of the
* extension we can leverage worker messaging. For the web-app, this
* will use the OTP generation utilities in-place. */
generate: (payload: OtpRequest) => MaybePromise<MaybeNull<OtpCode>>;
payload: OtpRequest;
};
export const usePeriodicOtpCode = ({ generate, payload }: UsePeriodOtpCodeOptions): [MaybeNull<OtpCode>, number] => {
const { shareId, itemId, type } = payload;
const [otp, setOtp] = useState<MaybeNull<OtpCode>>(null);
const [percentage, setPercentage] = useState<number>(-1);
const requestAnimationRef = useRef<number>(-1);
const ensureMounted = useEnsureMounted();
const { createNotification } = useNotifications();
/* Only trigger the countdown if we have a valid
* OTP code with a valid period - else do nothing */
const doRequestOtpCodeGeneration = useCallback(async () => {
const otpCode = await generate(payload);
ensureMounted(setOtp)(otpCode);
if (otpCode === null) {
return createNotification({
text: c('Error').t`Unable to generate an OTP code for this item`,
type: 'error',
});
}
if (otpCode !== null && otpCode.period && otpCode.period > 0) {
const applyCountdown = ensureMounted(() => {
requestAnimationRef.current = requestAnimationFrame(() => {
const ms = otpCode.expiry * 1000 - Date.now();
setPercentage(ms / (otpCode.period * 1000));
applyCountdown();
});
});
applyCountdown();
}
}, [shareId, itemId, type]);
/* if countdown has reached the 0 limit, trigger
* a new OTP Code generation sequence */
useEffect(() => {
if (percentage < 0) {
cancelAnimationFrame(requestAnimationRef.current);
void doRequestOtpCodeGeneration();
}
}, [percentage, doRequestOtpCodeGeneration]);
/* if any of the props change : clear the request
* animation frame request and re-init state */
useEffect(
() => () => {
setOtp(null);
setPercentage(-1);
cancelAnimationFrame(requestAnimationRef.current);
},
[shareId, itemId, type, payload.totpUri]
);
return [otp, percentage];
};
| 7,734
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useSessionLockPinSubmitEffect.ts
|
import { useEffect, useRef } from 'react';
import { SESSION_LOCK_PIN_LENGTH } from '../components/Lock/constants';
import { useDebouncedValue } from './useDebouncedValue';
type UseSessionLockPinOptions = {
onSubmit: (pin: string) => void;
};
/* Calls onSubmit when the PIN has reached the necessary length */
export const useSessionLockPinSubmitEffect = (pin: string, { onSubmit }: UseSessionLockPinOptions) => {
const value = useDebouncedValue(pin, 150);
const onSubmitRef = useRef(onSubmit);
useEffect(() => {
onSubmitRef.current = onSubmit;
}, [onSubmit]);
useEffect(() => {
const safePin = value.replaceAll(/\s+/g, '');
if (safePin.length === SESSION_LOCK_PIN_LENGTH) onSubmitRef.current(value);
}, [value]);
};
| 7,735
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useShareAccessOptionsPolling.ts
|
import { useEffect, useRef, useState } from 'react';
import usePrevious from '@proton/hooks/usePrevious';
import { ACTIVE_POLLING_TIMEOUT } from '@proton/pass/lib/events/constants';
import { getShareAccessOptionsIntent } from '@proton/pass/store/actions';
import { type Maybe } from '@proton/pass/types';
import { useActionRequest } from './useActionRequest';
export const useShareAccessOptionsPolling = (shareId: string) => {
const timer = useRef<Maybe<ReturnType<typeof setTimeout>>>();
const { loading, dispatch, revalidate } = useActionRequest({ action: getShareAccessOptionsIntent });
const wasLoading = usePrevious(loading);
const [didLoad, setDidLoad] = useState(false);
useEffect(() => {
timer.current = setInterval(() => dispatch(shareId), ACTIVE_POLLING_TIMEOUT);
revalidate(shareId);
return () => clearInterval(timer.current);
}, [shareId]);
useEffect(() => {
if (wasLoading === true && !loading) setDidLoad(true);
}, [loading]);
return didLoad ? false : loading;
};
| 7,736
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useTabsQuery.ts
|
import { useEffect } from 'react';
import type { Tabs } from 'webextension-polyfill';
import browser from '@proton/pass/lib/globals/browser';
import noop from '@proton/utils/noop';
export const useTabsQuery = (query: Tabs.QueryQueryInfoType, onTabsResult: (url: Tabs.Tab[]) => void) => {
useEffect(() => {
browser.tabs.query(query).then(onTabsResult).catch(noop);
}, []);
};
| 7,737
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass
|
petrpan-code/ProtonMail/WebClients/packages/pass/hooks/useVisibleEffect.ts
|
import { useEffect, useRef } from 'react';
import type { Maybe } from '@proton/pass/types/utils';
const FOCUS_CHECK_DELAY = 10;
export const isDocumentVisible = () => document.visibilityState === 'visible';
export const isDocumentFocused = () => document.hasFocus();
export const useVisibleEffect = (effect: (visible: boolean) => void) => {
const timer = useRef<Maybe<NodeJS.Timeout>>();
const active = useRef<boolean>(true);
useEffect(() => {
const handler = () => {
clearTimeout(timer.current);
timer.current = setTimeout(() => {
const wasActive = active.current;
const isActive = isDocumentVisible() || isDocumentFocused();
if (wasActive !== isActive) {
active.current = isActive;
effect(isActive);
}
}, FOCUS_CHECK_DELAY);
};
window.addEventListener('focus', handler);
window.addEventListener('blur', handler);
document.addEventListener('visibilitychange', handler);
handler();
return () => {
window.removeEventListener('focus', handler);
window.removeEventListener('blur', handler);
document.removeEventListener('visibilitychange', handler);
return clearTimeout(timer.current);
};
}, []);
};
| 7,738
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/api/api.ts
|
import type { Api } from '@proton/pass/types';
export let api: Api;
export const exposeApi = (value: Api) => (api = value);
| 7,739
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/api/errors.ts
|
export const LockedSessionError = () => {
const error = new Error('Session locked');
error.name = 'LockedSession';
return error;
};
| 7,740
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/api/factory.ts
|
import { defaultApiStatus } from '@proton/components/containers/api/apiStatusContext';
import { updateServerTime } from '@proton/crypto/lib/serverTime';
import type {
Api,
ApiAuth,
ApiCallFn,
ApiOptions,
ApiResult,
ApiState,
ApiSubscribtionEvent,
Maybe,
} from '@proton/pass/types';
import { waitUntil } from '@proton/pass/utils/fp/wait-until';
import { logger } from '@proton/pass/utils/logger';
import { createPubSub } from '@proton/pass/utils/pubsub/factory';
import configureApi from '@proton/shared/lib/api';
import {
getApiError,
getApiErrorMessage,
getIsOfflineError,
getIsUnreachableError,
} from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { getClientID } from '@proton/shared/lib/apps/helper';
import xhr from '@proton/shared/lib/fetch/fetch';
import { withLocaleHeaders } from '@proton/shared/lib/fetch/headers';
import { getDateHeader } from '@proton/shared/lib/fetch/helpers';
import { localeCode } from '@proton/shared/lib/i18n';
import type { ProtonConfig } from '@proton/shared/lib/interfaces/config';
import { withApiHandlers } from './handlers';
import { createRefreshHandler } from './refresh';
import { getSilenced } from './utils';
export type ApiFactoryOptions = {
config: ProtonConfig;
getAuth: () => Maybe<ApiAuth>;
};
export const createApi = ({ config, getAuth }: ApiFactoryOptions): Api => {
const pubsub = createPubSub<ApiSubscribtionEvent>();
const clientID = getClientID(config.APP_NAME);
const state: ApiState = {
appVersionBad: false,
offline: false,
pendingCount: 0,
serverTime: undefined,
sessionInactive: false,
sessionLocked: false,
unreachable: false,
};
const call = configureApi({ ...config, clientID, xhr } as any) as ApiCallFn;
const refreshHandler = createRefreshHandler({
call,
getAuth,
onRefresh: (data) => pubsub.publish({ type: 'refresh', data }),
});
const apiCall = withApiHandlers({ call, getAuth, refreshHandler, state });
const api = async ({ output = 'json', ...rest }: ApiOptions): Promise<ApiResult> => {
const config = getAuth() ? rest : withLocaleHeaders(localeCode, rest);
state.pendingCount += 1;
return apiCall(config)
.then((response) => {
/* The HTTP Date header is mandatory, so this should never
* occur. We need the server time for proper time sync: falling
* back to the local time can result in e.g. unverifiable signatures */
const serverTime = getDateHeader(response.headers);
if (!serverTime) throw new Error('Could not fetch server time');
state.serverTime = updateServerTime(serverTime);
return Promise.resolve(
(() => {
switch (output) {
case 'stream':
return response.body;
case 'raw':
return response;
default:
return response[output]();
}
})()
);
})
.catch((e: any) => {
const serverTime = e.response?.headers ? getDateHeader(e.response.headers) : undefined;
const { code } = getApiError(e);
const error = getApiErrorMessage(e);
const isOffline = getIsOfflineError(e);
const isUnreachable = getIsUnreachableError(e);
state.serverTime = serverTime ? updateServerTime(serverTime) : state.serverTime;
state.unreachable = isUnreachable;
state.offline = isOffline || defaultApiStatus.offline;
state.appVersionBad = e.name === 'AppVersionBadError';
state.sessionInactive = e.name === 'InactiveSession';
state.sessionLocked = e.name === 'LockedSession';
if (state.sessionLocked) pubsub.publish({ type: 'session', status: 'locked' });
if (state.sessionInactive) pubsub.publish({ type: 'session', status: 'inactive' });
if (error && !getSilenced(e.config, code)) pubsub.publish({ type: 'error', error });
throw e;
})
.finally(() => (state.pendingCount -= 1));
};
api.getState = () => state;
api.reset = async () => {
/* if API has pending requests - wait for API to be completely
* idle before resetting state - this avoids race conditions.
* ie: on session inactive error propagating to every pending call */
if (api.getState().pendingCount > 0) {
logger.info(`[API] Reset deferred until API idle`);
await waitUntil(() => api.getState().pendingCount === 0, 50);
}
state.pendingCount = 0;
state.serverTime = undefined;
state.appVersionBad = false;
state.offline = false;
state.unreachable = false;
state.sessionInactive = false;
state.sessionLocked = false;
logger.info(`[API] internal api state reset`);
};
api.subscribe = pubsub.subscribe;
api.unsubscribe = pubsub.unsubscribe;
return api as Api;
};
| 7,741
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/api/handlers.ts
|
import type { ApiAuth, ApiCallFn, ApiOptions, ApiState, Maybe } from '@proton/pass/types';
import { getApiError } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { retryHandler } from '@proton/shared/lib/api/helpers/retryHandler';
import { AppVersionBadError, InactiveSessionError } from '@proton/shared/lib/api/helpers/withApiHandlers';
import { OFFLINE_RETRY_ATTEMPTS_MAX, OFFLINE_RETRY_DELAY, RETRY_ATTEMPTS_MAX } from '@proton/shared/lib/constants';
import { API_CUSTOM_ERROR_CODES, HTTP_ERROR_CODES } from '@proton/shared/lib/errors';
import { withAuthHeaders } from '@proton/shared/lib/fetch/headers';
import { getDateHeader } from '@proton/shared/lib/fetch/helpers';
import { wait } from '@proton/shared/lib/helpers/promise';
import { LockedSessionError } from './errors';
import type { RefreshHandler } from './refresh';
import { isPassSessionRoute } from './utils';
type ApiHandlersOptions = {
call: ApiCallFn;
getAuth: () => Maybe<ApiAuth>;
refreshHandler: RefreshHandler;
state: ApiState;
};
/* Simplified version of withApiHandlers.js :
* - handles recursive session refresh
* - handles appBadVersion
* - handles basic offline error detection
* - FIXME: handle code 9001 errors with human verification */
export const withApiHandlers = ({ call, getAuth, refreshHandler, state }: ApiHandlersOptions): ApiCallFn => {
return (options: ApiOptions) => {
const {
ignoreHandler = [],
retriesOnOffline = OFFLINE_RETRY_ATTEMPTS_MAX,
retriesOnTimeout = OFFLINE_RETRY_ATTEMPTS_MAX,
} = options ?? {};
const next = async (attempts: number, maxAttempts?: number): Promise<any> => {
if (state.sessionInactive) throw InactiveSessionError();
if (state.appVersionBad) throw AppVersionBadError();
if (state.sessionLocked && !isPassSessionRoute(options?.url)) throw LockedSessionError();
try {
const auth = getAuth();
return await call(auth ? withAuthHeaders(auth.UID, auth.AccessToken, options) : options);
} catch (error: any) {
const { status, name, response } = error;
const { code } = getApiError(error);
if (maxAttempts && attempts >= maxAttempts) throw error;
/* Inactive extension session : only throw a `LockedSessionError`
* when we have not reached the max amount of unlock tries. After
* 3 unsuccessful attempts - we will get a 401 */
if (code === 300008 && status === HTTP_ERROR_CODES.UNPROCESSABLE_ENTITY) throw LockedSessionError();
if (code === API_CUSTOM_ERROR_CODES.APP_VERSION_BAD) throw AppVersionBadError();
if (name === 'OfflineError') {
if (attempts > retriesOnOffline) throw error;
await wait(OFFLINE_RETRY_DELAY);
return next(attempts + 1, retriesOnOffline);
}
if (name === 'TimeoutError') {
if (attempts > retriesOnTimeout) throw error;
return next(attempts + 1, retriesOnTimeout);
}
if (status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS && !ignoreHandler.includes(status)) {
await retryHandler(error);
return next(attempts + 1, RETRY_ATTEMPTS_MAX);
}
if (status === HTTP_ERROR_CODES.UNAUTHORIZED && !ignoreHandler.includes(status)) {
try {
await refreshHandler(getDateHeader(response?.headers));
return next(attempts + 1, RETRY_ATTEMPTS_MAX);
} catch (err: any) {
if (err.status >= 400 && err.status <= 499) throw InactiveSessionError();
throw err;
}
}
throw error;
}
};
return next(1);
};
};
| 7,742
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/api/proxy.ts
|
import { type Maybe } from '@proton/pass/types';
import { truthy } from '@proton/pass/utils/fp/predicates';
import { logger } from '@proton/pass/utils/logger';
import { getApiError } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { getAuthHeaders } from '@proton/shared/lib/fetch/headers';
import noop from '@proton/utils/noop';
import randomIntFromInterval from '@proton/utils/randomIntFromInterval';
export type APIProxyOptions = {
apiUrl: string;
apiProxyUrl: string;
fetch: (info: RequestInfo, init?: RequestInit) => Promise<Response>;
};
export const API_PROXY_KEY = 'api-proxy';
export const API_PROXY_IMAGE_ENDPOINT = 'core/v4/images/logo';
export const API_PROXY_ENDPOINTS = [API_PROXY_IMAGE_ENDPOINT];
export const API_IMAGE_DEFAULT_MAX_AGE = 1_209_600; /* 14 days */
export const API_IMAGE_FALLBACK_MAX_AGE = 86_400; /* 1 day */
export const API_BODYLESS_STATUS_CODES = [101, 204, 205, 304];
const withDelay = (value: number) => value + randomIntFromInterval(0, 3_600);
/** Encode the authentication data in the cache request URL */
export const withAuthHash = (url: string, UID: string, AccessToken: string) =>
`${url}#${btoa(JSON.stringify({ UID, AccessToken }))}`;
/** Extract the authentication data from the hash if any */
export const getAuthFromHash = (url: URL): Maybe<{ UID: string; AccessToken: string }> => {
try {
const [, ...hash] = url.hash;
const auth = JSON.parse(atob(hash.join('')));
if ('UID' in auth && 'AccessToken' in auth) {
url.hash = '';
return { UID: auth.UID, AccessToken: auth.AccessToken };
}
} catch {}
};
/** stale-while-revalidate approach :
* Should account for stale-while-revalidate window
* when backend supports this cache header directive.
* Leveraging standard Cache-Control directives:
* - `max-age: <seconds>`
* - `stale-while-revalidate: <seconds>` <- FIXME
* would allow us not to query the remote API on every request,
* as long as the cache response is "fresh", and only perform the
* request when the cache response is "stale" */
const shouldRevalidate = (response: Response): boolean => {
const cacheControlHeader = response.headers.get('Cache-Control');
const dateHeader = response.headers.get('Date');
const maxAge = cacheControlHeader?.match(/max-age=(\d+)/)?.[1];
const date = dateHeader ? new Date(dateHeader) : null;
if (maxAge !== undefined && date) {
const now = new Date();
date.setSeconds(date.getSeconds() + parseInt(maxAge, 10));
return date.getTime() < now.getTime();
}
return true;
};
/** Opens the API proxy cache and wipes every stale
* entries. This allows triggering revalidation */
export const cleanAPIProxyCache = async () => {
try {
const cache = await caches.open(API_PROXY_KEY);
const cacheKeys = await cache.keys();
const staleKeys = (
await Promise.all(
cacheKeys.map(async (request) => {
const res = await cache.match(request);
return res && shouldRevalidate(res) ? request : null;
})
)
).filter(truthy);
logger.info(`[CacheProxy] Removing ${staleKeys.length} stale cache entrie(s)`);
await Promise.all(staleKeys.map((req) => cache.delete(req)));
} catch {}
};
/** Clears the whole API proxy cache */
export const clearAPIProxyCache = () => caches.delete(API_PROXY_KEY).catch(noop);
const createAPIProxyHandler =
(options: APIProxyOptions) =>
async (remotePath: string, method: string): Promise<Response> => {
const apiProxyCache = await caches.open(API_PROXY_KEY);
const url = new URL(`${options.apiUrl}/${remotePath}`);
const auth = getAuthFromHash(url);
const cachedResponse = await apiProxyCache.match(url);
if (cachedResponse && !shouldRevalidate(cachedResponse)) {
logger.debug(`[CacheProxy] Serving GET ${url} from cache without revalidation`);
return cachedResponse;
}
logger.debug(`[CacheProxy] Attempting to revalidate GET ${url} from network`);
const response = options
.fetch(url.toString(), { method, ...(auth ? { headers: getAuthHeaders(auth.UID, auth.AccessToken) } : {}) })
.then(async (res) => {
logger.debug('[CacheProxy] Caching succesful network response', res.url);
if (API_BODYLESS_STATUS_CODES.includes(res.status)) {
void apiProxyCache.put(url, res.clone());
return res;
} else {
/* max-age is set to 0 on image responses from BE: this is sub-optimal in
* the context of the extension -> override the max-age header. */
const headers = new Headers(res.headers);
headers.set('Date', res.headers.get('Date') ?? new Date().toUTCString());
headers.set('Cache-Control', `max-age=${withDelay(API_IMAGE_DEFAULT_MAX_AGE)}`);
const response = new Response(await res.blob(), {
status: res.status,
statusText: res.statusText,
headers,
});
void apiProxyCache.put(url, response.clone());
return response;
}
})
.catch((err) => {
logger.debug(`[CacheProxy] Network or API error while fetching ${url}`, err);
/* When dealing with unprocessable content from the image
* endpoint - cache the error eitherway for now as we want
* to avoid swarming the service-worker with unnecessary
* parallel requests which may block other api calls with
* higher priority */
if (getApiError(err).status === 422 && err.response.url.includes(API_PROXY_IMAGE_ENDPOINT)) {
const res = err.response as Response;
const headers = new Headers(res.headers);
headers.set('Date', res.headers.get('Date') ?? new Date().toUTCString());
headers.set('Cache-Control', `max-age=${withDelay(API_IMAGE_FALLBACK_MAX_AGE)}`);
const response = new Response('Unprocessable Content', {
status: res.status,
statusText: res.statusText,
headers,
});
void apiProxyCache.put(url, response.clone());
return response;
}
return new Response('Network error', {
status: 408,
headers: { 'Content-Type': 'text/plain' },
});
});
// FIXME: stale-while-revalidate window should be computed
if (cachedResponse) {
logger.debug(`[CacheProxy] Serving GET ${url} from cache`);
return cachedResponse;
}
logger.debug(`[CacheProxy] Attempting to serve GET ${url} from network`);
return response;
};
export const handleAPIProxy = (options: APIProxyOptions) => (event: FetchEvent) => {
const handler = createAPIProxyHandler(options);
/* Proxy path : GET {apiProxyUrl}/{remotePath}
* Checks SW cache or forwards request to api endpoint */
if (event.request.url.startsWith(options.apiProxyUrl)) {
const remotePath = event.request.url.replace(options.apiProxyUrl, '');
if (API_PROXY_ENDPOINTS.find((allowedEndpoint) => remotePath.startsWith(allowedEndpoint))) {
return event.respondWith(handler(remotePath, event.request.method));
}
logger.debug(`[CacheProxy]: Refusing to serve non-allowed API endpoint for remote path: `, remotePath);
}
};
| 7,743
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/api/refresh.ts
|
import type { ApiAuth, ApiCallFn, Maybe } from '@proton/pass/types';
import { logger } from '@proton/pass/utils/logger';
import { setRefreshCookies as refreshTokens } from '@proton/shared/lib/api/auth';
import { retryHandler } from '@proton/shared/lib/api/helpers/retryHandler';
import { InactiveSessionError } from '@proton/shared/lib/api/helpers/withApiHandlers';
import { createOnceHandler } from '@proton/shared/lib/apiHandlers';
import type { RefreshSessionResponse } from '@proton/shared/lib/authentication/interface';
import { OFFLINE_RETRY_ATTEMPTS_MAX, OFFLINE_RETRY_DELAY, RETRY_ATTEMPTS_MAX } from '@proton/shared/lib/constants';
import { HTTP_ERROR_CODES } from '@proton/shared/lib/errors';
import { withUIDHeaders } from '@proton/shared/lib/fetch/headers';
import { getDateHeader } from '@proton/shared/lib/fetch/helpers';
import { wait } from '@proton/shared/lib/helpers/promise';
import randomIntFromInterval from '@proton/utils/randomIntFromInterval';
export type RefreshHandler = (responseDate?: Date) => Promise<void>;
export type RefreshSessionData = RefreshSessionResponse & { RefreshTime: number };
export type OnRefreshCallback = (response: RefreshSessionData) => void;
type CreateRefreshHandlerOptions = {
call: ApiCallFn;
getAuth: () => Maybe<ApiAuth>;
onRefresh: OnRefreshCallback;
};
/**
* Handle refresh token. Happens when the access token has expired.
* Multiple calls can fail, so this ensures the refresh route is called once.
* Needs to re-handle errors here for that reason.
*/
const refresh = async (options: {
call: ApiCallFn;
getAuth: () => Maybe<ApiAuth>;
attempt: number;
maxAttempts: number;
}): Promise<Response> => {
const { call, getAuth, attempt, maxAttempts } = options;
const auth = getAuth();
try {
if (auth === undefined || !auth.UID) throw InactiveSessionError();
return await call(withUIDHeaders(auth.UID, refreshTokens({ RefreshToken: auth.RefreshToken })));
} catch (error: any) {
if (attempt >= maxAttempts) throw error;
const { status, name } = error;
const next = () => refresh({ call, getAuth, attempt: attempt + 1, maxAttempts: OFFLINE_RETRY_ATTEMPTS_MAX });
if (['OfflineError', 'TimeoutError'].includes(name)) {
if (attempt > OFFLINE_RETRY_ATTEMPTS_MAX) throw error;
await wait(name === 'OfflineError' ? OFFLINE_RETRY_DELAY : 0);
return next();
}
if (status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS) {
await retryHandler(error);
return next();
}
throw error;
}
};
export const createRefreshHandler = ({ call, getAuth, onRefresh }: CreateRefreshHandlerOptions): RefreshHandler => {
const refreshHandlers: Map<string, RefreshHandler> = new Map();
return (responseDate) => {
const auth = getAuth();
if (auth === undefined || !auth.UID) throw InactiveSessionError();
if (!refreshHandlers.has(auth.UID)) {
refreshHandlers.set(
auth.UID,
createOnceHandler(async (responseDate?: Date) => {
await wait(randomIntFromInterval(100, 2000));
const lastRefreshDate = auth.RefreshTime;
if (lastRefreshDate === undefined || +(responseDate ?? new Date()) > lastRefreshDate) {
const response = await refresh({ call, getAuth, attempt: 1, maxAttempts: RETRY_ATTEMPTS_MAX });
const timestamp = getDateHeader(response.headers) ?? new Date();
const result: RefreshSessionResponse = await response.json();
logger.info('[API] Successfully refreshed session tokens');
onRefresh({ ...result, RefreshTime: +timestamp });
await wait(50);
}
})
);
}
return refreshHandlers.get(auth.UID)!(responseDate);
};
};
| 7,744
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/api/utils.ts
|
export const getSilenced = ({ silence }: any = {}, code: string | number): boolean =>
Array.isArray(silence) ? silence.includes(code) : !!silence;
export const isPassSessionRoute = (url?: string): boolean => Boolean(url?.startsWith('pass/v1/user/session/lock'));
| 7,745
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/auth/address.ts
|
import { api } from '@proton/pass/lib/api/api';
import type { GetAllPublicKeysResponse, Maybe } from '@proton/pass/types';
import { getApiError } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { getAllPublicKeys } from '@proton/shared/lib/api/keys';
import { API_CUSTOM_ERROR_CODES } from '@proton/shared/lib/errors';
export const getPublicKeysForEmail = async (email: string): Promise<string[]> => {
const { Address } = await api<GetAllPublicKeysResponse>(getAllPublicKeys({ Email: email, InternalOnly: 1 }));
return Address.Keys.map((key) => key.PublicKey);
};
export const getPrimaryPublicKeyForEmail = async (email: string): Promise<Maybe<string>> => {
try {
const publicKeys = await getPublicKeysForEmail(email);
return publicKeys?.[0];
} catch (err) {
const { code } = getApiError(err);
if (code === API_CUSTOM_ERROR_CODES.KEY_GET_ADDRESS_MISSING) return undefined;
throw err;
}
};
| 7,746
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/auth/fork.ts
|
import { c } from 'ttag';
import type { Api, MaybeNull } from '@proton/pass/types';
import { pullForkSession, setRefreshCookies as refreshTokens } from '@proton/shared/lib/api/auth';
import { getUser } from '@proton/shared/lib/api/user';
import { getAppHref } from '@proton/shared/lib/apps/helper';
import type { FORK_TYPE } from '@proton/shared/lib/authentication/ForkInterface';
import { getKey } from '@proton/shared/lib/authentication/cryptoHelper';
import { InvalidForkConsumeError } from '@proton/shared/lib/authentication/error';
import type { PullForkResponse, RefreshSessionResponse } from '@proton/shared/lib/authentication/interface';
import { getForkDecryptedBlob } from '@proton/shared/lib/authentication/sessionForkBlob';
import { type getConsumeForkParameters } from '@proton/shared/lib/authentication/sessionForking';
import type { APP_NAMES } from '@proton/shared/lib/constants';
import { APPS, MAIL_APP_NAME, PASS_APP_NAME, SSO_PATHS } from '@proton/shared/lib/constants';
import { withAuthHeaders, withUIDHeaders } from '@proton/shared/lib/fetch/headers';
import { encodeBase64URL, uint8ArrayToString } from '@proton/shared/lib/helpers/encoding';
import type { User } from '@proton/shared/lib/interfaces';
import type { AuthSession } from './session';
export type RequestForkOptions = { host?: string; app: APP_NAMES; type?: FORK_TYPE };
export type RequestForkResult = { url: string; state: string };
export const requestFork = ({
host = getAppHref('/', APPS.PROTONACCOUNT),
type,
app,
}: RequestForkOptions): RequestForkResult => {
const state = encodeBase64URL(uint8ArrayToString(crypto.getRandomValues(new Uint8Array(32))));
const searchParams = new URLSearchParams();
searchParams.append('app', app);
searchParams.append('state', state);
searchParams.append('independent', '0');
if (type) searchParams.append('t', type);
return { url: `${host}${SSO_PATHS.AUTHORIZE}?${searchParams.toString()}`, state };
};
export type ConsumeForkParameters = ReturnType<typeof getConsumeForkParameters>;
export type ConsumeForkPayload =
| { mode: 'sso'; localState: MaybeNull<string>; state: string; selector: string; key?: Uint8Array }
| { mode: 'secure'; state: string; selector: string; keyPassword: string };
export type ConsumeForkOptions = { api: Api; apiUrl?: string; payload: ConsumeForkPayload };
/**
* If `keyPassword` is not provided to `ConsumeForkOptions`, it will attempt to recover it from
* the `Payload` property of the `PullForkResponse`. `keyPassword` will always be omitted when
* retrieving the fork options from the url parameters. This is not the case when using secure
* extension messaging where `keyPassword` can safely be passed.
* ⚠️ Only validates the fork state in SSO mode.
*/
export const consumeFork = async (options: ConsumeForkOptions): Promise<AuthSession> => {
const { payload, apiUrl, api } = options;
const validFork =
(payload.mode === 'secure' || (payload.localState !== null && payload.key)) &&
payload.selector &&
payload.state;
if (!validFork) throw new InvalidForkConsumeError(`Invalid fork state`);
const pullForkParams = pullForkSession(payload.selector);
pullForkParams.url = apiUrl ? `${apiUrl}/${pullForkParams.url}` : pullForkParams.url;
const { UID, RefreshToken, LocalID, Payload } = await api<PullForkResponse>(pullForkParams);
const refresh = await api<RefreshSessionResponse>(withUIDHeaders(UID, refreshTokens({ RefreshToken })));
const { User } = await api<{ User: User }>(withAuthHeaders(UID, refresh.AccessToken, getUser()));
const keyPassword =
payload.mode === 'secure'
? payload.keyPassword
: await (async () => {
try {
const key = await getKey(payload.key!);
return (await getForkDecryptedBlob(key, Payload))?.keyPassword ?? '';
} catch (_) {
throw new InvalidForkConsumeError('Failed to decrypt fork payload');
}
})();
return {
AccessToken: refresh.AccessToken,
keyPassword,
LocalID,
RefreshToken: refresh.RefreshToken,
UID,
UserID: User.ID,
};
};
export enum AccountForkResponse {
CONFLICT,
SUCCESS,
ERROR,
}
export const getAccountForkResponsePayload = (type: AccountForkResponse, error?: any) => {
const additionalMessage = error?.message ?? '';
const payload = (() => {
switch (type) {
case AccountForkResponse.CONFLICT: {
return {
title: c('Error').t`Authentication error`,
message: c('Info')
.t`It seems you are already logged in to ${PASS_APP_NAME}. If you're trying to login with a different account, please logout from the extension first.`,
};
}
case AccountForkResponse.SUCCESS: {
return {
title: c('Title').t`Welcome to ${PASS_APP_NAME}`,
message: c('Info')
.t`More than a password manager, ${PASS_APP_NAME} protects your password and your personal email address via email aliases. Powered by the same technology behind ${MAIL_APP_NAME}, your data is end to end encrypted and is only accessible by you.`,
};
}
case AccountForkResponse.ERROR: {
return {
title: c('Error').t`Something went wrong`,
message: c('Warning').t`Unable to sign in to ${PASS_APP_NAME}. ${additionalMessage}`,
};
}
}
})();
return { payload };
};
| 7,747
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/auth/service.ts
|
import { c } from 'ttag';
import type { Maybe, MaybeNull, MaybePromise } from '@proton/pass/types';
import { type Api, SessionLockStatus } from '@proton/pass/types';
import { asyncLock } from '@proton/pass/utils/fp/promises';
import { logger } from '@proton/pass/utils/logger';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import { revoke } from '@proton/shared/lib/api/auth';
import { getApiError, getApiErrorMessage, getIs401Error } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import noop from '@proton/utils/noop';
import { type RefreshSessionData } from '../api/refresh';
import {
type ConsumeForkPayload,
type RequestForkOptions,
type RequestForkResult,
consumeFork,
requestFork,
} from './fork';
import {
type AuthSession,
type PersistedAuthSession,
encryptPersistedSession,
isValidSession,
resumeSession,
} from './session';
import type { SessionLockCheckResult } from './session-lock';
import {
checkSessionLock,
createSessionLock,
deleteSessionLock,
forceSessionLock,
unlockSession,
} from './session-lock';
import { type AuthStore } from './store';
export interface AuthServiceConfig {
api: Api;
/** Store holding the active session data */
authStore: AuthStore;
/** The in-memory session is used to store the session data securely.
* It allows resuming a session without any API calls to re-authenticate.
* In most cases you can omit the implementation and rely on the `authStore` */
getMemorySession?: () => MaybePromise<any>;
/** The persisted session will be parsed and decrypted to extract the
* session data. Requires an API call to retrieve the local key. */
getPersistedSession: (localID: Maybe<number>) => MaybePromise<MaybeNull<PersistedAuthSession>>;
/** Implement any service initialization logic in this hook. Should return
* a boolean flag indicating wether user was authorized or not. */
onInit: (options?: { forceLock: boolean }) => Promise<boolean>;
/** Called when authorization sequence starts: this can happen when consuming a
* session fork or when trying to resume a session. */
onAuthorize?: () => void;
/** Called whenever a user is successfully authenticated. This can happen
* after consuming a fork or resuming a session. */
onAuthorized?: (userID: string, localID: Maybe<number>) => void;
/** Called whenever a user is unauthenticated. This will be triggered any time
* the `logout` function is called (either via user action or when an inactive
* session is detected). The `broadcast` flag indicates wether we should
* broadcast the unauthorized session to other clients. */
onUnauthorized?: (userID: Maybe<string>, localID: Maybe<number>, broadcast: boolean) => void;
/** Called immediately after a fork has been successfully consumed. At this
* point the user is not fully logged in yet. */
onForkConsumed?: (session: AuthSession, state: string) => void;
/** Called when a fork could not be successfully consumed. This can happen
* if the fork data is invalid */
onForkInvalid?: () => void;
/** Handle the result of a fork request call. Can be used to redirect the
* user automatically when requesting a fork from account. */
onForkRequest?: (result: RequestForkResult) => void;
/** Called when an invalid persistent session error is thrown during a
* session resuming sequence. */
onSessionInvalid?: () => void;
/* Called when no persisted session or in-memory session can be used to
* resume a session. */
onSessionEmpty?: () => void;
/** Called when a session is locked either through user action or when a
* locked session is detected. The `broadcast` flag indicates wether we should
* broadcast the locked session to other clients. */
onSessionLocked?: (localID: Maybe<number>, broadcast: boolean) => void;
/* Callback on session lock check. By default, this will be triggered
* on every login sequence. */
onSessionLockCheck?: (data: SessionLockCheckResult) => void;
/** Called with the `sessionLockToken` when session is successfully unlocked */
onSessionUnlocked?: (sessionLockToken: string) => void;
/** Implement encrypted local session persistence using this hook. Called on every
* successful consumed fork or unlocked session. */
onSessionPersist?: (encryptedSession: string) => MaybePromise<void>;
/** Called when resuming the session failed for any reason excluding inactive
* session error. */
onSessionResumeFailure?: () => void;
/** Called when session tokens have been refreshed. The`broadcast` flag indicates
* wether we should broadcast the refresh session data to other clients. */
onSessionRefresh?: (localId: Maybe<number>, data: RefreshSessionData, broadcast: boolean) => MaybePromise<void>;
/** Implement how you want to handle notifications emitted from the service */
onNotification?: (reason: string) => void;
}
export const createAuthService = (config: AuthServiceConfig) => {
const { api, authStore } = config;
const authService = {
init: asyncLock((options?: { forceLock: boolean }) => {
logger.info(`[AuthService] Initialization start`);
return config.onInit(options).catch((err) => {
logger.warn(`[AuthService] Initialization failure`, err);
return false;
});
}),
/** Stores the initial configuration object passed to the
* auth service factory function. Useful if you want to trigger
* certain handlers outside of the auth service flow. */
config,
/** Removes any ongoing API listeners and starts listening for
* authentication relevant API messages.*/
listen: () => {
api.unsubscribe();
api.subscribe((event) => {
switch (event.type) {
case 'session': {
api.unsubscribe();
if (event.status === 'inactive') {
config.onNotification?.(c('Warning').t`Your session is inactive. Please log back in.`);
return authService.logout({ soft: true, broadcast: true });
}
if (event.status === 'locked') {
config.onNotification?.(c('Warning').t`Your session was locked.`);
return authService.lock({ soft: true, broadcast: true });
}
break;
}
case 'refresh': {
const { data } = event;
authStore.setAccessToken(data.AccessToken);
authStore.setRefreshToken(data.RefreshToken);
authStore.setUID(data.UID);
authStore.setRefreshTime(data.RefreshTime);
void config.onSessionRefresh?.(authStore.getLocalID(), data, true);
}
}
});
},
login: async (session: AuthSession) => {
config.onAuthorize?.();
authStore.setUID(session.UID);
authStore.setUserID(session.UserID);
authStore.setLocalID(session.LocalID);
authStore.setPassword(session.keyPassword);
authStore.setLockToken(session.sessionLockToken);
authStore.setAccessToken(session.AccessToken);
authStore.setRefreshToken(session.RefreshToken);
authStore.setRefreshTime(session.RefreshTime);
authService.listen();
try {
const lockStatus = authStore.getLockStatus() ?? (await authService.checkLock()).status;
if (lockStatus === SessionLockStatus.LOCKED) {
logger.info(`[AuthService] Detected locked session`);
await authService.lock({ soft: true, broadcast: false });
return false;
}
if (lockStatus === SessionLockStatus.REGISTERED && !session.sessionLockToken) {
logger.info(`[AuthService] Detected a registered session lock`);
await authService.lock({ soft: true, broadcast: false });
return false;
}
} catch (error: any) {
/* if there is an API error on `checkSessionLock` we want to logout
* the user only if it is due to a 401 or 403 status response */
if (getIs401Error(error) || getApiError(error).status === 403) {
void authService.logout({ soft: true, broadcast: true });
return false;
}
}
logger.info(`[AuthService] User is authorized`);
config.onAuthorized?.(authStore.getUserID()!, authStore.getLocalID());
return true;
},
logout: async (options: { soft: boolean; broadcast?: boolean }) => {
logger.info(`[AuthService] User is not authorized`);
const localID = authStore.getLocalID();
const userID = authStore.getUserID();
if (!options?.soft) void api({ ...revoke(), silent: true });
authStore.clear();
api.unsubscribe();
await api.reset();
config.onUnauthorized?.(userID, localID, options.broadcast ?? true);
return true;
},
consumeFork: async (payload: ConsumeForkPayload, apiUrl?: string): Promise<boolean> => {
try {
config.onAuthorize?.();
const session = await consumeFork({ api, payload, apiUrl });
config.onForkConsumed?.(session, payload.state);
const loggedIn = await authService.login(session);
if (loggedIn) await authService.persistSession();
return loggedIn;
} catch (error: unknown) {
config.onNotification?.(c('Warning').t`Your session could not be authorized.`);
config.onForkInvalid?.();
await authService.logout({ soft: true, broadcast: false });
return false;
}
},
requestFork: (options: RequestForkOptions): RequestForkResult => {
const result = requestFork(options);
config.onForkRequest?.(result);
return result;
},
/** Creates a session lock. Automatically updates the authentication
* store and immediately persists the session on success. */
createLock: async (lockCode: string, sessionLockTTL: number) => {
const sessionLockToken = await createSessionLock(lockCode, sessionLockTTL);
authStore.setLockToken(sessionLockToken);
authStore.setLockTTL(sessionLockTTL);
authStore.setLockStatus(SessionLockStatus.REGISTERED);
void authService.persistSession();
},
/** Deletes a registered session lock. Requires the session lock code.
* Immediately persists the session on success. */
deleteLock: async (lockCode: string) => {
await deleteSessionLock(lockCode);
authStore.setLockToken(undefined);
authStore.setLockTTL(undefined);
authStore.setLockStatus(SessionLockStatus.NONE);
void authService.persistSession();
},
lock: async (options: { soft: boolean; broadcast?: boolean }): Promise<void> => {
logger.info(`[AuthService] Locking session [soft: ${options.soft}]`);
if (!options?.soft) await forceSessionLock().catch(noop);
api.unsubscribe();
authStore.setLockStatus(SessionLockStatus.LOCKED);
authStore.setLockToken(undefined);
authStore.setLockLastExtendTime(undefined);
config.onSessionLocked?.(authStore.getLocalID(), options.broadcast ?? false);
},
unlock: async (pin: string): Promise<void> => {
try {
logger.info(`[AuthService] Unlocking session`);
await api.reset();
authService.listen();
const sessionLockToken = await unlockSession(pin);
authStore.setLockToken(sessionLockToken);
await authService.checkLock();
await authService.persistSession();
await authService.login(authStore.getSession());
config.onSessionUnlocked?.(sessionLockToken);
} catch (error: unknown) {
/* if the session is inactive at this point, it likely means the user
* reached the maximum amount of unlock attempts. Error is thrown so
* clients can react. */
if (api.getState().sessionInactive) void authService.logout({ soft: true, broadcast: true });
else void authService.lock({ soft: true, broadcast: false });
throw error;
}
},
/* Calling this function when a lock is registered and active
* will extend the lock by resetting the ttl server-side */
checkLock: async () => {
logger.info('[AuthService] Checking session lock status');
const lock = await checkSessionLock();
authStore.setLockStatus(lock.status);
authStore.setLockTTL(lock.ttl);
authStore.setLockLastExtendTime(getEpoch());
config.onSessionLockCheck?.(lock);
return lock;
},
persistSession: async () => {
try {
logger.info('[AuthService] Persisting session');
const session = authStore.getSession();
if (!isValidSession(session)) throw new Error('Trying to persist invalid session');
const encryptedSession = await encryptPersistedSession(api, session);
await config.onSessionPersist?.(encryptedSession);
} catch (error) {
logger.warn(`[AuthService] Persisting session failure`, error);
}
},
resumeSession: async (localID: Maybe<number>, options?: { forceLock: boolean }): Promise<boolean> => {
const memorySession = await config.getMemorySession?.();
if (memorySession && isValidSession(memorySession)) {
logger.info(`[Worker::Auth] Resuming in-memory session`);
return authService.login(memorySession);
}
try {
const persistedSession = await config.getPersistedSession(localID);
if (!persistedSession) {
logger.info(`[AuthService] No persisted session found`);
config.onSessionEmpty?.();
return false;
}
logger.info(`[AuthService] Resuming persisted session.`);
config.onAuthorize?.();
authStore.setUserID(persistedSession.UserID);
authStore.setUID(persistedSession.UID);
authStore.setLocalID(persistedSession.LocalID);
authStore.setAccessToken(persistedSession.AccessToken);
authStore.setRefreshToken(persistedSession.RefreshToken);
authStore.setRefreshTime(persistedSession.RefreshTime);
authService.listen();
const session = await resumeSession({
api,
authStore,
persistedSession,
onSessionInvalid: config.onSessionInvalid,
});
logger.info(`[AuthService] Session successfuly resumed`);
/* on `forceLock: true` remove the `sessionLockToken` from the
* session result to trigger an auth lock during the login sequence */
if (options?.forceLock) {
logger.info(`[AuthService] Forcing session lock`);
delete session.sessionLockToken;
}
return await authService.login(session);
} catch (error: unknown) {
const reason = error instanceof Error ? getApiErrorMessage(error) ?? error?.message : '';
logger.warn(`[AuthService] Resuming session failed (${reason})`);
config.onNotification?.(c('Warning').t`Your session could not be resumed.`);
/* if session is inactive : trigger unauthorized sequence */
if (api.getState().sessionInactive) await authService.logout({ soft: true, broadcast: true });
else config.onSessionResumeFailure?.();
return false;
}
},
};
return authService;
};
export type AuthService = ReturnType<typeof createAuthService>;
| 7,748
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/auth/session-lock.ts
|
import { api } from '@proton/pass/lib/api/api';
import { SessionLockStatus } from '@proton/pass/types';
export type SessionLockCheckResult = {
status: SessionLockStatus;
ttl?: number;
};
export const checkSessionLock = async (): Promise<SessionLockCheckResult> => {
try {
const { LockInfo } = await api({ url: 'pass/v1/user/session/lock/check', method: 'get' });
return {
status: LockInfo?.Exists ? SessionLockStatus.REGISTERED : SessionLockStatus.NONE,
ttl: LockInfo?.UnlockedSecs ?? undefined,
};
} catch (e: any) {
if (e?.name === 'LockedSession') return { status: SessionLockStatus.LOCKED };
throw e;
}
};
export const forceSessionLock = async (): Promise<void> => {
await api({
url: 'pass/v1/user/session/lock/force_lock',
method: 'post',
});
};
export const createSessionLock = async (LockCode: string, UnlockedSecs: number): Promise<string> =>
(
await api({
url: 'pass/v1/user/session/lock',
method: 'post',
data: { LockCode, UnlockedSecs },
})
).LockData!.StorageToken;
export const deleteSessionLock = async (LockCode: string): Promise<string> =>
(
await api({
url: 'pass/v1/user/session/lock',
method: 'delete',
data: { LockCode },
})
).LockData!.StorageToken;
export const unlockSession = async (LockCode: string): Promise<string> =>
(
await api({
url: 'pass/v1/user/session/lock/unlock',
method: 'post',
data: { LockCode },
})
).LockData!.StorageToken;
| 7,749
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/auth/session.ts
|
/* Inspired from packages/shared/lib/authentication/persistedSessionHelper.ts */
import type { Api } from '@proton/pass/types';
import { isObject } from '@proton/pass/utils/object/is-object';
import { getLocalKey, setLocalKey } from '@proton/shared/lib/api/auth';
import { InactiveSessionError } from '@proton/shared/lib/api/helpers/withApiHandlers';
import { getUser } from '@proton/shared/lib/api/user';
import { getKey } from '@proton/shared/lib/authentication/cryptoHelper';
import { InvalidPersistentSessionError } from '@proton/shared/lib/authentication/error';
import type { LocalKeyResponse } from '@proton/shared/lib/authentication/interface';
import { getDecryptedBlob, getEncryptedBlob } from '@proton/shared/lib/authentication/sessionBlobCryptoHelper';
import { withAuthHeaders } from '@proton/shared/lib/fetch/headers';
import { base64StringToUint8Array, uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import type { User as UserType } from '@proton/shared/lib/interfaces';
import type { AuthStore } from './store';
export type AuthSession = {
AccessToken: string;
keyPassword: string;
LocalID?: number;
RefreshTime?: number;
RefreshToken: string;
sessionLockToken?: string;
UID: string;
UserID: string;
};
export type PersistedAuthSession = Omit<AuthSession, 'keyPassword' | 'sessionLockToken'> & { blob: string };
export type PersistedAuthSessionBlob = Pick<AuthSession, 'keyPassword' | 'sessionLockToken'>;
export const SESSION_KEYS: (keyof AuthSession)[] = [
'AccessToken',
'keyPassword',
'LocalID',
'RefreshToken',
'sessionLockToken',
'UID',
'UserID',
];
export const isValidSession = (data: Partial<AuthSession>): data is AuthSession =>
Boolean(data.AccessToken && data.keyPassword && data.RefreshToken && data.UID && data.UserID);
export const isValidPersistedSession = (data: any): data is PersistedAuthSession =>
isObject(data) &&
Boolean('AccessToken' in data && data.AccessToken) &&
Boolean('RefreshToken' in data && data.RefreshToken) &&
Boolean('UID' in data && data.UID) &&
Boolean('UserID' in data && data.UserID) &&
Boolean('blob' in data && data.blob);
export const encryptPersistedSession = async (
api: Api,
{ keyPassword, sessionLockToken, ...session }: AuthSession
): Promise<string> => {
const rawKey = crypto.getRandomValues(new Uint8Array(32));
const key = await getKey(rawKey);
const base64StringKey = uint8ArrayToBase64String(rawKey);
await api<LocalKeyResponse>(withAuthHeaders(session.UID, session.AccessToken, setLocalKey(base64StringKey)));
return JSON.stringify({
...session,
blob: await getEncryptedBlob(key, JSON.stringify({ keyPassword, sessionLockToken })),
});
};
export const getPersistedSessionKey = async (api: Api): Promise<CryptoKey> => {
const { ClientKey } = await api<LocalKeyResponse>(getLocalKey());
const rawKey = base64StringToUint8Array(ClientKey);
return getKey(rawKey);
};
const decryptPersistedSessionBlob = async (key: CryptoKey, blob: string): Promise<string> => {
try {
return await getDecryptedBlob(key, blob);
} catch (_) {
throw new InvalidPersistentSessionError('Failed to decrypt persisted session blob');
}
};
const parsePersistedSessionBlob = (blob: string): PersistedAuthSessionBlob => {
try {
const parsedValue = JSON.parse(blob);
return {
keyPassword: parsedValue?.keyPassword ?? '',
sessionLockToken: parsedValue?.sessionLockToken,
};
} catch (_) {
throw new InvalidPersistentSessionError('Failed to parse persisted session blob');
}
};
export const decryptPersistedSession = async (key: CryptoKey, blob: string): Promise<PersistedAuthSessionBlob> => {
const decryptedBlob = await decryptPersistedSessionBlob(key, blob);
const persistedSessionBlob = parsePersistedSessionBlob(decryptedBlob);
return persistedSessionBlob;
};
type ResumeSessionOptions = {
api: Api;
authStore: AuthStore;
persistedSession: PersistedAuthSession;
onSessionInvalid?: () => void;
};
/* Session resuming flow responsible for decrypting the encrypted session
* blob. Ensure the authentication store is configured with authentication
* options in order for requests to succeed */
export const resumeSession = async ({
api,
authStore,
persistedSession,
onSessionInvalid,
}: ResumeSessionOptions): Promise<AuthSession> => {
try {
const [sessionKey, { User }] = await Promise.all([
getPersistedSessionKey(api),
api<{ User: UserType }>(getUser()),
]);
if (persistedSession.UserID !== User.ID) throw InactiveSessionError();
const ps = await decryptPersistedSession(sessionKey, persistedSession.blob);
return {
...authStore.getSession(),
keyPassword: ps.keyPassword,
sessionLockToken: ps.sessionLockToken,
};
} catch (error: any) {
if (error instanceof InvalidPersistentSessionError) onSessionInvalid?.();
throw error;
}
};
| 7,750
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/auth/store.ts
|
import type { Maybe, SessionLockStatus } from '@proton/pass/types';
import type { Store } from '@proton/pass/utils/store';
import { encodedGetter, encodedSetter } from '@proton/pass/utils/store';
import type { AuthSession } from './session';
export type AuthStore = ReturnType<typeof createAuthStore>;
const PASS_ACCESS_TOKEN_KEY = 'pass:access_token';
const PASS_LOCAL_ID_KEY = 'pass:local_id';
const PASS_LOCK_LAST_EXTEND_TIME = 'pass:lock_extend_time';
const PASS_LOCK_STATUS_KEY = 'pass:lock_status';
const PASS_LOCK_TOKEN_KEY = 'pass:lock_token';
const PASS_LOCK_TTL_KEY = 'pass:lock_ttl';
const PASS_MAILBOX_PWD_KEY = 'pass:mailbox_pwd';
const PASS_REFRESH_TIME_KEY = 'pass:refresh_time';
const PASS_REFRESH_TOKEN_KEY = 'pass:refresh_token';
const PASS_UID_KEY = 'pass:uid';
const PASS_USER_ID_KEY = 'pass:user_id';
export const createAuthStore = (store: Store) => {
const authStore = {
clear: () => store.reset(),
hasSession: (localID?: number) =>
Boolean(authStore.getUID() && (!localID || authStore.getLocalID() === localID)),
getSession: (): AuthSession => ({
AccessToken: authStore.getAccessToken() ?? '',
keyPassword: authStore.getPassword(),
LocalID: authStore.getLocalID(),
RefreshTime: authStore.getRefreshTime(),
RefreshToken: authStore.getRefreshToken() ?? '',
sessionLockToken: authStore.getLockToken(),
UID: authStore.getUID() ?? '',
UserID: authStore.getUserID() ?? '',
}),
setAccessToken: (accessToken: Maybe<string>): void => store.set(PASS_ACCESS_TOKEN_KEY, accessToken),
getAccessToken: (): Maybe<string> => store.get(PASS_ACCESS_TOKEN_KEY),
setRefreshToken: (refreshToken: Maybe<string>): void => store.set(PASS_REFRESH_TOKEN_KEY, refreshToken),
getRefreshToken: (): Maybe<string> => store.get(PASS_REFRESH_TOKEN_KEY),
setRefreshTime: (refreshTime: Maybe<number>) => store.set(PASS_REFRESH_TIME_KEY, refreshTime),
getRefreshTime: (): Maybe<number> => store.get(PASS_REFRESH_TIME_KEY),
setUID: (UID: Maybe<string>): void => store.set(PASS_UID_KEY, UID),
getUID: (): Maybe<string> => store.get(PASS_UID_KEY),
setUserID: (UserID: Maybe<string>): void => store.set(PASS_USER_ID_KEY, UserID),
getUserID: (): Maybe<string> => store.get(PASS_USER_ID_KEY),
setPassword: encodedSetter(store)(PASS_MAILBOX_PWD_KEY),
getPassword: encodedGetter(store)(PASS_MAILBOX_PWD_KEY, ''),
setLocalID: (LocalID: Maybe<number>): void => store.set(PASS_LOCAL_ID_KEY, LocalID),
getLocalID: (): Maybe<number> => store.get(PASS_LOCAL_ID_KEY),
setLockStatus: (status: Maybe<SessionLockStatus>): void => store.set(PASS_LOCK_STATUS_KEY, status),
getLockStatus: (): Maybe<SessionLockStatus> => store.get(PASS_LOCK_STATUS_KEY),
setLockToken: encodedSetter(store)(PASS_LOCK_TOKEN_KEY),
getLockToken: encodedGetter(store)(PASS_LOCK_TOKEN_KEY, undefined),
setLockTTL: (ttl: Maybe<number>) => store.set(PASS_LOCK_TTL_KEY, ttl),
getLockTTL: (): Maybe<number> => store.get(PASS_LOCK_TTL_KEY),
setLockLastExtendTime: (extendTime: Maybe<number>): void => store.set(PASS_LOCK_LAST_EXTEND_TIME, extendTime),
getLockLastExtendTime: (): Maybe<number> => store.get(PASS_LOCK_LAST_EXTEND_TIME),
};
return authStore;
};
export let authentication: AuthStore;
export const exposeAuthStore = (value: AuthStore) => (authentication = value);
| 7,751
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/client/index.ts
|
/**
* Be very careful when editing these predicates :
* They are used accross the worker code-base in order
* to safe-guard certain actions or block them. Some
* of them are also used in the UI code to trigger
* certain effects.
*/
import { AppStatus } from '@proton/pass/types';
import { oneOf, or } from '@proton/pass/utils/fp/predicates';
export const clientReady = oneOf(AppStatus.READY);
export const clientAuthorized = oneOf(AppStatus.AUTHORIZED);
export const clientUnauthorized = oneOf(AppStatus.UNAUTHORIZED, AppStatus.LOCKED);
export const clientLocked = oneOf(AppStatus.LOCKED);
export const clientErrored = oneOf(AppStatus.ERROR);
export const clientStale = oneOf(AppStatus.IDLE);
export const clientBusy = oneOf(AppStatus.IDLE, AppStatus.AUTHORIZED, AppStatus.AUTHORIZING, AppStatus.BOOTING);
export const clientStatusResolved = or(clientReady, clientUnauthorized, clientErrored);
export const clientCanBoot = or(clientAuthorized, clientUnauthorized, clientErrored);
| 7,752
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/pass-crypto.spec.ts
|
import { CryptoProxy } from '@proton/crypto';
import type { ItemRevisionContentsResponse, ShareGetResponse, ShareKeyResponse } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, ItemState, PassEncryptionTag, ShareType } from '@proton/pass/types';
import { ADDRESS_RECEIVE, ADDRESS_SEND, ADDRESS_STATUS } from '@proton/shared/lib/constants';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import type { Address, DecryptedKey, Key, User } from '@proton/shared/lib/interfaces';
import { PassCrypto } from './pass-crypto';
import * as processes from './processes';
import { decryptData } from './utils/crypto-helpers';
import { PassCryptoHydrationError, PassCryptoNotHydratedError, PassCryptoShareError } from './utils/errors';
import {
TEST_KEY_PASSWORD,
TEST_USER_KEY_ID,
createRandomKey,
createRandomShareResponses,
randomContents,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from './utils/testing';
describe('PassCrypto', () => {
let user: User;
let userKey: DecryptedKey;
const address = {
ID: `addressId-${Math.random()}`,
Status: ADDRESS_STATUS.STATUS_ENABLED,
Receive: ADDRESS_RECEIVE.RECEIVE_YES,
Send: ADDRESS_SEND.SEND_YES,
} as Address;
beforeAll(async () => {
await setupCryptoProxyForTesting();
userKey = await createRandomKey();
const PrivateKey = await CryptoProxy.exportPrivateKey({
privateKey: userKey.privateKey,
passphrase: TEST_KEY_PASSWORD,
});
user = {
Keys: [
{
ID: TEST_USER_KEY_ID,
PrivateKey,
Version: 3,
Active: 1,
} as Key,
],
} as User;
});
afterAll(async () => releaseCryptoProxy());
describe('PassCrypto::hydrate', () => {
afterEach(() => PassCrypto.clear());
test('should throw if no user keys', async () => {
await expect(
PassCrypto.hydrate({
user: { Keys: [] } as unknown as User,
addresses: [address],
keyPassword: TEST_KEY_PASSWORD,
})
).rejects.toThrow(PassCryptoHydrationError);
});
test('should throw if no active address keys', async () => {
await expect(
PassCrypto.hydrate({
user,
addresses: [{ ...address, Status: ADDRESS_STATUS.STATUS_DISABLED }],
keyPassword: TEST_KEY_PASSWORD,
})
).rejects.toThrow(PassCryptoHydrationError);
});
test('should hydrate correctly', async () => {
await expect(
PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD })
).resolves.not.toThrow();
});
test('should throw if no active user keys', async () => {
const userKey = user.Keys[0];
const inactiveKey = await createRandomKey();
const inactiveUserKey = await CryptoProxy.exportPrivateKey({
privateKey: inactiveKey.privateKey,
passphrase: `${TEST_KEY_PASSWORD}-inactive`,
});
const userReset = {
...user,
Keys: [
{
...userKey,
ID: `${TEST_USER_KEY_ID}-inactive-1`,
Active: 0,
PrivateKey: inactiveUserKey,
},
],
} as User;
await expect(
PassCrypto.hydrate({ user: userReset, addresses: [address], keyPassword: TEST_KEY_PASSWORD })
).rejects.toThrow(PassCryptoHydrationError);
});
test('should only track active user keys', async () => {
const userKey = user.Keys[0];
const inactiveKey = await createRandomKey();
const inactiveUserKey = await CryptoProxy.exportPrivateKey({
privateKey: inactiveKey.privateKey,
passphrase: `${TEST_KEY_PASSWORD}-inactive`,
});
const userReset = {
...user,
Keys: [
userKey,
{
...userKey,
ID: `${TEST_USER_KEY_ID}-inactive-1`,
Active: 0,
PrivateKey: inactiveUserKey,
},
],
} as User;
await PassCrypto.hydrate({ user: userReset, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
expect(PassCrypto.getContext().userKeys!.length).toEqual(1);
expect(PassCrypto.getContext().userKeys?.[0].ID).toEqual(TEST_USER_KEY_ID);
});
});
describe('PassCrypto::createVault', () => {
afterEach(() => PassCrypto.clear());
test('should throw if PassCrypto not hydrated', async () => {
await expect(PassCrypto.createVault(randomContents())).rejects.toThrow(PassCryptoNotHydratedError);
});
test('should call createVault with primary user key and primary addressId', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
const content = randomContents();
const vault = await PassCrypto.createVault(content);
expect(vault.AddressID).toEqual(address.ID);
expect(vault.ContentFormatVersion).toEqual(CONTENT_FORMAT_VERSION);
const vaultKey = await processes.openVaultKey({
userKeys: [userKey],
shareKey: {
Key: vault.EncryptedVaultKey,
KeyRotation: 1,
CreateTime: 0,
},
});
const decryptedContent = await decryptData(
vaultKey.key,
base64StringToUint8Array(vault.Content),
PassEncryptionTag.VaultContent
);
expect(decryptedContent).toStrictEqual(content);
});
});
describe('PassCrypto::updateVault', () => {
afterEach(() => PassCrypto.clear());
test('should throw if PassCrypto not hydrated', async () => {
await expect(PassCrypto.updateVault({} as any)).rejects.toThrow(PassCryptoNotHydratedError);
});
test('should call updateVault with latest vaultKey', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
const vault = await PassCrypto.createVault(randomContents());
const shareKey: ShareKeyResponse = {
Key: vault.EncryptedVaultKey,
KeyRotation: 42,
CreateTime: 0,
UserKeyID: TEST_USER_KEY_ID,
};
const encryptedShare: ShareGetResponse = {
AddressID: vault.AddressID,
Content: vault.Content,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
ContentKeyRotation: 42,
CreateTime: 0,
ExpireTime: 0,
NewUserInvitesReady: 0,
Owner: true,
PendingInvites: 0,
Permission: 1,
Primary: false,
Shared: false,
ShareID: `shareId-${Math.random()}`,
TargetID: `targetId-${Math.random()}`,
TargetMaxMembers: 2,
TargetMembers: 0,
TargetType: ShareType.Vault,
VaultID: `vaultId-${Math.random()}`,
};
/* register the share */
const share = await PassCrypto.openShare({ encryptedShare, shareKeys: [shareKey] });
const contentUpdate = randomContents();
const vaultUpdate = await PassCrypto.updateVault({ shareId: share!.shareId, content: contentUpdate });
const vaultKey = PassCrypto.getShareManager(share!.shareId).getVaultKey(42);
const decryptedContent = await decryptData(
vaultKey.key,
base64StringToUint8Array(vaultUpdate.Content),
PassEncryptionTag.VaultContent
);
expect(decryptedContent).toStrictEqual(contentUpdate);
expect(vaultUpdate.ContentFormatVersion).toEqual(CONTENT_FORMAT_VERSION);
expect(vaultUpdate.KeyRotation).toEqual(42);
});
});
describe('PassCrypto::openShare', () => {
afterEach(() => PassCrypto.clear());
test('should throw if PassCrypto not hydrated', async () => {
await expect(PassCrypto.openShare({} as any)).rejects.toThrow(PassCryptoNotHydratedError);
});
test('should create a new share manager and add new vault keys on manager', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
/* create a vault */
const content = randomContents();
const vault = await PassCrypto.createVault(content);
const shareKey: ShareKeyResponse = {
Key: vault.EncryptedVaultKey,
KeyRotation: 1,
CreateTime: 0,
UserKeyID: TEST_USER_KEY_ID,
};
/* mock response */
const encryptedShare: ShareGetResponse = {
AddressID: vault.AddressID,
Content: vault.Content,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
ContentKeyRotation: 1,
CreateTime: 0,
ExpireTime: 0,
NewUserInvitesReady: 0,
Owner: true,
PendingInvites: 0,
Permission: 1,
Primary: false,
Shared: false,
ShareID: `shareId-${Math.random()}`,
TargetID: `targetId-${Math.random()}`,
TargetMaxMembers: 2,
TargetMembers: 0,
TargetType: ShareType.Vault,
VaultID: `vaultId-${Math.random()}`,
};
const share = await PassCrypto.openShare({ encryptedShare, shareKeys: [shareKey] });
const shareManager = PassCrypto.getShareManager(encryptedShare.ShareID);
expect(share!.content).toEqual(content);
expect(PassCrypto.getShareManager(encryptedShare.ShareID)).toBeDefined();
expect(shareManager.getShare()).toStrictEqual(share);
expect(shareManager.hasVaultKey(1)).toBe(true);
/* simulate new vault keys being added */
const encryptedShareUpdate: ShareGetResponse = {
...encryptedShare,
ContentKeyRotation: 2,
};
const newShareKey: ShareKeyResponse = {
Key: vault.EncryptedVaultKey,
KeyRotation: 2,
CreateTime: 0,
UserKeyID: TEST_USER_KEY_ID,
};
jest.spyOn(shareManager, 'addVaultKey');
const shareUpdate = await PassCrypto.openShare({
encryptedShare: encryptedShareUpdate,
shareKeys: [shareKey, newShareKey],
});
expect(shareManager.getShare()).toStrictEqual(shareUpdate);
expect(shareManager.hasVaultKey(1)).toBe(true);
expect(shareManager.hasVaultKey(2)).toBe(true);
});
test('should throw if share keys list is empty', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
const content = randomContents();
const vault = await PassCrypto.createVault(content);
const encryptedShare: ShareGetResponse = {
AddressID: vault.AddressID,
Content: vault.Content,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
ContentKeyRotation: 2,
CreateTime: 0,
ExpireTime: 0,
NewUserInvitesReady: 0,
Owner: true,
PendingInvites: 0,
Permission: 1,
Primary: false,
Shared: false,
ShareID: `shareId-${Math.random()}`,
TargetID: `targetId-${Math.random()}`,
TargetMaxMembers: 2,
TargetMembers: 0,
TargetType: ShareType.Vault,
VaultID: `vaultId-${Math.random()}`,
};
await expect(PassCrypto.openShare({ encryptedShare, shareKeys: [] })).rejects.toThrow(
new PassCryptoShareError(`Empty share keys`)
);
});
test('should throw if there are no share keys for current share rotation', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
const content = randomContents();
const vault = await PassCrypto.createVault(content);
const shareKey: ShareKeyResponse = {
Key: vault.EncryptedVaultKey,
KeyRotation: 1,
CreateTime: 0,
UserKeyID: TEST_USER_KEY_ID,
};
const encryptedShare: ShareGetResponse = {
AddressID: vault.AddressID,
Content: vault.Content,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
ContentKeyRotation: 2,
CreateTime: 0,
ExpireTime: 0,
NewUserInvitesReady: 0,
Owner: true,
PendingInvites: 0,
Permission: 1,
Primary: false,
Shared: false,
ShareID: `shareId-${Math.random()}`,
TargetID: `targetId-${Math.random()}`,
TargetMaxMembers: 2,
TargetMembers: 0,
TargetType: ShareType.Vault,
VaultID: `vaultId-${Math.random()}`,
};
await expect(PassCrypto.openShare({ encryptedShare, shareKeys: [shareKey] })).rejects.toThrow(
new PassCryptoShareError(`Missing vault key for rotation 2`)
);
});
test('should return null if no user key can decrypt current share', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
const content = randomContents();
const vault = await PassCrypto.createVault(content);
const shareKey: ShareKeyResponse = {
Key: vault.EncryptedVaultKey,
KeyRotation: 1,
CreateTime: 0,
UserKeyID: `${TEST_USER_KEY_ID}-inactive`,
};
const encryptedShare: ShareGetResponse = {
AddressID: vault.AddressID,
Content: vault.Content,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
ContentKeyRotation: 1,
CreateTime: 0,
ExpireTime: 0,
NewUserInvitesReady: 0,
Owner: true,
PendingInvites: 0,
Permission: 1,
Primary: false,
Shared: false,
ShareID: `shareId-${Math.random()}`,
TargetID: `targetId-${Math.random()}`,
TargetMaxMembers: 2,
TargetMembers: 0,
TargetType: ShareType.Vault,
VaultID: `vaultId-${Math.random()}`,
};
expect(await PassCrypto.openShare({ encryptedShare, shareKeys: [shareKey] })).toEqual(null);
});
});
describe('PassCrypto::updateShare', () => {
afterEach(() => PassCrypto.clear());
test('should throw if PassCrypto not hydrated', async () => {
await expect(PassCrypto.openShare({} as any)).rejects.toThrow(PassCryptoNotHydratedError);
});
test('should register only new vaults keys on shareManager', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
const [encryptedShare, shareKey] = await createRandomShareResponses(userKey, address.ID);
const shareId = encryptedShare.ShareID;
await PassCrypto.openShare({ encryptedShare, shareKeys: [shareKey] });
const shareManager = PassCrypto.getShareManager(encryptedShare.ShareID);
jest.spyOn(shareManager, 'addVaultKey');
const content = randomContents();
const vault = await processes.createVault({ content, userKey, addressId: address.ID });
const newShareKey: ShareKeyResponse = {
Key: vault.EncryptedVaultKey,
KeyRotation: 2,
CreateTime: 0,
UserKeyID: TEST_USER_KEY_ID,
};
await PassCrypto.updateShareKeys({ shareId, shareKeys: [shareKey] });
expect(shareManager.addVaultKey).toHaveBeenCalledTimes(0);
await PassCrypto.updateShareKeys({ shareId, shareKeys: [shareKey, newShareKey] });
expect(shareManager.addVaultKey).toHaveBeenCalledTimes(1);
});
});
describe('PassCrypto::openItem', () => {
afterEach(() => PassCrypto.clear());
test('should throw if PassCrypto not hydrated', async () => {
await expect(PassCrypto.openItem({} as any)).rejects.toThrow(PassCryptoNotHydratedError);
});
test('should throw if vault share has not been registered yet', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
const encryptedItem: ItemRevisionContentsResponse = {
ItemID: `itemId-${Math.random()}`,
Revision: 1,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
KeyRotation: 1,
Content: 'base64encoded',
ItemKey: 'base64encoded',
State: ItemState.Active,
CreateTime: 0,
ModifyTime: 0,
RevisionTime: 0,
};
await expect(
PassCrypto.openItem({
shareId: 'somerandom',
encryptedItem,
})
).rejects.toThrow(PassCryptoShareError);
});
test('should decrypt item with shareManager vault key', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
const [encryptedShare, shareKey] = await createRandomShareResponses(userKey, address.ID);
await PassCrypto.openShare({ encryptedShare, shareKeys: [shareKey] });
const vaultKey = await processes.openVaultKey({ shareKey, userKeys: [userKey] });
/* create item */
const itemContent = randomContents();
const item = await processes.createItem({ content: itemContent, vaultKey });
const encryptedItem: ItemRevisionContentsResponse = {
ItemID: `itemId-${Math.random()}`,
Revision: 1,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
KeyRotation: 1,
Content: item.Content,
ItemKey: item.ItemKey,
State: ItemState.Active,
CreateTime: 0,
ModifyTime: 0,
RevisionTime: 0,
};
const openedItem = await PassCrypto.openItem({ shareId: encryptedShare.ShareID, encryptedItem });
expect(openedItem.itemId).toEqual(encryptedItem.ItemID);
expect(openedItem.content).toEqual(itemContent);
expect(openedItem.revision).toEqual(encryptedItem.Revision);
expect(openedItem.state).toEqual(encryptedItem.State);
});
});
describe('PassCrypto::moveItem', () => {
afterEach(() => PassCrypto.clear());
test('should throw if PassCrypto not hydrated', async () => {
await expect(PassCrypto.moveItem({} as any)).rejects.toThrow(PassCryptoNotHydratedError);
});
test('should re-encrypt item and create new item key with correct destination vault key', async () => {
await PassCrypto.hydrate({ user, addresses: [address], keyPassword: TEST_KEY_PASSWORD });
const content = randomContents();
const [targetShare, targetVaultKey] = await createRandomShareResponses(userKey, address.ID);
await PassCrypto.openShare({ encryptedShare: targetShare, shareKeys: [targetVaultKey] });
const { Item } = await PassCrypto.moveItem({ content, destinationShareId: targetShare.ShareID });
expect(Item.ContentFormatVersion).toEqual(CONTENT_FORMAT_VERSION);
expect(Item.KeyRotation).toEqual(targetVaultKey.KeyRotation);
const encryptedItem: ItemRevisionContentsResponse = {
ItemID: `itemId-${Math.random()}`,
Revision: 1,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
KeyRotation: 1,
Content: Item.Content,
ItemKey: Item.ItemKey,
State: ItemState.Active,
CreateTime: 0,
ModifyTime: 0,
RevisionTime: 0,
};
const movedItem = await PassCrypto.openItem({ shareId: targetShare.ShareID, encryptedItem });
expect(movedItem.content).toEqual(content);
});
});
});
| 7,753
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/pass-crypto.ts
|
import { CryptoProxy } from '@proton/crypto';
import { Api as CryptoApi } from '@proton/crypto/lib/worker/api';
import { authentication } from '@proton/pass/lib/auth/store';
import type {
PassCryptoManagerContext,
PassCryptoWorker,
SerializedCryptoContext,
ShareContext,
ShareGetResponse,
ShareKeyResponse,
ShareManager,
TypedOpenedShare,
} from '@proton/pass/types';
import { ShareType } from '@proton/pass/types';
import { unwrap } from '@proton/pass/utils/fp/promises';
import { logId, logger } from '@proton/pass/utils/logger';
import { entriesMap } from '@proton/pass/utils/object/map';
import { getDecryptedAddressKeysHelper, getDecryptedUserKeysHelper } from '@proton/shared/lib/keys';
import * as processes from './processes';
import { createShareManager } from './share-manager';
import { getSupportedAddresses } from './utils/addresses';
import {
PassCryptoError,
PassCryptoHydrationError,
PassCryptoNotHydratedError,
PassCryptoShareError,
isPassCryptoError,
} from './utils/errors';
function assertHydrated(ctx: PassCryptoManagerContext): asserts ctx is Required<PassCryptoManagerContext> {
if (
ctx.user === undefined ||
ctx.addresses === undefined ||
ctx.primaryAddress === undefined ||
ctx.userKeys === undefined ||
ctx.primaryUserKey === undefined
) {
throw new PassCryptoNotHydratedError('Pass crypto manager incorrectly hydrated');
}
}
const createPassCrypto = (): PassCryptoWorker => {
if (process.env.NODE_ENV !== 'test') {
CryptoApi.init();
CryptoProxy.setEndpoint(new CryptoApi(), (endpoint) => endpoint.clearKeyStore());
}
const context: PassCryptoManagerContext = {
user: undefined,
userKeys: [],
addresses: [],
primaryUserKey: undefined,
primaryAddress: undefined,
shareManagers: new Map(),
};
const hasShareManager = (shareId: string): boolean => context.shareManagers.has(shareId);
const getShareManager = (shareId: string): ShareManager => {
if (!hasShareManager(shareId)) throw new PassCryptoShareError(`Unknown shareId : cannot resolve share manager`);
return context.shareManagers.get(shareId)!;
};
const unregisterInactiveShares = () => {
context.shareManagers.forEach((shareManager, shareId) => {
if (!shareManager.isActive(context.userKeys)) {
logger.debug(`[PassCrypto::Worker] Unregistering share ${logId(shareId)} (inactive)`);
context.shareManagers.delete(shareId);
}
});
};
/* Resolves the decrypted address key reference */
const getPrimaryAddressKeyById = async (addressId: string) => {
assertHydrated(context);
const address = context.addresses.find((address) => address.ID === addressId);
if (address === undefined) throw new PassCryptoError(`Could not find address with ID ${logId(addressId)}`);
const [primaryAddressKey] = await getDecryptedAddressKeysHelper(
address.Keys,
context.user,
context.userKeys,
authentication.getPassword()
);
return primaryAddressKey;
};
const worker: PassCryptoWorker = {
getContext: () => context,
async hydrate({ user, addresses, keyPassword, snapshot }) {
logger.debug('[PassCrypto::Worker] Hydrating...');
try {
const userKeys = await getDecryptedUserKeysHelper(user, keyPassword);
const activeAddresses = addresses.filter(getSupportedAddresses);
if (userKeys.length === 0) throw new PassCryptoHydrationError('No user keys found');
if (activeAddresses.length === 0) throw new PassCryptoHydrationError('No active user addresses found');
context.user = user;
context.addresses = addresses;
context.primaryAddress = activeAddresses[0];
context.userKeys = userKeys;
context.primaryUserKey = userKeys[0];
if (snapshot) {
const entries = snapshot.shareManagers as [string, SerializedCryptoContext<ShareContext>][];
const shareManagers = await unwrap(entriesMap(entries)(createShareManager.fromSnapshot));
context.shareManagers = new Map(shareManagers);
logger.debug('[PassCrypto::Worker] Hydrated from snapshot');
}
} catch (e) {
logger.warn('[PassCrypto::Worker] hydration failed', e);
throw new PassCryptoHydrationError('Hydration failure');
}
unregisterInactiveShares();
},
clear() {
context.user = undefined;
context.userKeys = [];
context.addresses = [];
context.primaryAddress = undefined;
context.primaryUserKey = undefined;
context.shareManagers = new Map();
},
getShareManager,
/* Creating a vault does not register a share manager :
* call PassCrypto::openShare to register it */
async createVault(content) {
assertHydrated(context);
return processes.createVault({
content,
userKey: context.primaryUserKey,
addressId: context.primaryAddress.ID,
});
},
/* Updating a vault does not register a share manager :
* call PassCrypto::openShare to register it.
*
* ⚠️ Key rotation : We're assuming the shareManager will
* always hold the latest rotation keys - In order to future
* -proof this, each vault update should be preceded by a
* call to retrieve the latest shareKeys */
async updateVault({ shareId, content }) {
assertHydrated(context);
const shareManager = getShareManager(shareId);
const latestRotation = shareManager.getLatestRotation();
const vaultKey = shareManager.getVaultKey(latestRotation);
return processes.updateVault({ vaultKey, content });
},
canOpenShare(shareId) {
try {
return worker.getShareManager(shareId).isActive(context.userKeys);
} catch (_) {
return false;
}
},
/* Opening a new share has the side-effect of registering a
* shareManager for this share. When opening a pre-registered
* share (most likely hydrated from a snapshot) - filter the
* vault keys to only open those we haven't already processed.
* This can happen during a vault share content update or during
* a full data sync. */
openShare: async <T extends ShareType = ShareType>(data: {
encryptedShare: ShareGetResponse;
shareKeys: ShareKeyResponse[];
}) => {
assertHydrated(context);
try {
const { encryptedShare, shareKeys } = data;
if (shareKeys.length === 0) throw new PassCryptoShareError('Empty share keys');
/* before processing the current encryptedShare - ensure the
* latest rotation key can be decrypted with an active userKey */
const latestKey = shareKeys.reduce((acc, curr) => (curr.KeyRotation > acc.KeyRotation ? curr : acc));
const canOpenShare = context.userKeys.some(({ ID }) => ID === latestKey.UserKeyID);
if (!canOpenShare) return null;
const shareId = encryptedShare.ShareID;
const maybeShareManager = hasShareManager(shareId) ? getShareManager(shareId) : undefined;
const share = await (async () => {
switch (encryptedShare.TargetType) {
case ShareType.Vault: {
const vaultKeys = await Promise.all(
shareKeys.map((shareKey) =>
maybeShareManager?.hasVaultKey(shareKey.KeyRotation)
? maybeShareManager.getVaultKey(shareKey.KeyRotation)
: processes.openVaultKey({ shareKey, userKeys: context.userKeys })
)
);
const rotation = encryptedShare.ContentKeyRotation!;
const vaultKey = vaultKeys.find((key) => key.rotation === rotation);
if (vaultKey === undefined) {
throw new PassCryptoShareError(`Missing vault key for rotation ${rotation}`);
}
return processes.openShare({ type: ShareType.Vault, encryptedShare, vaultKey });
}
case ShareType.Item:
return processes.openShare({ type: ShareType.Item, encryptedShare });
default:
throw new PassCryptoShareError('Unsupported share type');
}
})();
const shareManager = maybeShareManager ?? createShareManager(share);
context.shareManagers.set(shareId, shareManager);
shareManager.setShare(share); /* handle update when recyling */
await worker.updateShareKeys({ shareId, shareKeys });
return shareManager.getShare() as TypedOpenedShare<T>;
} catch (err: any) {
throw isPassCryptoError(err) ? err : new PassCryptoError(err);
}
},
/* FIXME: add support for itemKeys when we
* support ItemShares */
async updateShareKeys({ shareId, shareKeys }) {
assertHydrated(context);
const shareManager = getShareManager(shareId);
const newVaultKeys = await Promise.all(
shareKeys
.filter(({ KeyRotation }) => !shareManager.hasVaultKey(KeyRotation))
.map((shareKey) => processes.openVaultKey({ shareKey, userKeys: context.userKeys }))
);
newVaultKeys.forEach((vaultKey) => shareManager.addVaultKey(vaultKey));
},
removeShare: (shareId) => context.shareManagers.delete(shareId),
/* Resolve the latest rotation for this share
* and use the vault key for that rotation */
async createItem({ shareId, content }) {
assertHydrated(context);
const shareManager = getShareManager(shareId);
const latestRotation = shareManager.getLatestRotation();
const vaultKey = shareManager.getVaultKey(latestRotation);
return processes.createItem({ content, vaultKey });
},
async openItem({ shareId, encryptedItem }) {
assertHydrated(context);
const shareManager = getShareManager(shareId);
const vaultKey = shareManager.getVaultKey(encryptedItem.KeyRotation!);
return processes.openItem({ encryptedItem, vaultKey });
},
/* We're assuming that every call to PassCrypto::updateItem will
* be preceded by a request to resolve the latest encrypted item
* key for future-proofing */
async updateItem({ shareId, content, latestItemKey, lastRevision }) {
assertHydrated(context);
const shareManager = getShareManager(shareId);
const vaultKey = shareManager.getVaultKey(latestItemKey.KeyRotation);
const itemKey = await processes.openItemKey({ encryptedItemKey: latestItemKey, vaultKey });
return processes.updateItem({ itemKey, content, lastRevision });
},
async moveItem({ destinationShareId, content }) {
assertHydrated(context);
const shareManager = getShareManager(destinationShareId);
const latestRotation = shareManager.getLatestRotation();
const destinationVaultKey = shareManager.getVaultKey(latestRotation);
return processes.moveItem({ destinationShareId, destinationVaultKey, content });
},
async createVaultInvite({ shareId, invitedPublicKey, email, role }) {
assertHydrated(context);
const shareManager = getShareManager(shareId);
const share = shareManager.getShare();
const inviteKeys = await processes.createInviteKeys({
targetKeys: shareManager.getVaultKeys(),
invitedPublicKey: await CryptoProxy.importPublicKey({ armoredKey: invitedPublicKey }),
inviterPrivateKey: (await getPrimaryAddressKeyById(share.addressId)).privateKey,
});
return { Keys: inviteKeys, Email: email, ShareRoleID: role, TargetType: ShareType.Vault };
},
async createNewUserVaultInvite({ shareId, email, role }) {
assertHydrated(context);
const shareManager = getShareManager(shareId);
const share = shareManager.getShare();
const signature = await processes.createNewUserSignature({
inviterPrivateKey: (await getPrimaryAddressKeyById(share.addressId)).privateKey,
invitedEmail: email,
vaultKey: shareManager.getVaultKey(shareManager.getLatestRotation()),
});
return {
Email: email,
ShareRoleID: role,
Signature: signature,
TargetType: ShareType.Vault,
};
},
async promoteInvite({ shareId, invitedPublicKey }) {
assertHydrated(context);
const shareManager = getShareManager(shareId);
const share = shareManager.getShare();
const inviteKeys = await processes.createInviteKeys({
targetKeys: shareManager.getVaultKeys(),
invitedPublicKey: await CryptoProxy.importPublicKey({ armoredKey: invitedPublicKey }),
inviterPrivateKey: (await getPrimaryAddressKeyById(share.addressId)).privateKey,
});
return { Keys: inviteKeys };
},
async acceptVaultInvite({ inviteKeys, invitedAddressId, inviterPublicKeys }) {
assertHydrated(context);
const vaultKeys = await processes.reencryptInviteKeys({
userKey: context.primaryUserKey,
inviteKeys,
invitedPrivateKey: (await getPrimaryAddressKeyById(invitedAddressId)).privateKey,
inviterPublicKeys: await Promise.all(
inviterPublicKeys.map((armoredKey) => CryptoProxy.importPublicKey({ armoredKey }))
),
});
return { Keys: vaultKeys };
},
async readVaultInvite({ inviteKey, invitedAddressId, encryptedVaultContent, inviterPublicKeys }) {
assertHydrated(context);
return processes.readVaultInviteContent({
inviteKey,
encryptedVaultContent,
invitedPrivateKey: (await getPrimaryAddressKeyById(invitedAddressId)).privateKey,
inviterPublicKeys: await Promise.all(
inviterPublicKeys.map((armoredKey) => CryptoProxy.importPublicKey({ armoredKey }))
),
});
},
serialize: () => ({
shareManagers: [...context.shareManagers.entries()].map(([shareId, shareManager]) => [
shareId,
shareManager.serialize(),
]),
}),
};
return worker;
};
export const PassCrypto = createPassCrypto();
| 7,754
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/share-manager.spec.ts
|
import type { VaultKey } from '@proton/pass/types';
import { ShareType } from '@proton/pass/types';
import { createShareManager } from './share-manager';
import { generateKey, getSymmetricKey } from './utils/crypto-helpers';
import { PassCryptoShareError, PassCryptoVaultError } from './utils/errors';
import { TEST_USER_KEY_ID, createRandomShare } from './utils/testing';
describe('ShareManager', () => {
test('createShareManager should init manager with share', () => {
const share = createRandomShare(ShareType.Vault);
const shareManager = createShareManager(share);
expect(shareManager.getShare()).toStrictEqual(share);
});
test('ShareManager::getLatestRotation should throw if no rotation set', () => {
const share = createRandomShare(ShareType.Vault);
const shareManager = createShareManager(share);
expect(shareManager.getLatestRotation).toThrow(PassCryptoShareError);
});
test('ShareManager::setLatestRotation should set the latest rotation', () => {
const share = createRandomShare(ShareType.Vault);
const shareManager = createShareManager(share);
shareManager.setLatestRotation(42);
expect(shareManager.getLatestRotation()).toStrictEqual(42);
});
test('ShareManager::hasVaultKey should account for share type and rotation', async () => {
const key = generateKey();
const vaultKey: VaultKey = {
raw: key,
key: await getSymmetricKey(key),
rotation: 1,
userKeyId: TEST_USER_KEY_ID,
};
const itemShare = createRandomShare(ShareType.Item);
const itemShareManager = createShareManager(itemShare);
expect(itemShareManager.hasVaultKey(1)).toEqual(false);
const vaultShare = createRandomShare(ShareType.Vault);
const vaultShareManager = createShareManager(vaultShare);
vaultShareManager.addVaultKey(vaultKey);
expect(vaultShareManager.hasVaultKey(1)).toEqual(true);
expect(vaultShareManager.hasVaultKey(2)).toEqual(false);
});
test('ShareManager::getVaultKey should throw on ItemShare', async () => {
const itemShare = createRandomShare(ShareType.Item);
const shareManager = createShareManager(itemShare);
expect(() => shareManager.getVaultKey(1)).toThrow(PassCryptoVaultError);
});
test('ShareManager::getVaultKey should throw if no key for rotation found', () => {
const vaultShare = createRandomShare(ShareType.Vault);
const shareManager = createShareManager(vaultShare);
expect(() => shareManager.getVaultKey(1)).toThrow(PassCryptoVaultError);
});
test('ShareManager::addVaultKey should throw on ItemShare', async () => {
const key = generateKey();
const vaultKey: VaultKey = {
raw: key,
key: await getSymmetricKey(key),
rotation: 1,
userKeyId: TEST_USER_KEY_ID,
};
const share = createRandomShare(ShareType.Item);
const shareManager = createShareManager(share);
expect(() => shareManager.addVaultKey(vaultKey)).toThrow(PassCryptoVaultError);
});
test('ShareManager::addVaultKey should add vault key to share context & update latest rotation', async () => {
const key = generateKey();
const vaultKey: VaultKey = {
raw: key,
key: await getSymmetricKey(key),
rotation: 42,
userKeyId: TEST_USER_KEY_ID,
};
const share = createRandomShare(ShareType.Vault);
const shareManager = createShareManager(share);
expect(() => shareManager.addVaultKey(vaultKey)).not.toThrow();
expect(shareManager.getVaultKey(42)).toStrictEqual(vaultKey);
expect(shareManager.getLatestRotation()).toEqual(42);
});
test('ShareManager::serialize result should allow re-hydrating instance', async () => {
const vaultKeys: VaultKey[] = await Promise.all(
Array.from({ length: 3 }, async (_, i) => {
const key = generateKey();
return {
raw: key,
key: await getSymmetricKey(key),
rotation: i + 1,
userKeyId: TEST_USER_KEY_ID,
};
})
);
const share = createRandomShare(ShareType.Vault);
const shareManager = createShareManager(share);
vaultKeys.forEach((vaultKey) => shareManager.addVaultKey(vaultKey));
const dump = shareManager.serialize();
const rehydratedManager = await createShareManager.fromSnapshot(dump);
expect(rehydratedManager.getShare()).toStrictEqual(share);
expect(rehydratedManager.getLatestRotation()).toEqual(3);
vaultKeys.forEach((vaultKey) =>
expect(rehydratedManager.getVaultKey(vaultKey.rotation)).toStrictEqual(vaultKey)
);
});
});
| 7,755
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/share-manager.ts
|
import type {
OpenedShare,
Rotation,
SerializedCryptoContext,
ShareContext,
ShareManager,
TypedOpenedShare,
VaultKey,
} from '@proton/pass/types';
import { ShareType } from '@proton/pass/types';
import { base64StringToUint8Array, uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { getSymmetricKey } from './utils/crypto-helpers';
import { PassCryptoShareError, PassCryptoVaultError } from './utils/errors';
export const createShareManager = <T extends ShareType = ShareType>(
share: TypedOpenedShare<T>,
context?: ShareContext
): ShareManager<T> => {
const shareContext: ShareContext = context ?? {
share,
latestRotation: -1,
vaultKeys: new Map(),
itemKeys: new Map(),
};
const shareManager: ShareManager<T> = {
getShare: () => shareContext.share as TypedOpenedShare<T>,
setShare: (share) => (shareContext.share = share),
setLatestRotation: (rotation) => (shareContext.latestRotation = rotation),
getLatestRotation() {
if (shareContext.latestRotation === -1) {
throw new PassCryptoShareError(`Share has not been hydrated`);
}
return shareContext.latestRotation;
},
hasVaultKey: (rotation) =>
shareManager.getShare().targetType === ShareType.Vault && shareContext.vaultKeys.has(rotation),
getVaultKey(rotation) {
if (shareManager.getShare().targetType !== ShareType.Vault) {
throw new PassCryptoVaultError(`Cannot resolve vault keys for non-vault share`);
}
if (!shareManager.hasVaultKey(rotation)) {
throw new PassCryptoVaultError(`Cannot find vault key for rotation ${rotation}`);
}
return shareContext.vaultKeys.get(rotation)!;
},
getVaultKeys: () => Array.from(shareContext.vaultKeys.values()),
addVaultKey(vaultKey) {
if (shareManager.getShare().targetType !== ShareType.Vault) {
throw new PassCryptoVaultError(`Cannot add vault key to non-vault share`);
}
const rotation = vaultKey.rotation;
shareContext.vaultKeys.set(rotation, vaultKey);
if (rotation > shareContext.latestRotation) {
shareManager.setLatestRotation(rotation);
}
},
/* a share is considered `active` if its latest rotation key
* was encrypted with an active user key - if the user key is
* inactive, then share should be ignored until it becomes
* active again */
isActive(userKeys = []) {
try {
const { targetType } = shareManager.getShare();
const latestRotation = shareManager.getLatestRotation();
if (targetType === ShareType.Vault) {
const vaultKey = shareManager.getVaultKey(latestRotation);
return userKeys.some(({ ID }) => ID === vaultKey.userKeyId);
}
return false;
} catch (_) {
return false;
}
},
serialize: () => ({
...shareContext,
share: (() => {
switch (shareContext.share.targetType) {
case ShareType.Vault: {
return {
...shareContext.share,
content: uint8ArrayToBase64String(shareContext.share.content),
};
}
case ShareType.Item:
return shareContext.share;
}
})(),
vaultKeys: [...shareContext.vaultKeys.entries()].map(([rotation, vaultKey]) => [
rotation,
{
rotation: vaultKey.rotation,
raw: uint8ArrayToBase64String(vaultKey.raw),
userKeyId: vaultKey.userKeyId,
},
]),
itemKeys: [],
}),
};
return shareManager as ShareManager<T>;
};
createShareManager.fromSnapshot = async (snapshot: SerializedCryptoContext<ShareContext>): Promise<ShareManager> => {
/**
* Item shares do not have a content property
* Only encode the vault content when dealing
* with VaultShares
*/
const share: OpenedShare = (() => {
switch (snapshot.share.targetType) {
case ShareType.Vault: {
return { ...snapshot.share, content: base64StringToUint8Array(snapshot.share.content) };
}
case ShareType.Item: {
return snapshot.share;
}
}
})();
const vaultKeys: [Rotation, VaultKey][] = await Promise.all(
snapshot.vaultKeys.map(async ([rotation, vaultKey]) => {
const rawKey = base64StringToUint8Array(vaultKey.raw);
return [
rotation,
{
rotation: vaultKey.rotation,
raw: rawKey,
key: await getSymmetricKey(rawKey),
userKeyId: vaultKey.userKeyId,
},
];
})
);
return createShareManager(share, {
...snapshot,
share,
vaultKeys: new Map(vaultKeys),
itemKeys: new Map(),
});
};
| 7,756
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/index.ts
|
export * from './invite/create-invite-keys';
export * from './invite/create-new-user-signature';
export * from './invite/open-invite-key';
export * from './invite/read-vault-invite';
export * from './invite/reencrypt-invite-keys';
export * from './item/create-item';
export * from './item/move-item';
export * from './item/open-item';
export * from './item/open-item-key';
export * from './item/update-item';
export * from './share/open-share';
export * from './vault/create-vault';
export * from './vault/open-vault-key';
export * from './vault/update-vault';
| 7,757
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/create-invite-keys.spec.ts
|
import { CryptoProxy, VERIFICATION_STATUS } from '@proton/crypto';
import { PassSignatureContext } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import {
createRandomKey,
createRandomVaultKey,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../utils/testing';
import { createInviteKeys } from './create-invite-keys';
describe('create invite keys crypto process', () => {
beforeAll(async () => setupCryptoProxyForTesting());
afterAll(async () => releaseCryptoProxy());
test('should re-encrypt & sign all vaultKeys', async () => {
const vaultKeys = await Promise.all(
Array.from({ length: 4 }).map((_, rotation) => createRandomVaultKey(rotation))
);
const invitedKey = await createRandomKey();
const inviterKey = await createRandomKey();
const inviteKeys = await createInviteKeys({
targetKeys: vaultKeys,
invitedPublicKey: invitedKey.publicKey,
inviterPrivateKey: inviterKey.privateKey,
});
const decryptedKeys = await Promise.all(
inviteKeys.map(async (vaultKey) => {
const binaryMessage = base64StringToUint8Array(vaultKey.Key);
return CryptoProxy.decryptMessage({
binaryMessage,
decryptionKeys: invitedKey.privateKey,
verificationKeys: inviterKey.publicKey,
format: 'binary',
context: {
value: PassSignatureContext.VaultInviteExistingUser,
required: true,
},
});
})
);
decryptedKeys.forEach(({ verified }) => expect(verified).toEqual(VERIFICATION_STATUS.SIGNED_AND_VALID));
decryptedKeys.forEach(({ data }, i) => expect(data).toStrictEqual(vaultKeys[i].raw));
});
});
| 7,758
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/create-invite-keys.ts
|
import type { PrivateKeyReference, PublicKeyReference } from '@proton/crypto';
import { CryptoProxy } from '@proton/crypto';
import { type ItemKey, type KeyRotationKeyPair, PassSignatureContext, type VaultKey } from '@proton/pass/types';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
type CreateInviteKeysProcessParams = {
targetKeys: (VaultKey | ItemKey)[];
invitedPublicKey: PublicKeyReference;
inviterPrivateKey: PrivateKeyReference;
};
export const createInviteKeys = async ({
targetKeys,
invitedPublicKey,
inviterPrivateKey,
}: CreateInviteKeysProcessParams): Promise<KeyRotationKeyPair[]> => {
return Promise.all(
targetKeys.map(
async ({ raw: binaryData, rotation: KeyRotation }): Promise<KeyRotationKeyPair> => ({
Key: uint8ArrayToBase64String(
(
await CryptoProxy.encryptMessage({
binaryData,
encryptionKeys: [invitedPublicKey],
signingKeys: [inviterPrivateKey],
format: 'binary',
context: {
value: PassSignatureContext.VaultInviteExistingUser,
critical: true,
},
})
).message
),
KeyRotation,
})
)
);
};
| 7,759
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/create-new-user-signature.spec.ts
|
import { CryptoProxy, VERIFICATION_STATUS } from '@proton/crypto/lib';
import { PassSignatureContext } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import {
createRandomKey,
createRandomVaultKey,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../utils/testing';
import { createNewUserSignature, createNewUserSignatureBody } from './create-new-user-signature';
describe('create new user invite signature', () => {
beforeAll(async () => setupCryptoProxyForTesting());
afterAll(async () => releaseCryptoProxy());
test('should create valid detached signature payload', async () => {
const vaultKey = await createRandomVaultKey(0);
const addressKey = await createRandomKey();
const invitedEmail = 'test@proton.me';
const signature = await createNewUserSignature({
invitedEmail,
inviterPrivateKey: addressKey.privateKey,
vaultKey,
});
const { verified } = await CryptoProxy.verifyMessage({
binaryData: createNewUserSignatureBody({ invitedEmail, vaultKey }),
binarySignature: base64StringToUint8Array(signature),
verificationKeys: [addressKey.publicKey],
context: {
value: PassSignatureContext.VaultInviteNewUser,
required: true,
},
});
expect(verified).toEqual(VERIFICATION_STATUS.SIGNED_AND_VALID);
});
});
| 7,760
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/create-new-user-signature.ts
|
import { CryptoProxy, type PrivateKeyReference } from '@proton/crypto/lib';
import { PassSignatureContext, type VaultKey } from '@proton/pass/types';
import { stringToUint8Array, uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
type CreateNewUserSignatureProcessParams = {
invitedEmail: string;
inviterPrivateKey: PrivateKeyReference;
vaultKey: VaultKey;
};
type CreateNewUserSignatureBodyProcessParams = Omit<CreateNewUserSignatureProcessParams, 'inviterPrivateKey'>;
/* FIXME: use common rust library once integrated for generating
* the signature body payload */
export const createNewUserSignatureBody = ({
invitedEmail,
vaultKey,
}: CreateNewUserSignatureBodyProcessParams): Uint8Array => {
const bEmail = stringToUint8Array(invitedEmail);
const bSeperator = stringToUint8Array('|');
const bVaultKey = vaultKey.raw;
const binaryData = new Uint8Array(bEmail.length + bSeperator.length + bVaultKey.length);
binaryData.set(bEmail, 0);
binaryData.set(bSeperator, bEmail.length);
binaryData.set(bVaultKey, bEmail.length + bSeperator.length);
return binaryData;
};
export const createNewUserSignature = async (params: CreateNewUserSignatureProcessParams): Promise<string> => {
const signature = await CryptoProxy.signMessage({
binaryData: createNewUserSignatureBody(params),
signingKeys: [params.inviterPrivateKey],
format: 'binary',
detached: true,
context: {
value: PassSignatureContext.VaultInviteNewUser,
critical: true,
},
});
return uint8ArrayToBase64String(signature);
};
| 7,761
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/open-invite-key.spec.ts
|
import {
createRandomKey,
createRandomVaultKey,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../utils/testing';
import { createInviteKeys } from './create-invite-keys';
import { openInviteKey } from './open-invite-key';
describe('open invite keys', () => {
beforeAll(async () => setupCryptoProxyForTesting());
afterAll(async () => releaseCryptoProxy());
test('should decrypt target keys correctly', async () => {
const vaultKey = await createRandomVaultKey(0);
const invitedKey = await createRandomKey();
const inviterKeys = await Promise.all(Array.from({ length: 4 }).map(() => createRandomKey()));
const [inviteKey] = await createInviteKeys({
targetKeys: [vaultKey],
invitedPublicKey: invitedKey.publicKey,
inviterPrivateKey: inviterKeys[2].privateKey,
});
const openedInviteKeys = await openInviteKey({
inviteKey,
invitedPrivateKey: invitedKey.privateKey,
inviterPublicKeys: inviterKeys.map((key) => key.publicKey),
});
expect(openedInviteKeys).toStrictEqual(vaultKey.raw);
});
});
| 7,762
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/open-invite-key.ts
|
import type { PrivateKeyReference, PublicKeyReference } from '@proton/crypto';
import { CryptoProxy } from '@proton/crypto';
import type { KeyRotationKeyPair } from '@proton/pass/types';
import { PassSignatureContext } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
type OpenInviteKeyProcessParams = {
inviteKey: KeyRotationKeyPair;
invitedPrivateKey: PrivateKeyReference;
inviterPublicKeys: PublicKeyReference[];
};
export const openInviteKey = async ({
inviteKey,
invitedPrivateKey,
inviterPublicKeys,
}: OpenInviteKeyProcessParams): Promise<Uint8Array> =>
(
await CryptoProxy.decryptMessage({
binaryMessage: base64StringToUint8Array(inviteKey.Key),
decryptionKeys: invitedPrivateKey,
verificationKeys: inviterPublicKeys,
format: 'binary',
context: {
value: PassSignatureContext.VaultInviteExistingUser,
required: true,
},
})
).data;
| 7,763
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/read-vault-invite.spec.ts
|
import { encryptData } from '@proton/pass/lib/crypto/utils/crypto-helpers';
import {
createRandomKey,
createRandomVaultKey,
randomContents,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '@proton/pass/lib/crypto/utils/testing';
import { PassEncryptionTag } from '@proton/pass/types';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { createInviteKeys } from './create-invite-keys';
import { readVaultInviteContent } from './read-vault-invite';
describe('read vault invite content', () => {
beforeAll(async () => setupCryptoProxyForTesting());
afterAll(async () => releaseCryptoProxy());
test('should decrypt encrypted vault content correctly', async () => {
const invitedKey = await createRandomKey();
const inviterKeys = await Promise.all(Array.from({ length: 4 }).map(() => createRandomKey()));
const vaultKey = await createRandomVaultKey(0);
const vaultContent = randomContents();
const encryptedVaultContent = await encryptData(vaultKey.key, vaultContent, PassEncryptionTag.VaultContent);
const [inviteKey] = await createInviteKeys({
targetKeys: [vaultKey],
invitedPublicKey: invitedKey.publicKey,
inviterPrivateKey: inviterKeys[0].privateKey,
});
const decryptedVaultContent = await readVaultInviteContent({
inviteKey,
encryptedVaultContent: uint8ArrayToBase64String(encryptedVaultContent),
invitedPrivateKey: invitedKey.privateKey,
inviterPublicKeys: inviterKeys.map((key) => key.publicKey),
});
expect(decryptedVaultContent).toStrictEqual(vaultContent);
});
});
| 7,764
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/read-vault-invite.ts
|
import type { PrivateKeyReference, PublicKeyReference } from '@proton/crypto';
import { type KeyRotationKeyPair, PassEncryptionTag } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { decryptData, getSymmetricKey } from '../../utils/crypto-helpers';
import { openInviteKey } from './open-invite-key';
type ReadVaultInviteContentProcessParams = {
inviteKey: KeyRotationKeyPair;
encryptedVaultContent: string;
invitedPrivateKey: PrivateKeyReference;
inviterPublicKeys: PublicKeyReference[];
};
export const readVaultInviteContent = async ({
inviteKey,
encryptedVaultContent,
invitedPrivateKey,
inviterPublicKeys,
}: ReadVaultInviteContentProcessParams): Promise<Uint8Array> => {
const openedVaultKey = await openInviteKey({ inviteKey, invitedPrivateKey, inviterPublicKeys });
const vaultKey = await getSymmetricKey(openedVaultKey);
return decryptData(vaultKey, base64StringToUint8Array(encryptedVaultContent), PassEncryptionTag.VaultContent);
};
| 7,765
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/reencrypt-invite-keys.spec.ts
|
import { CryptoProxy, VERIFICATION_STATUS } from '@proton/crypto';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import {
createRandomKey,
createRandomVaultKey,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../utils/testing';
import { createInviteKeys } from './create-invite-keys';
import { reencryptInviteKeys } from './reencrypt-invite-keys';
describe('acceptVaultInvite crypto process', () => {
beforeAll(async () => setupCryptoProxyForTesting());
afterAll(async () => releaseCryptoProxy());
test('should decrypt, re-encrypt & sign all vaultKeys with userKey', async () => {
const vaultKeys = await Promise.all(
Array.from({ length: 4 }).map((_, rotation) => createRandomVaultKey(rotation))
);
const userKey = await createRandomKey();
const invitedKey = await createRandomKey();
const inviterKeys = await Promise.all(Array.from({ length: 4 }).map(() => createRandomKey()));
const inviteKeys = await createInviteKeys({
targetKeys: vaultKeys,
invitedPublicKey: invitedKey.publicKey,
inviterPrivateKey: inviterKeys[2].privateKey,
});
const reencryptedKeys = await reencryptInviteKeys({
inviteKeys,
invitedPrivateKey: invitedKey.privateKey,
inviterPublicKeys: inviterKeys.map((key) => key.privateKey),
userKey: userKey,
});
const decryptedKeys = await Promise.all(
reencryptedKeys.map(async (vaultKey) => {
const binaryMessage = base64StringToUint8Array(vaultKey.Key);
return CryptoProxy.decryptMessage({
binaryMessage,
decryptionKeys: userKey.privateKey,
verificationKeys: userKey.privateKey,
format: 'binary',
});
})
);
decryptedKeys.forEach(({ verified }) => expect(verified).toEqual(VERIFICATION_STATUS.SIGNED_AND_VALID));
decryptedKeys.forEach(({ data }, i) => expect(data).toStrictEqual(vaultKeys[i].raw));
});
});
| 7,766
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/invite/reencrypt-invite-keys.ts
|
import type { PrivateKeyReference, PublicKeyReference } from '@proton/crypto';
import { CryptoProxy } from '@proton/crypto';
import type { KeyRotationKeyPair } from '@proton/pass/types';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import type { DecryptedKey } from '@proton/shared/lib/interfaces';
import { openInviteKey } from './open-invite-key';
type ReencryptInviteKeysProcessParams = {
inviteKeys: KeyRotationKeyPair[];
invitedPrivateKey: PrivateKeyReference;
inviterPublicKeys: PublicKeyReference[];
userKey: DecryptedKey;
};
export const reencryptInviteKeys = async ({
inviteKeys,
invitedPrivateKey,
inviterPublicKeys,
userKey,
}: ReencryptInviteKeysProcessParams): Promise<KeyRotationKeyPair[]> =>
Promise.all(
inviteKeys.map(async (inviteKey): Promise<KeyRotationKeyPair> => {
const vaultKey = await openInviteKey({ inviteKey, invitedPrivateKey, inviterPublicKeys });
const { message: encryptedVaultKey } = await CryptoProxy.encryptMessage({
binaryData: vaultKey,
encryptionKeys: userKey.privateKey,
signingKeys: userKey.privateKey,
format: 'binary',
});
return {
Key: uint8ArrayToBase64String(encryptedVaultKey),
KeyRotation: inviteKey.KeyRotation,
};
})
);
| 7,767
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/create-item.spec.ts
|
import type { VaultKey } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, PassEncryptionTag } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { decryptData, generateKey, getSymmetricKey } from '../../utils/crypto-helpers';
import { PassCryptoItemError } from '../../utils/errors';
import { TEST_USER_KEY_ID, randomContents } from '../../utils/testing';
import { createItem } from './create-item';
describe('createItem crypto process', () => {
const key = generateKey();
const content = randomContents();
test('should encrypt item content with item key and encrypt item key with vault key', async () => {
const vaultKey: VaultKey = {
raw: key,
key: await getSymmetricKey(key),
rotation: 1,
userKeyId: TEST_USER_KEY_ID,
};
const item = await createItem({ content, vaultKey });
const decryptedItemKey = await decryptData(
vaultKey.key,
base64StringToUint8Array(item.ItemKey),
PassEncryptionTag.ItemKey
);
const itemKey = await getSymmetricKey(decryptedItemKey);
const decryptedContent = await decryptData(
itemKey,
base64StringToUint8Array(item.Content),
PassEncryptionTag.ItemContent
);
expect(item.ContentFormatVersion).toEqual(CONTENT_FORMAT_VERSION);
expect(item.KeyRotation).toEqual(1);
expect(decryptedContent).toStrictEqual(content);
});
test('should throw when provided with empty content', async () => {
const vaultKey: VaultKey = {
raw: key,
key: await getSymmetricKey(key),
rotation: 1,
userKeyId: TEST_USER_KEY_ID,
};
await expect(createItem({ content: new Uint8Array(0), vaultKey })).rejects.toThrow(PassCryptoItemError);
});
test('should throw if base64 content is over MAX_ITEM_CONTENT_B64_LENGTH', async () => {
const vaultKey: VaultKey = {
raw: key,
key: await getSymmetricKey(key),
rotation: 1,
userKeyId: TEST_USER_KEY_ID,
};
await expect(createItem({ content: new Uint8Array(40000), vaultKey })).rejects.toThrow(PassCryptoItemError);
});
});
| 7,768
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/create-item.ts
|
import type { ItemCreateRequest, VaultKey } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, PassEncryptionTag } from '@proton/pass/types';
import { pipe } from '@proton/pass/utils/fp/pipe';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { encryptData, generateKey, getSymmetricKey } from '../../utils/crypto-helpers';
import { PassCryptoItemError } from '../../utils/errors';
import { validateItemContentSize } from '../../utils/validators';
type CreateItemProcessParams = {
content: Uint8Array;
vaultKey: VaultKey;
};
export const createItem = async ({ content, vaultKey }: CreateItemProcessParams): Promise<ItemCreateRequest> => {
if (content.length === 0) {
throw new PassCryptoItemError('Item content cannot be empty');
}
const key = generateKey();
const itemKey = await getSymmetricKey(key);
const encryptedItemContent = await encryptData(itemKey, content, PassEncryptionTag.ItemContent);
const encryptedItemKey = await encryptData(vaultKey.key, key, PassEncryptionTag.ItemKey);
return {
Content: pipe(uint8ArrayToBase64String, validateItemContentSize)(encryptedItemContent),
ContentFormatVersion: CONTENT_FORMAT_VERSION,
ItemKey: uint8ArrayToBase64String(encryptedItemKey),
KeyRotation: vaultKey.rotation,
};
};
| 7,769
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/move-item.spec.ts
|
import type { VaultKey } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, PassEncryptionTag } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { decryptData, generateKey, getSymmetricKey } from '../../utils/crypto-helpers';
import { PassCryptoItemError } from '../../utils/errors';
import { TEST_USER_KEY_ID, randomContents } from '../../utils/testing';
import { moveItem } from './move-item';
describe('moveItem crypto process', () => {
const key = generateKey();
const content = randomContents();
test('should re-encrypt item content with destination vault key', async () => {
const destinationShareId = `shareId-${Math.random()}`;
const destinationVaultKey: VaultKey = {
key: await getSymmetricKey(key),
raw: key,
rotation: 42,
userKeyId: TEST_USER_KEY_ID,
};
const movedItem = await moveItem({ content, destinationVaultKey, destinationShareId });
expect(movedItem.Item.ContentFormatVersion).toEqual(CONTENT_FORMAT_VERSION);
expect(movedItem.Item.KeyRotation).toEqual(destinationVaultKey.rotation);
const newItemKey = await decryptData(
destinationVaultKey.key,
base64StringToUint8Array(movedItem.Item.ItemKey),
PassEncryptionTag.ItemKey
);
const decryptedContent = await decryptData(
await getSymmetricKey(newItemKey),
base64StringToUint8Array(movedItem.Item.Content!),
PassEncryptionTag.ItemContent
);
expect(decryptedContent).toStrictEqual(content);
});
test('should throw when provided with empty content', async () => {
const vaultKey: VaultKey = {
key: await getSymmetricKey(key),
raw: key,
rotation: 42,
userKeyId: TEST_USER_KEY_ID,
};
await expect(
moveItem({
content: new Uint8Array(0),
destinationShareId: '',
destinationVaultKey: vaultKey,
})
).rejects.toThrow(PassCryptoItemError);
});
});
| 7,770
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/move-item.ts
|
import type { ItemMoveSingleToShareRequest, VaultKey } from '@proton/pass/types';
import { PassCryptoItemError } from '../../utils/errors';
import { createItem } from './create-item';
type MoveItemProcessParams = {
destinationShareId: string;
destinationVaultKey: VaultKey;
content: Uint8Array;
};
export const moveItem = async ({
destinationShareId,
destinationVaultKey,
content,
}: MoveItemProcessParams): Promise<ItemMoveSingleToShareRequest> => {
if (content.length === 0) {
throw new PassCryptoItemError('Item content cannot be empty');
}
return {
Item: await createItem({ vaultKey: destinationVaultKey, content }),
ShareID: destinationShareId,
};
};
| 7,771
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/open-item-key.spec.ts
|
import type { ItemKeyResponse, VaultKey } from '@proton/pass/types';
import { PassEncryptionTag } from '@proton/pass/types';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { encryptData, generateKey, getSymmetricKey } from '../../utils/crypto-helpers';
import { TEST_USER_KEY_ID } from '../../utils/testing';
import { openItemKey } from './open-item-key';
describe('openItemKey crypto process', () => {
const key = generateKey();
const itemKey = generateKey();
test('should decrypt item key accordingly', async () => {
const vaultKey: VaultKey = {
key: await getSymmetricKey(key),
raw: key,
rotation: 1,
userKeyId: TEST_USER_KEY_ID,
};
const encryptedItemKey: ItemKeyResponse = {
Key: uint8ArrayToBase64String(await encryptData(vaultKey.key, itemKey, PassEncryptionTag.ItemKey)),
KeyRotation: 42,
};
const decryptedItemKey = await openItemKey({ encryptedItemKey, vaultKey });
expect(decryptedItemKey.raw).toStrictEqual(itemKey);
expect(decryptedItemKey.rotation).toStrictEqual(42);
expect(decryptedItemKey.key).toBeDefined();
});
});
| 7,772
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/open-item-key.ts
|
import type { ItemKey, ItemKeyResponse, VaultKey } from '@proton/pass/types';
import { PassEncryptionTag } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { decryptData, getSymmetricKey } from '../../utils/crypto-helpers';
type OpenVaultKeyProcessParams = {
encryptedItemKey: ItemKeyResponse;
vaultKey: VaultKey;
};
export const openItemKey = async ({
encryptedItemKey: { Key, KeyRotation },
vaultKey,
}: OpenVaultKeyProcessParams): Promise<ItemKey> => {
const data = base64StringToUint8Array(Key);
const itemKey = await decryptData(vaultKey.key, data, PassEncryptionTag.ItemKey);
return {
raw: itemKey,
key: await getSymmetricKey(itemKey),
rotation: KeyRotation,
};
};
| 7,773
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/open-item.spec.ts
|
import type { ItemRevisionContentsResponse, VaultKey } from '@proton/pass/types';
import { ItemState } from '@proton/pass/types';
import { generateKey, getSymmetricKey } from '../../utils/crypto-helpers';
import { PassCryptoItemError } from '../../utils/errors';
import { TEST_USER_KEY_ID, randomContents } from '../../utils/testing';
import { createItem } from './create-item';
import { openItem } from './open-item';
describe('openItem crypto process', () => {
const key = generateKey();
const content = randomContents();
const timestamp = Math.floor(Date.now() / 1000);
const itemId = `itemId-${Math.random()}`;
test('should decrypt item accordingly', async () => {
const vaultKey: VaultKey = {
key: await getSymmetricKey(key),
raw: key,
rotation: 1,
userKeyId: TEST_USER_KEY_ID,
};
const createItemRequest = await createItem({ content, vaultKey });
const encryptedItem: ItemRevisionContentsResponse = {
ItemID: itemId,
Revision: 1,
KeyRotation: 1,
ContentFormatVersion: createItemRequest.ContentFormatVersion,
Content: createItemRequest.Content,
ItemKey: createItemRequest.ItemKey,
State: ItemState.Active,
CreateTime: timestamp,
ModifyTime: timestamp,
LastUseTime: timestamp,
RevisionTime: timestamp,
};
const item = await openItem({ encryptedItem, vaultKey });
expect(item.itemId).toEqual(itemId);
expect(item.contentFormatVersion).toEqual(createItemRequest.ContentFormatVersion);
expect(item.content).toStrictEqual(content);
expect(item.state).toEqual(ItemState.Active);
expect(item.revision).toEqual(1);
});
test('should throw if provided with an incorrect share key rotation', async () => {
const vaultKey: VaultKey = {
key: await getSymmetricKey(key),
raw: key,
rotation: 1,
userKeyId: TEST_USER_KEY_ID,
};
const createItemRequest = await createItem({ content, vaultKey });
const encryptedItem: ItemRevisionContentsResponse = {
ItemID: itemId,
Revision: 12,
KeyRotation: 2 /* ⛔️ */,
ContentFormatVersion: createItemRequest.ContentFormatVersion,
Content: createItemRequest.Content,
ItemKey: createItemRequest.ItemKey,
State: ItemState.Active,
CreateTime: timestamp,
ModifyTime: timestamp,
LastUseTime: timestamp,
RevisionTime: timestamp,
};
await expect(openItem({ encryptedItem, vaultKey })).rejects.toThrow(PassCryptoItemError);
});
});
| 7,774
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/open-item.ts
|
import type { ItemRevisionContentsResponse, OpenedItem, VaultKey } from '@proton/pass/types';
import { PassEncryptionTag } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { decryptData } from '../../utils/crypto-helpers';
import { PassCryptoItemError } from '../../utils/errors';
import { openItemKey } from './open-item-key';
type OpenItemKeyProcessParams = {
encryptedItem: ItemRevisionContentsResponse;
vaultKey: VaultKey;
};
export const openItem = async ({ encryptedItem, vaultKey }: OpenItemKeyProcessParams): Promise<OpenedItem> => {
if (!encryptedItem.ItemKey) {
/**
* TODO : If the item has no ItemKey then we're dealing with an ItemShare
* where the ItemKey is stored in the share
*/
throw new PassCryptoItemError('Unsupported operation : cannot open Item from ItemShare yet..');
}
if (vaultKey.rotation !== encryptedItem.KeyRotation) {
throw new PassCryptoItemError(
`Invalid vault key rotation : received ${vaultKey.rotation} / expected ${encryptedItem.KeyRotation}`
);
}
const itemKey = await openItemKey({
encryptedItemKey: { Key: encryptedItem.ItemKey!, KeyRotation: encryptedItem.KeyRotation! },
vaultKey,
});
const decryptedContent = await decryptData(
itemKey.key,
base64StringToUint8Array(encryptedItem.Content),
PassEncryptionTag.ItemContent
);
return {
itemId: encryptedItem.ItemID,
revision: encryptedItem.Revision,
contentFormatVersion: encryptedItem.ContentFormatVersion,
state: encryptedItem.State,
content: decryptedContent,
aliasEmail: encryptedItem.AliasEmail ?? null,
createTime: encryptedItem.CreateTime,
revisionTime: encryptedItem.RevisionTime,
modifyTime: encryptedItem.ModifyTime,
lastUseTime: encryptedItem.LastUseTime ?? null,
};
};
| 7,775
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/update-item.spec.ts
|
import type { ItemKey } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, PassEncryptionTag } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { decryptData, generateKey, getSymmetricKey } from '../../utils/crypto-helpers';
import { PassCryptoItemError } from '../../utils/errors';
import { randomContents } from '../../utils/testing';
import { updateItem } from './update-item';
describe('updateItem crypto process', () => {
const key = generateKey();
const content = randomContents();
test('should re-encrypt item content with supplied item key', async () => {
const itemKey: ItemKey = {
key: await getSymmetricKey(key),
raw: key,
rotation: 42,
};
const update = await updateItem({ content, itemKey, lastRevision: 3 });
expect(update.ContentFormatVersion).toEqual(CONTENT_FORMAT_VERSION);
expect(update.KeyRotation).toEqual(itemKey.rotation);
expect(update.LastRevision).toEqual(3);
const decryptedContent = await decryptData(
itemKey.key,
base64StringToUint8Array(update.Content!),
PassEncryptionTag.ItemContent
);
expect(decryptedContent).toStrictEqual(content);
});
test('should throw when provided with empty content', async () => {
const itemKey: ItemKey = {
key: await getSymmetricKey(key),
raw: key,
rotation: 42,
};
await expect(
updateItem({
content: new Uint8Array(0),
itemKey,
lastRevision: 3,
})
).rejects.toThrow(PassCryptoItemError);
});
test('should throw if base64 content is over MAX_ITEM_CONTENT_B64_LENGTH', async () => {
const itemKey: ItemKey = {
key: await getSymmetricKey(key),
raw: key,
rotation: 42,
};
await expect(
updateItem({
content: new Uint8Array(40000),
itemKey,
lastRevision: 3,
})
).rejects.toThrow(PassCryptoItemError);
});
});
| 7,776
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/item/update-item.ts
|
import type { ItemKey, ItemUpdateRequest } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, PassEncryptionTag } from '@proton/pass/types';
import { pipe } from '@proton/pass/utils/fp/pipe';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { encryptData } from '../../utils/crypto-helpers';
import { PassCryptoItemError } from '../../utils/errors';
import { validateItemContentSize } from '../../utils/validators';
type UpdateItemProcessParams = {
itemKey: ItemKey;
content: Uint8Array;
lastRevision: number;
};
export const updateItem = async ({
itemKey,
content,
lastRevision,
}: UpdateItemProcessParams): Promise<ItemUpdateRequest> => {
if (content.length === 0) {
throw new PassCryptoItemError('Item content cannot be empty');
}
const encryptedItemContent = await encryptData(itemKey.key, content, PassEncryptionTag.ItemContent);
return {
KeyRotation: itemKey.rotation,
LastRevision: lastRevision,
Content: pipe(uint8ArrayToBase64String, validateItemContentSize)(encryptedItemContent),
ContentFormatVersion: CONTENT_FORMAT_VERSION,
};
};
| 7,777
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/share/open-share.spec.ts
|
import { CONTENT_FORMAT_VERSION, type ShareGetResponse, ShareType } from '@proton/pass/types';
import { createRandomKey, randomContents, releaseCryptoProxy, setupCryptoProxyForTesting } from '../../utils/testing';
import { createVault } from '../vault/create-vault';
import { openVaultKey } from '../vault/open-vault-key';
import { openShare } from './open-share';
describe('openShare crypto process', () => {
beforeAll(async () => setupCryptoProxyForTesting());
afterAll(async () => releaseCryptoProxy());
const content = randomContents();
const createTime = Math.floor(Date.now() / 1000);
const vaultId = `vaultId-${Math.random()}`;
const shareId = `shareId-${Math.random()}`;
const addressId = `addressId-${Math.random()}`;
const permission = Math.random();
test('should decrypt VaultShare accordingly', async () => {
const userKey = await createRandomKey();
const vault = await createVault({ content, addressId, userKey });
/* resolve vault key */
const vaultKey = await openVaultKey({
shareKey: {
KeyRotation: 1,
Key: vault.EncryptedVaultKey,
CreateTime: 0,
},
userKeys: [userKey],
});
const encryptedShare: ShareGetResponse = {
AddressID: addressId,
Content: vault.Content,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
ContentKeyRotation: 1,
CreateTime: createTime,
NewUserInvitesReady: 0,
Owner: true,
PendingInvites: 0,
Permission: permission,
Primary: false,
Shared: false,
ShareID: shareId,
TargetID: vaultId,
TargetMaxMembers: 2,
TargetMembers: 0,
TargetType: ShareType.Vault,
VaultID: vaultId,
};
const share = await openShare({ type: ShareType.Vault, encryptedShare, vaultKey });
/* check share properties */
expect(share.addressId).toEqual(addressId);
expect(share.content).toStrictEqual(content);
expect(share.contentFormatVersion).toEqual(CONTENT_FORMAT_VERSION);
expect(share.contentKeyRotation).toEqual(1);
expect(share.permission).toEqual(permission);
expect(share.shareId).toEqual(shareId);
expect(share.targetId).toEqual(vaultId);
expect(share.targetType).toEqual(ShareType.Vault);
expect(share.vaultId).toEqual(vaultId);
});
});
| 7,778
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/share/open-share.ts
|
import { decryptData } from '@proton/pass/lib/crypto/utils/crypto-helpers';
import type { OpenedShare, ShareGetResponse, ShareRole, VaultKey } from '@proton/pass/types';
import { PassEncryptionTag, ShareType } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
type OpenShareProcessParams = { encryptedShare: ShareGetResponse } & (
| { type: ShareType.Vault; vaultKey: VaultKey }
| { type: ShareType.Item }
);
export const openShare = async ({ encryptedShare, ...options }: OpenShareProcessParams): Promise<OpenedShare> => {
const base = {
addressId: encryptedShare.AddressID,
createTime: encryptedShare.CreateTime,
expireTime: encryptedShare.ExpireTime,
newUserInvitesReady: encryptedShare.NewUserInvitesReady,
owner: encryptedShare.Owner,
permission: encryptedShare.Permission,
shared: encryptedShare.Shared,
shareId: encryptedShare.ShareID,
shareRoleId: encryptedShare.ShareRoleID! as ShareRole, // fixme : check optionality
targetId: encryptedShare.TargetID,
targetMaxMembers: encryptedShare.TargetMaxMembers,
targetMembers: encryptedShare.TargetMembers,
targetType: encryptedShare.TargetType,
vaultId: encryptedShare.VaultID,
};
switch (options.type) {
case ShareType.Vault: {
const content = await decryptData(
options.vaultKey.key,
base64StringToUint8Array(encryptedShare.Content!),
PassEncryptionTag.VaultContent
);
return {
...base,
contentKeyRotation: encryptedShare.ContentKeyRotation!,
contentFormatVersion: encryptedShare.ContentFormatVersion!,
content,
};
}
case ShareType.Item: {
return {
...base,
content: null,
contentFormatVersion: null,
contentKeyRotation: null,
};
}
}
};
| 7,779
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/vault/create-vault.spec.ts
|
import { CryptoProxy, VERIFICATION_STATUS } from '@proton/crypto';
import { CONTENT_FORMAT_VERSION, PassEncryptionTag } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { decryptData, getSymmetricKey } from '../../utils/crypto-helpers';
import { PassCryptoVaultError } from '../../utils/errors';
import {
createRandomKey,
randomAddress,
randomContents,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../utils/testing';
import { createVault } from './create-vault';
describe('createVault crypto process', () => {
beforeAll(async () => setupCryptoProxyForTesting());
afterAll(async () => releaseCryptoProxy());
test('should encrypt & sign vaultKey with userKey and encrypt contents with vaultKey', async () => {
const userKey = await createRandomKey();
const address = randomAddress();
const content = randomContents();
const vault = await createVault({ content, addressId: address.ID, userKey });
const { data, verified } = await CryptoProxy.decryptMessage({
binaryMessage: base64StringToUint8Array(vault.EncryptedVaultKey),
decryptionKeys: [userKey.privateKey],
verificationKeys: [userKey.privateKey],
format: 'binary',
});
expect(verified).toEqual(VERIFICATION_STATUS.SIGNED_AND_VALID);
const vaultKey = await getSymmetricKey(data);
const decryptedContent = await decryptData(
vaultKey,
base64StringToUint8Array(vault.Content),
PassEncryptionTag.VaultContent
);
expect(decryptedContent).toStrictEqual(content);
expect(vault.AddressID).toEqual(address.ID);
expect(vault.ContentFormatVersion).toEqual(CONTENT_FORMAT_VERSION);
});
test('should throw when provided with empty content', async () => {
const userKey = await createRandomKey();
const address = randomAddress();
await expect(
createVault({
content: new Uint8Array(0),
addressId: address.ID,
userKey,
})
).rejects.toThrow(PassCryptoVaultError);
});
});
| 7,780
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/vault/create-vault.ts
|
import { CryptoProxy } from '@proton/crypto';
import type { VaultCreateRequest } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, PassEncryptionTag } from '@proton/pass/types';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import type { DecryptedKey } from '@proton/shared/lib/interfaces';
import { encryptData, generateKey, getSymmetricKey } from '../../utils/crypto-helpers';
import { PassCryptoVaultError } from '../../utils/errors';
type CreateVaultProcessParams = {
content: Uint8Array;
userKey: DecryptedKey;
addressId: string;
};
export const createVault = async ({
content,
userKey,
addressId,
}: CreateVaultProcessParams): Promise<VaultCreateRequest> => {
if (content.length === 0) {
throw new PassCryptoVaultError('Vault content cannot be empty');
}
const key = generateKey();
const shareKey = await getSymmetricKey(key);
const encryptedVaultContent = await encryptData(shareKey, content, PassEncryptionTag.VaultContent);
const encryptedVaultKey = await CryptoProxy.encryptMessage({
binaryData: key,
encryptionKeys: [userKey.privateKey],
signingKeys: [userKey.privateKey],
format: 'binary',
});
return {
AddressID: addressId,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
Content: uint8ArrayToBase64String(encryptedVaultContent),
EncryptedVaultKey: uint8ArrayToBase64String(encryptedVaultKey.message),
};
};
| 7,781
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/vault/open-vault-key.spec.ts
|
import { PassEncryptionTag } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import lastItem from '@proton/utils/lastItem';
import { decryptData } from '../../utils/crypto-helpers';
import {
createRandomKey,
randomAddress,
randomContents,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../utils/testing';
import { createVault } from './create-vault';
import { openVaultKey } from './open-vault-key';
describe('openVaultKey crypto process', () => {
beforeAll(async () => setupCryptoProxyForTesting());
afterAll(async () => releaseCryptoProxy());
test('should decrypt vault key using private user keys', async () => {
const userKeys = [await createRandomKey(), await createRandomKey(), await createRandomKey()];
const content = randomContents();
const vault = await createVault({
content,
addressId: randomAddress().ID,
userKey: lastItem(userKeys)!,
});
const vaultKey = await openVaultKey({
shareKey: { Key: vault.EncryptedVaultKey, KeyRotation: 1, CreateTime: 0 },
userKeys,
});
const decryptedContent = await decryptData(
vaultKey.key,
base64StringToUint8Array(vault.Content),
PassEncryptionTag.VaultContent
);
expect(vaultKey.rotation).toEqual(1);
expect(decryptedContent).toStrictEqual(content);
});
});
| 7,782
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/vault/open-vault-key.ts
|
import { CryptoProxy, VERIFICATION_STATUS } from '@proton/crypto';
import type { ShareKeyResponse, VaultKey } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import type { DecryptedKey } from '@proton/shared/lib/interfaces';
import { getSymmetricKey } from '../../utils/crypto-helpers';
import { PassCryptoVaultError } from '../../utils/errors';
type OpenVaultKeyProcessParams = {
shareKey: ShareKeyResponse;
userKeys: DecryptedKey[];
};
export const openVaultKey = async ({ shareKey, userKeys }: OpenVaultKeyProcessParams): Promise<VaultKey> => {
const { Key, KeyRotation, UserKeyID } = shareKey;
const privateUserKeys = userKeys.map(({ privateKey }) => privateKey);
const { data: vaultKey, verified } = await CryptoProxy.decryptMessage({
binaryMessage: base64StringToUint8Array(Key),
decryptionKeys: privateUserKeys,
verificationKeys: privateUserKeys,
format: 'binary',
});
if (verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) {
throw new PassCryptoVaultError(`Could not validate vault key signature`);
}
return {
raw: vaultKey,
key: await getSymmetricKey(vaultKey),
rotation: KeyRotation,
userKeyId: UserKeyID,
};
};
| 7,783
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/vault/update-vault.spec.ts
|
import type { VaultKey } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, PassEncryptionTag } from '@proton/pass/types';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { decryptData, generateKey, getSymmetricKey } from '../../utils/crypto-helpers';
import { PassCryptoVaultError } from '../../utils/errors';
import { TEST_USER_KEY_ID, randomContents } from '../../utils/testing';
import { updateVault } from './update-vault';
describe('updateVault crypto process', () => {
test('should re-encrypt vault content with supplied vault key', async () => {
const key = generateKey();
const shareKey = await getSymmetricKey(key);
const content = randomContents();
const vaultKey: VaultKey = {
key: shareKey,
raw: key,
rotation: 42,
userKeyId: TEST_USER_KEY_ID,
};
const vaultUpdate = await updateVault({ vaultKey, content });
const decryptedContent = await decryptData(
vaultKey.key,
base64StringToUint8Array(vaultUpdate.Content),
PassEncryptionTag.VaultContent
);
expect(decryptedContent).toStrictEqual(content);
expect(vaultUpdate.ContentFormatVersion).toEqual(CONTENT_FORMAT_VERSION);
expect(vaultUpdate.KeyRotation).toEqual(42);
});
test('should throw when provided with empty content', async () => {
const key = generateKey();
const shareKey = await getSymmetricKey(key);
const vaultKey: VaultKey = {
key: shareKey,
raw: key,
rotation: 42,
userKeyId: TEST_USER_KEY_ID,
};
await expect(
updateVault({
content: new Uint8Array(0),
vaultKey,
})
).rejects.toThrow(PassCryptoVaultError);
});
});
| 7,784
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/processes/vault/update-vault.ts
|
import type { VaultKey, VaultUpdateRequest } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, PassEncryptionTag } from '@proton/pass/types';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { encryptData } from '../../utils/crypto-helpers';
import { PassCryptoVaultError } from '../../utils/errors';
type UpdateVaultProcessParams = {
vaultKey: VaultKey;
content: Uint8Array;
};
export const updateVault = async ({ vaultKey, content }: UpdateVaultProcessParams): Promise<VaultUpdateRequest> => {
if (content.length === 0) {
throw new PassCryptoVaultError('Vault content cannot be empty');
}
const encryptedVaultContent = await encryptData(vaultKey.key, content, PassEncryptionTag.VaultContent);
return {
ContentFormatVersion: CONTENT_FORMAT_VERSION,
Content: uint8ArrayToBase64String(encryptedVaultContent),
KeyRotation: vaultKey.rotation,
};
};
| 7,785
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/utils/addresses.ts
|
import { and, or } from '@proton/pass/utils/fp/predicates';
import { getIsAddressActive, getIsAddressEnabled, getIsAddressExternal } from '@proton/shared/lib/helpers/address';
import type { Address } from '@proton/shared/lib/interfaces';
type AddressPredicate = (address: Address) => boolean;
/**
* When user is external : make sure the address is enabled
* When user is internal : make sure address is active
*/
export const getSupportedAddresses = or<AddressPredicate[]>(
getIsAddressActive,
and(getIsAddressEnabled, getIsAddressExternal)
);
| 7,786
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/utils/cache.decrypt.ts
|
import { deobfuscateItem, obfuscateItem } from '@proton/pass/lib/items/item.obfuscation';
import type { ItemsByShareId } from '@proton/pass/store/reducers';
import type { State } from '@proton/pass/store/types';
import type { Maybe, PassCryptoSnapshot, SerializedCryptoContext } from '@proton/pass/types';
import { PassEncryptionTag } from '@proton/pass/types';
import type { EncryptedPassCache, PassCache } from '@proton/pass/types/worker/cache';
import { logger } from '@proton/pass/utils/logger';
import { stringToUint8Array, uint8ArrayToString } from '@proton/shared/lib/helpers/encoding';
import { getCacheEncryptionKey } from './cache.encrypt';
import { decryptData } from './crypto-helpers';
const decrypt = async <T extends object>(options: {
data: string;
key: CryptoKey;
useTextDecoder: boolean;
}): Promise<T | undefined> => {
if (!options.data) return;
try {
const encryptedData = stringToUint8Array(options.data);
const decryptedData = await decryptData(options.key, encryptedData, PassEncryptionTag.Cache);
const decoder = new TextDecoder();
return JSON.parse(
options.useTextDecoder ? decoder.decode(decryptedData) : uint8ArrayToString(decryptedData)
) as T;
} catch (error) {
logger.warn(`[Cache::decrypt] Decryption failure`, error);
}
};
export const decryptCachedState = async (
{ state: encryptedState, snapshot: encryptedSnapshot, salt }: Partial<EncryptedPassCache>,
sessionLockToken: Maybe<string>
): Promise<Maybe<PassCache>> => {
if (!encryptedState) logger.warn(`[Cache::decrypt] Cached state not found`);
if (!encryptedSnapshot) logger.warn(`[Cache::decrypt] Crypto snapshot not found`);
if (!salt) logger.warn(`[Cache::decrypt] Salt not found`);
if (encryptedState && encryptedSnapshot && salt) {
logger.info(`[Cache::decrypt] Decrypting cache [sessionLockToken=${!!sessionLockToken}]`);
const cacheKey = await getCacheEncryptionKey(stringToUint8Array(salt), sessionLockToken);
const [state, snapshot] = await Promise.all([
decrypt<State>({ data: encryptedState, key: cacheKey, useTextDecoder: true }),
decrypt<SerializedCryptoContext<PassCryptoSnapshot>>({
data: encryptedSnapshot,
key: cacheKey,
useTextDecoder: false,
}),
]);
if (state !== undefined && snapshot !== undefined) {
/* reobfuscate each cached item with a new mask */
for (const [shareId, items] of Object.entries(state.items.byShareId as ItemsByShareId)) {
for (const item of Object.values(items)) {
if ('itemId' in item) {
state.items.byShareId[shareId][item.itemId] = {
...item,
data: obfuscateItem(deobfuscateItem(item.data)),
};
}
}
}
return { state, snapshot };
}
}
};
| 7,787
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/utils/cache.encrypt.ts
|
import { authentication } from '@proton/pass/lib/auth/store';
import type { Maybe } from '@proton/pass/types';
import { ENCRYPTION_ALGORITHM } from '@proton/shared/lib/authentication/cryptoHelper';
import { stringToUint8Array } from '@proton/shared/lib/helpers/encoding';
const KEY_ALGORITHM = { name: 'AES-GCM', length: 256 };
export const CACHE_SALT_LENGTH = 32;
const HKDF_PARAMS: Omit<HkdfParams, 'salt'> = {
name: 'HKDF',
hash: 'SHA-256',
info: stringToUint8Array('pass-extension-cache-key'), // context identifier for domain separation
};
/**
* Get key to use for cache encryption.
* NB: this function does not take an arbitrary key/password in input because it relies on a key derivation step
* that is only secure enough in some cases.
* @param salt - randomly generated salt of `SALT_LENGTH` size, ideally regenerated at each snapshot
* @returns key to use with `encryptData` and `decryptData`
*/
export const getCacheEncryptionKey = async (salt: Uint8Array, sessionLockToken: Maybe<string>): Promise<CryptoKey> => {
// sanity check to avoid problems when using the key
if (ENCRYPTION_ALGORITHM !== KEY_ALGORITHM.name) {
throw new Error('Key algorithm does not match encryption algorithm');
}
// We run a key derivation step (HKDF) to achieve domain separation (preventing the encrypted data to be
// decrypted outside of the booting context) and to better protect the password in case of e.g.
// future GCM key-recovery attacks.
// Since the password is already salted using bcrypt, we consider it entropic enough for HKDF: see
// discussion on key-stretching step in https://eprint.iacr.org/2010/264.pdf (Section 9).
const saltedUserPassword = `${authentication.getPassword()}${sessionLockToken ?? ''}`;
const passwordBytes = stringToUint8Array(saltedUserPassword);
const keyToSalt = await crypto.subtle.importKey('raw', passwordBytes.buffer, HKDF_PARAMS.name, false, [
'deriveKey',
]);
return crypto.subtle.deriveKey(
{
...HKDF_PARAMS,
salt,
},
keyToSalt,
KEY_ALGORITHM,
false,
['decrypt', 'encrypt']
);
};
| 7,788
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/utils/crypto-helpers.ts
|
import { stringToUtf8Array } from '@proton/crypto/lib/utils';
import type { PassEncryptionTag } from '@proton/pass/types';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
export const KEY_LENGTH = 32;
const IV_LENGTH = 12;
const ALGORITHM = 'AES-GCM';
export const getSymmetricKey = async (key: Uint8Array): Promise<CryptoKey> =>
crypto.subtle.importKey('raw', key.slice(0, KEY_LENGTH).buffer, ALGORITHM, false, ['decrypt', 'encrypt']);
export const generateKey = (): Uint8Array => crypto.getRandomValues(new Uint8Array(KEY_LENGTH));
export const encryptData = async (key: CryptoKey, data: Uint8Array, tag: PassEncryptionTag) => {
const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
const cipher = await crypto.subtle.encrypt(
{ name: ALGORITHM, iv, additionalData: stringToUtf8Array(tag) },
key,
data
);
return mergeUint8Arrays([iv, new Uint8Array(cipher)]);
};
export const decryptData = async (key: CryptoKey, data: Uint8Array, tag: PassEncryptionTag) => {
const iv = data.slice(0, IV_LENGTH);
const cipher = data.slice(IV_LENGTH, data.length);
const result = await crypto.subtle.decrypt(
{ name: ALGORITHM, iv, additionalData: stringToUtf8Array(tag) },
key,
cipher
);
return new Uint8Array(result);
};
| 7,789
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/utils/errors.ts
|
export class PassCryptoError extends Error {}
export class PassCryptoNotHydratedError extends PassCryptoError {}
export class PassCryptoHydrationError extends PassCryptoError {}
export class PassCryptoShareError extends PassCryptoError {}
export class PassCryptoVaultError extends PassCryptoError {}
export class PassCryptoItemError extends PassCryptoError {}
export const isPassCryptoError = (err: any) => err instanceof PassCryptoError;
| 7,790
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/utils/testing.ts
|
import type { PrivateKeyReference } from '@proton/crypto';
import { CryptoProxy } from '@proton/crypto';
import type { ShareGetResponse, ShareKeyResponse, TypedOpenedShare, VaultKey } from '@proton/pass/types';
import { CONTENT_FORMAT_VERSION, ShareType } from '@proton/pass/types';
import { ADDRESS_TYPE } from '@proton/shared/lib/constants';
import { type Address, AddressConfirmationState, type DecryptedKey } from '@proton/shared/lib/interfaces';
import { createVault } from '../processes/vault/create-vault';
import { generateKey, getSymmetricKey } from './crypto-helpers';
/* Load Crypto API outside of web workers, for testing purposes.
* Dynamic import to avoid loading the library unless required */
export async function setupCryptoProxyForTesting() {
const { Api: CryptoApi } = await import(
/* webpackChunkName: "crypto-worker-api" */ '@proton/crypto/lib/worker/api'
);
CryptoApi.init();
CryptoProxy.setEndpoint(new CryptoApi(), (endpoint) => endpoint.clearKeyStore());
}
export function releaseCryptoProxy() {
return CryptoProxy.releaseEndpoint();
}
export function randomKey(): Promise<PrivateKeyReference> {
return CryptoProxy.generateKey({ userIDs: [{ name: 'TestKey', email: 'test@proton.ch' }], curve: 'ed25519' });
}
export const TEST_KEY_PASSWORD = 'p4ssphr4se';
export const TEST_USER_KEY_ID = 'userkey_123';
export const createRandomKey = async (): Promise<DecryptedKey> => {
const generatedKey = await randomKey();
return {
privateKey: generatedKey,
publicKey: generatedKey,
ID: TEST_USER_KEY_ID,
};
};
export function randomAddress(): Address {
return {
ConfirmationState: AddressConfirmationState.CONFIRMATION_CONFIRMED,
DisplayName: '',
DomainID: '',
Email: '',
HasKeys: 0,
Keys: [],
Order: 0,
Priority: 0,
Receive: 0,
Send: 0,
Signature: '',
SignedKeyList: null,
Status: 0,
Type: ADDRESS_TYPE.TYPE_ORIGINAL,
ID: '345',
ProtonMX: true,
CatchAll: false,
};
}
export function randomContents(length: number = 20): Uint8Array {
let a = [];
for (let i = 0; i < length; i++) {
a[i] = Math.ceil(Math.random() * 255);
}
return new Uint8Array(a);
}
export const createRandomShareResponses = async (
userKey: DecryptedKey,
addressId: string,
content?: Uint8Array
): Promise<[ShareGetResponse, ShareKeyResponse]> => {
const vault = await createVault({ content: content ?? randomContents(), userKey, addressId });
return [
{
AddressID: vault.AddressID,
Content: vault.Content,
ContentFormatVersion: CONTENT_FORMAT_VERSION,
ContentKeyRotation: 1,
CreateTime: 0,
ExpireTime: 0,
NewUserInvitesReady: 0,
Owner: true,
PendingInvites: 0,
Permission: 1,
Primary: false,
Shared: false,
ShareID: `shareId-${Math.random()}`,
TargetID: `targetId-${Math.random()}`,
TargetMaxMembers: 2,
TargetMembers: 1,
TargetType: ShareType.Vault,
VaultID: `vaultId-${Math.random()}`,
},
{
Key: vault.EncryptedVaultKey,
KeyRotation: 1,
CreateTime: 0,
UserKeyID: userKey.ID,
},
];
};
export const createRandomShare = <T extends ShareType>(targetType: T): TypedOpenedShare<T> => {
const base = {
shareId: `shareId-${Math.random()}`,
vaultId: `vaultId-${Math.random()}`,
targetId: `targetId-${Math.random()}`,
addressId: `addressId-${Math.random()}`,
permission: 42,
expireTime: 0,
createTime: 0,
};
switch (targetType) {
case ShareType.Vault: {
return {
...base,
targetType,
content: randomContents(),
contentKeyRotation: 1,
contentFormatVersion: CONTENT_FORMAT_VERSION,
} as TypedOpenedShare<T>;
}
case ShareType.Item: {
return {
...base,
targetType,
content: null,
contentKeyRotation: null,
contentFormatVersion: null,
} as TypedOpenedShare<T>;
}
default: {
throw new Error('Unknown target share type');
}
}
};
export const createRandomVaultKey = async (rotation: number): Promise<VaultKey> => {
const raw = generateKey();
const key = await getSymmetricKey(raw);
return { key, raw, rotation, userKeyId: undefined };
};
| 7,791
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/crypto/utils/validators.ts
|
import { c } from 'ttag';
import { PassCryptoItemError } from './errors';
/* this is roughly equivalent to a 7kb binary blob */
export const MAX_ITEM_CONTENT_B64_LENGTH = 53248;
export const validateItemContentSize = (base64Content: string): string => {
if (base64Content.length > MAX_ITEM_CONTENT_B64_LENGTH) {
throw new PassCryptoItemError(c('Error').t`Item content cannot exceed 40KB`);
}
return base64Content;
};
| 7,792
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/events/constants.ts
|
export const ACTIVE_POLLING_TIMEOUT = 30_000; /* 30 seconds */
export const INACTIVE_POLLING_TIMEOUT = 1_800_000; /* 30 minutes */
| 7,793
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/events/manager.spec.ts
|
import type { Api } from '@proton/pass/types';
import { FIBONACCI_LIST } from '@proton/shared/lib/constants';
import { eventManager } from './manager';
const TEST_INTERVAL = 5_000;
const getTestEventID = (n: number = 1) => `TEST_EVENT_ID_${n}`;
const createMockedEventManager = () => {
const mockApi = jest.fn().mockImplementation(() => Promise.resolve({}));
(mockApi as any).getState = () => ({});
const mockQuery = jest.fn().mockImplementation(() => ({ url: 'test/endpoint' }));
const mockGetCursor = jest.fn().mockImplementation((res) => ({ EventID: res.EventID, More: Boolean(res.More) }));
const manager = eventManager({
api: mockApi as any as Api,
initialEventID: getTestEventID(0),
interval: TEST_INTERVAL,
query: mockQuery,
getCursor: mockGetCursor,
});
return {
manager,
api: mockApi as jest.Mock,
query: mockQuery as jest.Mock,
setApiResponse: (EventID: string, More: 0 | 1) => mockApi.mockResolvedValue({ EventID, More }),
};
};
describe('event manager', () => {
beforeEach(() => jest.useFakeTimers());
test('should initialize configuration correctly', () => {
const { manager } = createMockedEventManager();
const state = manager.state;
expect(manager.getEventID()).toEqual(getTestEventID(0));
expect(state.lastEventID).toEqual(getTestEventID(0));
expect(state.interval).toEqual(5_000);
expect(state.abortController).toBe(undefined);
expect(state.timeoutHandle).toBe(undefined);
expect(state.retryIndex).toEqual(0);
});
test('setters should update internal state', () => {
const { manager } = createMockedEventManager();
manager.setEventID(getTestEventID(1));
manager.setInterval(30_000);
expect(manager.state.lastEventID).toEqual(getTestEventID(1));
expect(manager.state.interval).toEqual(30_000);
});
test('should immediately call API when calling `call()`', async () => {
const { manager, api, query } = createMockedEventManager();
api.mockResolvedValue({ EventID: getTestEventID(1), More: 0 });
await manager.call();
expect(api).toHaveBeenCalledTimes(1);
expect(query.mock.calls[0][0]).toEqual(getTestEventID(0));
expect(manager.state.lastEventID).toEqual(getTestEventID(1));
expect(manager.state.timeoutHandle).toBeDefined();
expect(manager.state.abortController).not.toBeDefined();
expect(manager.state.retryIndex).toEqual(0);
manager.stop();
});
test('should handle `More` data and re-request API in the same timeout', async () => {
const { manager, api, query } = createMockedEventManager();
let count = 0;
api.mockImplementation(() => {
count += 1;
return Promise.resolve({
EventID: getTestEventID(count),
More: count == 2 ? 0 : 1,
});
});
await manager.call();
expect(api).toHaveBeenCalledTimes(2);
expect(query.mock.calls[0][0]).toEqual(getTestEventID(0));
expect(query.mock.calls[1][0]).toEqual(getTestEventID(1));
expect(manager.state.lastEventID).toEqual(getTestEventID(2));
expect(manager.state.timeoutHandle).toBeDefined();
expect(manager.state.abortController).not.toBeDefined();
expect(manager.state.retryIndex).toEqual(0);
manager.stop();
});
test('should start polling after interval when calling `start()`', async () => {
const { manager, api } = createMockedEventManager();
api.mockResolvedValue({ EventID: getTestEventID(1), More: 0 });
manager.start();
expect(manager.state.timeoutHandle).toBeDefined();
jest.advanceTimersByTime(TEST_INTERVAL);
expect(api).toHaveBeenCalledTimes(1);
expect(manager.state.abortController).toBeDefined();
await jest.advanceTimersToNextTimerAsync();
expect(manager.state.lastEventID).toEqual(getTestEventID(1));
expect(manager.state.retryIndex).toEqual(0);
expect(manager.state.abortController).not.toBeDefined();
expect(manager.state.timeoutHandle).toBeDefined();
manager.stop();
});
test('should cancel timeout when calling `stop()`', async () => {
const { manager, api, query } = createMockedEventManager();
api.mockResolvedValue({ EventID: getTestEventID(1), More: 0 });
manager.start();
expect(manager.state.timeoutHandle).toBeDefined();
jest.advanceTimersByTime(TEST_INTERVAL - 1);
manager.stop();
await jest.advanceTimersToNextTimerAsync();
jest.advanceTimersByTime(1);
expect(api).not.toHaveBeenCalled();
expect(query).not.toHaveBeenCalled();
expect(manager.state.lastEventID).toEqual(getTestEventID(0));
expect(manager.state.retryIndex).toEqual(0);
expect(manager.state.abortController).not.toBeDefined();
expect(manager.state.timeoutHandle).not.toBeDefined();
});
test('should stop and reset internal state when calling `reset()`', async () => {
const { manager, api, query } = createMockedEventManager();
api.mockResolvedValue({ EventID: getTestEventID(1), More: 0 });
manager.start();
expect(manager.state.timeoutHandle).toBeDefined();
jest.advanceTimersByTime(TEST_INTERVAL - 1);
manager.reset();
await jest.advanceTimersToNextTimerAsync();
jest.advanceTimersByTime(1);
expect(api).not.toHaveBeenCalled();
expect(query).not.toHaveBeenCalled();
expect(manager.state.lastEventID).not.toBeDefined();
expect(manager.state.retryIndex).toEqual(0);
expect(manager.state.abortController).not.toBeDefined();
expect(manager.state.timeoutHandle).not.toBeDefined();
});
test('should notify listeners on events & errors', async () => {
const { manager, api } = createMockedEventManager();
const listener = jest.fn().mockImplementation();
manager.subscribe(listener);
let count = 0;
api.mockImplementation(() => {
count += 1;
return Promise.resolve({
EventID: getTestEventID(count),
More: 0,
});
});
manager.start();
while (count < 5) {
await jest.advanceTimersToNextTimerAsync();
expect(listener).toHaveBeenCalledTimes(count);
expect(listener.mock.calls[count - 1][0]).toEqual({ EventID: getTestEventID(count), More: 0 });
}
api.mockImplementation(() => Promise.reject('FAILURE'));
await jest.advanceTimersToNextTimerAsync();
expect(listener).toHaveBeenCalledTimes(count + 1);
expect(listener.mock.calls[count][0]).toEqual({ error: 'FAILURE' });
manager.stop();
});
test('retry behaviour should throttle interval', async () => {
const { manager, api } = createMockedEventManager();
api.mockImplementation(() => Promise.reject('FAILURE'));
manager.start();
let count = 0;
while (count < 10) {
count++;
await jest.advanceTimersByTimeAsync(TEST_INTERVAL * FIBONACCI_LIST[manager.state.retryIndex]);
const retryIndex = Math.min(count, FIBONACCI_LIST.length - 1);
expect(manager.state.retryIndex).toEqual(retryIndex);
}
expect(api).toHaveBeenCalledTimes(10);
});
});
| 7,794
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/events/manager.ts
|
import type { Maybe } from '@proton/pass/types';
import type { Api } from '@proton/pass/types/api';
import { logger } from '@proton/pass/utils/logger';
import { FIBONACCI_LIST } from '@proton/shared/lib/constants';
import createListeners from '@proton/shared/lib/helpers/listeners';
import { onceWithQueue } from '@proton/shared/lib/helpers/onceWithQueue';
import { ACTIVE_POLLING_TIMEOUT } from './constants';
export type EventManagerEvent<T extends {}> = T | { error: unknown };
export type EventCursor = { EventID: string; More: boolean };
export const NOOP_EVENT = '*';
export type EventManagerConfig<T extends {}> = {
api: Api /* Function to call the API */;
interval?: number /* Maximum interval time to wait between each call */;
initialEventID: string;
query: (eventID: string) => {} /* Event polling endpoint override */;
getCursor: (event: T) => EventCursor;
getLatestEventID?: () => Promise<string> | string;
};
export type EventManager<T extends {}> = {
state: EventManagerState;
setEventID: (eventID: string) => void;
getEventID: () => Maybe<string>;
start: () => void;
stop: () => void;
call: () => Promise<void>;
reset: () => void;
setInterval: (interval: number) => void;
subscribe: (listener: (event: EventManagerEvent<T>) => void) => () => void;
};
type EventManagerState = {
interval: number;
retryIndex: number;
lastEventID?: string;
timeoutHandle?: any;
abortController?: AbortController;
};
export const eventManager = <T extends {}>({
api,
interval = ACTIVE_POLLING_TIMEOUT,
initialEventID,
query,
getCursor,
getLatestEventID,
}: EventManagerConfig<T>): EventManager<T> => {
const listeners = createListeners<[EventManagerEvent<T>]>();
const state: EventManagerState = { interval, retryIndex: 0, lastEventID: initialEventID };
const setInterval = (nextInterval: number) => (state.interval = nextInterval);
const setEventID = (eventID: string) => (state.lastEventID = eventID);
const getEventID = () => (state.lastEventID ? state.lastEventID : undefined);
const setRetryIndex = (index: number) => (state.retryIndex = index);
const getRetryIndex = () => state.retryIndex;
/* Increase the retry index when the call fails to not spam */
const increaseRetryIndex = () => {
const index = getRetryIndex();
if (index < FIBONACCI_LIST.length - 1) setRetryIndex(index + 1);
};
/* Start the event manager, does nothing if it is already started */
const start = (callFn: () => Promise<void>) => {
if (!state.timeoutHandle) {
const ms = state.interval * FIBONACCI_LIST[state.retryIndex];
state.timeoutHandle = setTimeout(callFn, ms);
}
};
/* Stop the event manager, does nothing if it's already stopped */
const stop = () => {
if (state.abortController) {
state.abortController.abort();
delete state.abortController;
}
if (state.timeoutHandle) {
clearTimeout(state.timeoutHandle);
delete state.timeoutHandle;
}
};
/* Stop the event manager and reset its state */
const reset = () => {
stop();
state.retryIndex = 0;
state.interval = interval;
delete state.abortController;
delete state.lastEventID;
delete state.timeoutHandle;
listeners.clear();
};
/* Call the event manager. Either does it immediately, or queues
* the call until after the current call has finished */
const call = onceWithQueue(async () => {
try {
stop();
const abortController = new AbortController();
state.abortController = abortController;
while (true) {
const eventID = getEventID() ?? (await getLatestEventID?.());
if (!eventID) {
logger.warn('No valid `EventID` provided');
return;
}
const result = await api<T>({ ...query(eventID), signal: abortController.signal, silence: true });
if (!result) return;
await Promise.all(listeners.notify(result));
const { More, EventID: nextEventID } = getCursor(result);
setEventID(nextEventID);
setRetryIndex(0);
if (!More) break;
}
delete state.abortController;
start(call);
} catch (error: any) {
/* ⚠️ if the request failed due to a locked or inactive session :
* do not restart the event-manager. For any other type of error,
* we can safely increase the retry index and retry.. */
const { appVersionBad, sessionInactive, sessionLocked } = api.getState();
if (error.name === 'AbortError' || appVersionBad || sessionInactive || sessionLocked) return;
delete state.abortController;
increaseRetryIndex();
start(call);
listeners.notify({ error });
throw error;
}
});
return {
setEventID,
getEventID,
setInterval,
start: () => start(call),
stop,
call,
reset,
subscribe: listeners.subscribe,
get state() {
return state;
},
};
};
| 7,795
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/export/export.spec.ts
|
import JSZip from 'jszip';
import { CryptoProxy } from '@proton/crypto';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '@proton/pass/lib/crypto/utils/testing';
import { CONTENT_FORMAT_VERSION, ItemState } from '@proton/pass/types';
import { getEpoch } from '@proton/pass/utils/time/get-epoch';
import { PASS_APP_NAME } from '@proton/shared/lib/constants';
import { createExportZip, encryptZip } from './export';
import type { ExportPayload } from './types';
const EXPORT_TEST_VAULT_ID = 'vault-share-id';
const EXPORT_TEST_PAYLOAD: ExportPayload = {
version: '5.0.0.99',
encrypted: true,
vaults: {
[EXPORT_TEST_VAULT_ID]: {
name: 'Default vault',
description: 'This is my super secret test vault',
display: {},
items: [
{
itemId: `itemId-${Math.random()}`,
shareId: `shareId-${Math.random()}`,
state: ItemState.Active,
data: {
type: 'note',
metadata: {
name: 'Note',
note: 'This is a test note',
itemUuid: 'r4nd0mUUID',
},
content: {},
platformSpecific: {},
extraFields: [],
},
contentFormatVersion: CONTENT_FORMAT_VERSION,
aliasEmail: null,
createTime: getEpoch(),
modifyTime: getEpoch() + 100,
},
],
},
},
};
const EXPORT_TEST_PASSPHRASE = 'p4ssphr4se';
describe('Pass export', () => {
beforeAll(async () => setupCryptoProxyForTesting());
afterAll(async () => releaseCryptoProxy());
test('createExportZip should build unencrypted zip', async () => {
const zip = await createExportZip(EXPORT_TEST_PAYLOAD);
const unzip = await JSZip.loadAsync(zip);
expect(unzip.file('export.json')).not.toBe(undefined);
const rawData = await unzip.file(`${PASS_APP_NAME}/data.json`)?.async('string');
const data = JSON.parse(rawData!);
expect(data.version).toEqual(EXPORT_TEST_PAYLOAD.version);
expect(data.vaults).toEqual(EXPORT_TEST_PAYLOAD.vaults);
});
test('encryptZip should encrypt zip file to binary format', async () => {
const uint8Zip = crypto.getRandomValues(new Uint8Array(32));
const armoredMessage = await encryptZip(uint8Zip, EXPORT_TEST_PASSPHRASE);
const decrypted = await CryptoProxy.decryptMessage({
armoredMessage,
passwords: [EXPORT_TEST_PASSPHRASE],
format: 'binary',
});
expect(decrypted.data.toString()).toEqual(uint8Zip.toString());
});
});
| 7,796
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/export/export.ts
|
import JSZip from 'jszip';
import { CryptoProxy } from '@proton/crypto';
import { PASS_APP_NAME } from '@proton/shared/lib/constants';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import type { ExportPayload } from './types';
/**
* Exporting data from the extension uses the .zip format
* for future-proofing : we will support integrating additional
* files when exporting
*/
export const createExportZip = async (payload: ExportPayload): Promise<Uint8Array> => {
const zip = new JSZip();
zip.file(`${PASS_APP_NAME}/data.json`, JSON.stringify(payload));
return zip.generateAsync({ type: 'uint8array' });
};
/**
* Once support for argon2 is released, then we should pass a config to use
* that instead - as long as the export feature is alpha, it’s okay to release
* without argon2, but let’s pass config: { s2kIterationCountByte: 255 } to
* encryptMessage with the highest security we have atm
*/
export const encryptZip = async (data: Uint8Array, passphrase: string): Promise<string> =>
(
await CryptoProxy.encryptMessage({
binaryData: data,
passwords: [passphrase],
config: { s2kIterationCountByte: 255 },
format: 'armored',
})
).message;
export const decryptZip = async (data: string, passphrase: string): Promise<string> => {
const decrypted = await CryptoProxy.decryptMessage({
armoredMessage: data,
passwords: [passphrase],
format: 'binary',
});
return uint8ArrayToBase64String(decrypted.data);
};
| 7,797
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/export/types.ts
|
import type { ItemType, UnsafeItemRevision, VaultShareContent } from '@proton/pass/types';
export type ExportedItem<T extends ItemType = ItemType> = Omit<
UnsafeItemRevision<T>,
'revision' | 'revisionTime' | 'lastUseTime'
>;
export type ExportPayload = {
version: string;
encrypted: boolean;
userId?: string;
vaults: {
[shareId: string]: VaultShareContent & {
items: ExportedItem[];
};
};
};
export type ExportRequestPayload = { encrypted: true; passphrase: string } | { encrypted: false };
| 7,798
|
0
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/extension
|
petrpan-code/ProtonMail/WebClients/packages/pass/lib/extension/message/index.ts
|
export * from './send-message';
export * from './message-broker';
| 7,799
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.