summaryrefslogtreecommitdiffstats
path: root/toolkit/components/satchel/SignUpFormRuleset.sys.mjs
blob: 7a42880fdb628bfe09f5a0a337d38d0f82a36798 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/* 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/. */

/**
 * Fathom ML model for identifying sign up <forms>
 *
 * This is developed out-of-tree at https://github.com/mozilla-services/fathom-login-forms,
 * where there is also over a GB of training, validation, and
 * testing data. To make changes, do your edits there (whether adding new
 * training pages, adding new rules, or both), retrain and evaluate as
 * documented at https://mozilla.github.io/fathom/training.html, paste the
 * coefficients emitted by the trainer into the ruleset, and finally copy the
 * ruleset's "CODE TO COPY INTO PRODUCTION" section to this file's "CODE FROM
 * TRAINING REPOSITORY" section.
 */

import {
  dom,
  out,
  rule,
  ruleset,
  score,
  type,
  element,
  utils,
} from "resource://gre/modules/third_party/fathom/fathom.mjs";

let { isVisible, attributesMatch, setDefault } = utils;

const DEVELOPMENT = false;

/**
 * --- START OF CODE FROM TRAINING REPOSITORY ---
 */
const coefficients = {
  form: new Map([
    ["formAttributesMatchRegisterRegex", 0.4614015519618988],
    ["formAttributesMatchLoginRegex", -2.608457326889038],
    ["formAttributesMatchSubscriptionRegex", -3.253319501876831],
    ["formAttributesMatchLoginAndRegisterRegex", 3.6423728466033936],
    ["formHasAcNewPassword", 2.214113473892212],
    ["formHasAcCurrentPassword", -0.43707895278930664],
    ["formHasEmailField", 1.760241150856018],
    ["formHasUsernameField", 1.1527059078216553],
    ["formHasPasswordField", 1.6670876741409302],
    ["formHasFirstOrLastNameField", 0.9517516493797302],
    ["formHasRegisterButton", 1.574048638343811],
    ["formHasLoginButton", -1.1688978672027588],
    ["formHasSubscribeButton", -0.26299405097961426],
    ["formHasContinueButton", 2.3797709941864014],
    ["formHasTermsAndConditionsHyperlink", 1.764896035194397],
    ["formHasPasswordForgottenHyperlink", -0.32138824462890625],
    ["formHasAlreadySignedUpHyperlink", 3.160510301589966],
    ["closestElementIsEmailLabelLike", 1.0336143970489502],
    ["formHasRememberMeCheckbox", -1.2176686525344849],
    ["formHasSubcriptionCheckbox", 0.6100747585296631],
    ["docTitleMatchesRegisterRegex", 0.680654764175415],
    ["docTitleMatchesEditProfileRegex", -4.104133605957031],
    ["closestHeaderMatchesRegisterRegex", 1.3462989330291748],
    ["closestHeaderMatchesLoginRegex", -0.1804502159357071],
    ["closestHeaderMatchesSubscriptionRegex", -1.3057124614715576],
  ]),
};

const biases = [["form", -4.402400970458984]];

const loginRegex =
  /login|log-in|log_in|log in|signon|sign-on|sign_on|sign on|signin|sign-in|sign_in|sign in|einloggen|anmelden|logon|log-on|log_on|log on|Войти|ورود|登录|Přihlásit se|Přihlaste|Авторизоваться|Авторизация|entrar|ログイン|로그인|inloggen|Συνδέσου|accedi|ログオン|Giriş Yap|登入|connecter|connectez-vous|Connexion|Вход|inicia/i;
const registerRegex =
  /regist|sign up|signup|sign-up|sign_up|join|new|登録|neu|erstellen|設定|신규|Créer|Nouveau|baru|nouă|nieuw|create[a-zA-Z\s]+account|create[a-zA-Z\s]+profile|activate[a-zA-Z\s]+account|Zugang anlegen|Angaben prüfen|Konto erstellen|ثبت نام|登録|注册|cadastr|Зарегистрироваться|Регистрация|Bellige alynmak|تسجيل|ΕΓΓΡΑΦΗΣ|Εγγραφή|Créer mon compte|Créer un compte|Mendaftar|가입하기|inschrijving|Zarejestruj się|Deschideți un cont|Создать аккаунт|ร่วม|Üye Ol|ساخت حساب کاربری|Schrijf je|S'inscrire/i;
const emailRegex = /mail/i;
const usernameRegex = /user|member/i;
const nameRegex = /first|last|middle/i;
const subscriptionRegex =
  /subscri|trial|offer|information|angebote|probe|ニュースレター|abonn|promotion|news/i;
const termsAndConditionsRegex =
  /terms|condition|rules|policy|privacy|nutzungsbedingungen|AGB|richtlinien|datenschutz|términos|condiciones/i;
const pwForgottenRegex =
  /forgot|reset|set password|vergessen|vergeten|oublié|dimenticata|Esqueceu|esqueci|Забыли|忘记|找回|Zapomenuté|lost|忘れた|忘れられた|忘れの方|재설정|찾기|help|فراموشی| را فراموش کرده اید|Восстановить|Unuttu|perdus|重新設定|recover|remind|request|restore|trouble|olvidada/i;
const continueRegex =
  /continue|go on|weiter|fortfahren|ga verder|next|continuar/i;
const rememberMeRegex =
  /remember|stay|speichern|merken|bleiben|auto_login|auto-login|auto login|ricordami|manter|mantenha|savelogin|keep me logged in|keep me signed in|save email address|save id|stay signed in|次回からログオンIDの入力を省略する|メールアドレスを保存する|を保存|아이디저장|아이디 저장|로그인 상태 유지|lembrar|mantenha-me conectado|Запомни меня|запомнить меня|Запомните меня|Не спрашивать в следующий раз|下次自动登录|记住我|recordar|angemeldet bleiben/i;
const alreadySignedUpRegex = /already|bereits|schon|ya tienes cuenta/i;
const editProfile = /edit/i;

function createRuleset(coeffs, biases) {
  let descendantsCache;
  let surroundingNodesCache;

  /**
   * Check document characteristics
   */
  function docTitleMatchesRegisterRegex(fnode) {
    const docTitle = fnode.element.ownerDocument.title;
    return checkValueAgainstRegex(docTitle, registerRegex);
  }
  function docTitleMatchesEditProfileRegex(fnode) {
    const docTitle = fnode.element.ownerDocument.title;
    return checkValueAgainstRegex(docTitle, editProfile);
  }

  /**
   * Check header
   */
  function closestHeaderMatchesLoginRegex(fnode) {
    return closestHeaderMatchesPredicate(fnode.element, header =>
      checkValueAgainstRegex(header.innerText, loginRegex)
    );
  }
  function closestHeaderMatchesRegisterRegex(fnode) {
    return closestHeaderMatchesPredicate(fnode.element, header =>
      checkValueAgainstRegex(header.innerText, registerRegex)
    );
  }
  function closestHeaderMatchesSubscriptionRegex(fnode) {
    return closestHeaderMatchesPredicate(fnode.element, header =>
      checkValueAgainstRegex(header.innerText, subscriptionRegex)
    );
  }

  /**
   * Check checkboxes
   */
  function formHasRememberMeCheckbox(fnode) {
    return elementHasRegexMatchingCheckbox(fnode.element, rememberMeRegex);
  }
  function formHasSubcriptionCheckbox(fnode) {
    return elementHasRegexMatchingCheckbox(fnode.element, subscriptionRegex);
  }

  /**
   * Check input fields
   */
  function formHasFirstOrLastNameField(fnode) {
    const acValues = ["name", "given-name", "family-name"];
    return elementHasPredicateMatchingInput(
      fnode.element,
      elem =>
        atLeastOne(acValues.filter(ac => elem.autocomplete == ac)) ||
        inputFieldMatchesPredicate(elem, attr =>
          checkValueAgainstRegex(attr, nameRegex)
        )
    );
  }
  function formHasEmailField(fnode) {
    return elementHasPredicateMatchingInput(
      fnode.element,
      elem =>
        elem.autocomplete == "email" ||
        elem.type == "email" ||
        inputFieldMatchesPredicate(elem, attr =>
          checkValueAgainstRegex(attr, emailRegex)
        )
    );
  }
  function formHasUsernameField(fnode) {
    return elementHasPredicateMatchingInput(
      fnode.element,
      elem =>
        elem.autocomplete == "username" ||
        inputFieldMatchesPredicate(elem, attr =>
          checkValueAgainstRegex(attr, usernameRegex)
        )
    );
  }
  function formHasPasswordField(fnode) {
    const acValues = ["current-password", "new-password"];
    return elementHasPredicateMatchingInput(
      fnode.element,
      elem =>
        atLeastOne(acValues.filter(ac => elem.autocomplete == ac)) ||
        elem.type == "password"
    );
  }

  /**
   * Check autocomplete values
   */
  function formHasAcCurrentPassword(fnode) {
    return inputFieldMatchesSelector(
      fnode.element,
      "autocomplete=current-password"
    );
  }
  function formHasAcNewPassword(fnode) {
    return inputFieldMatchesSelector(
      fnode.element,
      "autocomplete=new-password"
    );
  }

  /**
   * Check hyperlinks within form
   */
  function formHasTermsAndConditionsHyperlink(fnode) {
    return elementHasPredicateMatchingHyperlink(
      fnode.element,
      termsAndConditionsRegex
    );
  }
  function formHasPasswordForgottenHyperlink(fnode) {
    return elementHasPredicateMatchingHyperlink(
      fnode.element,
      pwForgottenRegex
    );
  }
  function formHasAlreadySignedUpHyperlink(fnode) {
    return elementHasPredicateMatchingHyperlink(
      fnode.element,
      alreadySignedUpRegex
    );
  }

  /**
   * Check labels
   */
  function closestElementIsEmailLabelLike(fnode) {
    return elementHasPredicateMatchingInput(fnode.element, elem =>
      previousSiblingLabelMatchesRegex(elem, emailRegex)
    );
  }

  /**
   * Check buttons
   */
  function formHasRegisterButton(fnode) {
    return elementHasPredicateMatchingButton(
      fnode.element,
      button =>
        checkValueAgainstRegex(button.innerText, registerRegex) ||
        buttonMatchesPredicate(button, attr =>
          checkValueAgainstRegex(attr, registerRegex)
        )
    );
  }
  function formHasLoginButton(fnode) {
    return elementHasPredicateMatchingButton(
      fnode.element,
      button =>
        checkValueAgainstRegex(button.innerText, loginRegex) ||
        buttonMatchesPredicate(button, attr =>
          checkValueAgainstRegex(attr, loginRegex)
        )
    );
  }
  function formHasContinueButton(fnode) {
    return elementHasPredicateMatchingButton(
      fnode.element,
      button =>
        checkValueAgainstRegex(button.innerText, continueRegex) ||
        buttonMatchesPredicate(button, attr =>
          checkValueAgainstRegex(attr, continueRegex)
        )
    );
  }
  function formHasSubscribeButton(fnode) {
    return elementHasPredicateMatchingButton(
      fnode.element,
      button =>
        checkValueAgainstRegex(button.innerText, subscriptionRegex) ||
        buttonMatchesPredicate(button, attr =>
          checkValueAgainstRegex(attr, subscriptionRegex)
        )
    );
  }

  /**
   * Check form attributes
   */
  function formAttributesMatchRegisterRegex(fnode) {
    return formMatchesPredicate(fnode.element, attr =>
      checkValueAgainstRegex(attr, registerRegex)
    );
  }
  function formAttributesMatchLoginRegex(fnode) {
    return formMatchesPredicate(fnode.element, attr =>
      checkValueAgainstRegex(attr, loginRegex)
    );
  }
  function formAttributesMatchSubscriptionRegex(fnode) {
    return formMatchesPredicate(fnode.element, attr =>
      checkValueAgainstRegex(attr, subscriptionRegex)
    );
  }
  function formAttributesMatchLoginAndRegisterRegex(fnode) {
    return formMatchesPredicate(fnode.element, attr =>
      checkValueAgainstAllRegex(attr, [registerRegex, loginRegex])
    );
  }

  /**
   * HELPER FUNCTIONS
   */
  function elementMatchesPredicate(element, predicate, additional = []) {
    return attributesMatch(
      element,
      predicate,
      ["id", "name", "className"].concat(additional)
    );
  }
  function formMatchesPredicate(element, predicate) {
    return elementMatchesPredicate(element, predicate, ["action"]);
  }
  function inputFieldMatchesPredicate(element, predicate) {
    return elementMatchesPredicate(element, predicate, ["placeholder"]);
  }
  function inputFieldMatchesSelector(element, selector) {
    return atLeastOne(getElementDescendants(element, `input[${selector}]`));
  }
  function buttonMatchesPredicate(element, predicate) {
    return elementMatchesPredicate(element, predicate, [
      "value",
      "id",
      "title",
    ]);
  }
  function elementHasPredicateMatchingDescendant(element, selector, predicate) {
    const matchingElements = getElementDescendants(element, selector);
    return matchingElements.some(predicate);
  }
  function elementHasPredicateMatchingHeader(element, predicate) {
    return (
      elementHasPredicateMatchingDescendant(
        element,
        "h1,h2,h3,h4,h5,h6",
        predicate
      ) ||
      elementHasPredicateMatchingDescendant(
        element,
        "div[class*=heading],div[class*=header],div[class*=title],header",
        predicate
      )
    );
  }
  function elementHasPredicateMatchingButton(element, predicate) {
    return elementHasPredicateMatchingDescendant(
      element,
      "button,input[type=submit],input[type=button]",
      predicate
    );
  }
  function elementHasPredicateMatchingInput(element, predicate) {
    return elementHasPredicateMatchingDescendant(element, "input", predicate);
  }
  function elementHasPredicateMatchingHyperlink(element, regexExp) {
    return elementHasPredicateMatchingDescendant(
      element,
      "a",
      link =>
        previousSiblingLabelMatchesRegex(link, regexExp) ||
        checkValueAgainstRegex(link.innerText, regexExp) ||
        elementMatchesPredicate(
          link,
          attr => checkValueAgainstRegex(attr, regexExp),
          ["href"]
        ) ||
        nextSiblingLabelMatchesRegex(link, regexExp)
    );
  }
  function elementHasRegexMatchingCheckbox(element, regexExp) {
    return elementHasPredicateMatchingDescendant(
      element,
      "input[type=checkbox], div[class*=checkbox]",
      box =>
        elementMatchesPredicate(box, attr =>
          checkValueAgainstRegex(attr, regexExp)
        ) || nextSiblingLabelMatchesRegex(box, regexExp)
    );
  }

  function nextSiblingLabelMatchesRegex(element, regexExp) {
    let nextElem = element.nextElementSibling;
    if (nextElem && nextElem.tagName == "LABEL") {
      return checkValueAgainstRegex(nextElem.innerText, regexExp);
    }
    let closestElem = closestElementFollowing(element, "label");
    return closestElem
      ? checkValueAgainstRegex(closestElem.innerText, regexExp)
      : false;
  }

  function previousSiblingLabelMatchesRegex(element, regexExp) {
    let previousElem = element.previousElementSibling;
    if (previousElem && previousElem.tagName == "LABEL") {
      return checkValueAgainstRegex(previousElem.innerText, regexExp);
    }
    let closestElem = closestElementPreceding(element, "label");
    return closestElem
      ? checkValueAgainstRegex(closestElem.innerText, regexExp)
      : false;
  }
  function getElementDescendants(element, selector) {
    const selectorToDescendants = setDefault(
      descendantsCache,
      element,
      () => new Map()
    );

    return setDefault(selectorToDescendants, selector, () =>
      Array.from(element.querySelectorAll(selector))
    );
  }

  function clearCache() {
    descendantsCache = new WeakMap();
    surroundingNodesCache = new WeakMap();
  }
  function closestHeaderMatchesPredicate(element, predicate) {
    return (
      elementHasPredicateMatchingHeader(element, predicate) ||
      closestHeaderAboveMatchesPredicate(element, predicate)
    );
  }
  function closestHeaderAboveMatchesPredicate(element, predicate) {
    let closestHeader = closestElementPreceding(element, "h1,h2,h3,h4,h5,h6");

    if (closestHeader !== null) {
      if (predicate(closestHeader)) {
        return true;
      }
    }
    closestHeader = closestElementPreceding(
      element,
      "div[class*=heading],div[class*=header],div[class*=title],header"
    );
    return closestHeader ? predicate(closestHeader) : false;
  }
  function closestElementPreceding(element, selector) {
    return getSurroundingNodes(element, selector).precedingNode;
  }
  function closestElementFollowing(element, selector) {
    return getSurroundingNodes(element, selector).followingNode;
  }
  function getSurroundingNodes(element, selector) {
    const selectorToSurroundingNodes = setDefault(
      surroundingNodesCache,
      element,
      () => new Map()
    );

    return setDefault(selectorToSurroundingNodes, selector, () => {
      let elements = getElementDescendants(element.ownerDocument, selector);
      let followingIndex = closestFollowingNodeIndex(elements, element);
      let precedingIndex = followingIndex - 1;
      let preceding = precedingIndex < 0 ? null : elements[precedingIndex];
      let following =
        followingIndex == elements.length ? null : elements[followingIndex];
      return { precedingNode: preceding, followingNode: following };
    });
  }
  function closestFollowingNodeIndex(elements, element) {
    let low = 0;
    let high = elements.length;
    while (low < high) {
      let i = (low + high) >>> 1;
      if (
        element.compareDocumentPosition(elements[i]) &
        Node.DOCUMENT_POSITION_PRECEDING
      ) {
        low = i + 1;
      } else {
        high = i;
      }
    }
    return low;
  }

  function checkValueAgainstAllRegex(value, regexExp = []) {
    return regexExp.every(reg => checkValueAgainstRegex(value, reg));
  }

  function checkValueAgainstRegex(value, regexExp) {
    return value ? regexExp.test(value) : false;
  }
  function atLeastOne(iter) {
    return iter.length >= 1;
  }

  /**
   * CREATION OF RULESET
   */
  const rules = ruleset(
    [
      rule(
        DEVELOPMENT ? dom("form").when(isVisible) : element("form"),
        type("form").note(clearCache)
      ),
      // Check form attributes
      rule(type("form"), score(formAttributesMatchRegisterRegex), {
        name: "formAttributesMatchRegisterRegex",
      }),
      rule(type("form"), score(formAttributesMatchLoginRegex), {
        name: "formAttributesMatchLoginRegex",
      }),
      rule(type("form"), score(formAttributesMatchSubscriptionRegex), {
        name: "formAttributesMatchSubscriptionRegex",
      }),
      rule(type("form"), score(formAttributesMatchLoginAndRegisterRegex), {
        name: "formAttributesMatchLoginAndRegisterRegex",
      }),
      // Check autocomplete attributes
      rule(type("form"), score(formHasAcCurrentPassword), {
        name: "formHasAcCurrentPassword",
      }),
      rule(type("form"), score(formHasAcNewPassword), {
        name: "formHasAcNewPassword",
      }),
      // Check input fields
      rule(type("form"), score(formHasEmailField), {
        name: "formHasEmailField",
      }),
      rule(type("form"), score(formHasUsernameField), {
        name: "formHasUsernameField",
      }),
      rule(type("form"), score(formHasPasswordField), {
        name: "formHasPasswordField",
      }),
      rule(type("form"), score(formHasFirstOrLastNameField), {
        name: "formHasFirstOrLastNameField",
      }),
      // Check buttons
      rule(type("form"), score(formHasRegisterButton), {
        name: "formHasRegisterButton",
      }),
      rule(type("form"), score(formHasLoginButton), {
        name: "formHasLoginButton",
      }),
      rule(type("form"), score(formHasContinueButton), {
        name: "formHasContinueButton",
      }),
      rule(type("form"), score(formHasSubscribeButton), {
        name: "formHasSubscribeButton",
      }),
      // Check hyperlinks
      rule(type("form"), score(formHasTermsAndConditionsHyperlink), {
        name: "formHasTermsAndConditionsHyperlink",
      }),
      rule(type("form"), score(formHasPasswordForgottenHyperlink), {
        name: "formHasPasswordForgottenHyperlink",
      }),
      rule(type("form"), score(formHasAlreadySignedUpHyperlink), {
        name: "formHasAlreadySignedUpHyperlink",
      }),
      // Check labels
      rule(type("form"), score(closestElementIsEmailLabelLike), {
        name: "closestElementIsEmailLabelLike",
      }),
      // Check checkboxes
      rule(type("form"), score(formHasRememberMeCheckbox), {
        name: "formHasRememberMeCheckbox",
      }),
      rule(type("form"), score(formHasSubcriptionCheckbox), {
        name: "formHasSubcriptionCheckbox",
      }),
      // Check header
      rule(type("form"), score(closestHeaderMatchesRegisterRegex), {
        name: "closestHeaderMatchesRegisterRegex",
      }),
      rule(type("form"), score(closestHeaderMatchesLoginRegex), {
        name: "closestHeaderMatchesLoginRegex",
      }),
      rule(type("form"), score(closestHeaderMatchesSubscriptionRegex), {
        name: "closestHeaderMatchesSubscriptionRegex",
      }),
      // Check doc title
      rule(type("form"), score(docTitleMatchesRegisterRegex), {
        name: "docTitleMatchesRegisterRegex",
      }),
      rule(type("form"), score(docTitleMatchesEditProfileRegex), {
        name: "docTitleMatchesEditProfileRegex",
      }),
      rule(type("form"), out("form")),
    ],
    coeffs,
    biases
  );
  return rules;
}

/**
 * --- END OF CODE FROM TRAINING REPOSITORY ---
 */

export const SignUpFormRuleset = {
  type: "form",
  rules: createRuleset([...coefficients.form], biases),
};