forked from apple/password-manager-resources
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PasswordRulesParser.js
551 lines (459 loc) · 18.7 KB
/
PasswordRulesParser.js
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
// Copyright (c) 2019 - 2020 Apple Inc. Licensed under MIT License.
"use strict";
if (!console) {
console = {
assert: function() { },
error: function() { },
warn: function() { },
};
}
const Identifier = {
ASCII_PRINTABLE: "ascii-printable",
DIGIT: "digit",
LOWER: "lower",
SPECIAL: "special",
UNICODE: "unicode",
UPPER: "upper",
};
const RuleName = {
ALLOWED: "allowed",
MAX_CONSECUTIVE: "max-consecutive",
REQUIRED: "required",
MIN_LENGTH: "minlength",
MAX_LENGTH: "maxlength",
};
const CHARACTER_CLASS_START_SENTINEL = "[";
const CHARACTER_CLASS_END_SENTINEL = "]";
const PROPERTY_VALUE_SEPARATOR = ",";
const PROPERTY_SEPARATOR = ";";
const PROPERTY_VALUE_START_SENTINEL = ":";
const SPACE_CODE_POINT = " ".codePointAt(0);
const SHOULD_NOT_BE_REACHED = "Should not be reached";
class Rule {
constructor(name, value)
{
this._name = name;
this.value = value;
}
get name() { return this._name; }
toString() { return JSON.stringify(this); }
};
class NamedCharacterClass {
constructor(name)
{
console.assert(_isValidRequiredOrAllowedPropertyValueIdentifier(name));
this._name = name;
}
get name() { return this._name.toLowerCase(); }
toString() { return this._name; }
toHTMLString() { return this._name; }
};
class CustomCharacterClass {
constructor(characters)
{
console.assert(characters instanceof Array);
this._characters = characters;
}
get characters() { return this._characters; }
toString() { return `[${this._characters.join("")}]`; }
toHTMLString() { return `[${this._characters.join("").replace('"', """)}]`; }
};
// MARK: Lexer functions
function _isIdentifierCharacter(c)
{
console.assert(c.length === 1);
return c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c === "-";
}
function _isASCIIDigit(c)
{
console.assert(c.length === 1);
return c >= "0" && c <= "9";
}
function _isASCIIPrintableCharacter(c)
{
console.assert(c.length === 1);
return c >= " " && c <= "~";
}
function _isASCIIWhitespace(c)
{
console.assert(c.length === 1);
return c === " " || c === "\f" || c === "\n" || c === "\r" || c === "\t";
}
// MARK: ASCII printable character bit set and canonicalization functions
function _bitSetIndexForCharacter(c)
{
console.assert(c.length == 1);
return c.codePointAt(0) - SPACE_CODE_POINT;
}
function _characterAtBitSetIndex(index)
{
return String.fromCodePoint(index + SPACE_CODE_POINT);
}
function _markBitsForNamedCharacterClass(bitSet, namedCharacterClass)
{
console.assert(bitSet instanceof Array);
console.assert(namedCharacterClass.name !== Identifier.UNICODE);
console.assert(namedCharacterClass.name !== Identifier.ASCII_PRINTABLE);
if (namedCharacterClass.name === Identifier.UPPER)
bitSet.fill(true, _bitSetIndexForCharacter("A"), _bitSetIndexForCharacter("Z") + 1);
else if (namedCharacterClass.name === Identifier.LOWER)
bitSet.fill(true, _bitSetIndexForCharacter("a"), _bitSetIndexForCharacter("z") + 1);
else if (namedCharacterClass.name === Identifier.DIGIT)
bitSet.fill(true, _bitSetIndexForCharacter("0"), _bitSetIndexForCharacter("9") + 1);
else if (namedCharacterClass.name === Identifier.SPECIAL) {
bitSet.fill(true, _bitSetIndexForCharacter(" "), _bitSetIndexForCharacter("/") + 1);
bitSet.fill(true, _bitSetIndexForCharacter(":"), _bitSetIndexForCharacter("@") + 1);
bitSet.fill(true, _bitSetIndexForCharacter("["), _bitSetIndexForCharacter("`") + 1);
bitSet.fill(true, _bitSetIndexForCharacter("{"), _bitSetIndexForCharacter("~") + 1);
} else
console.assert(false, SHOULD_NOT_BE_REACHED, namedCharacterClass);
}
function _markBitsForCustomCharacterClass(bitSet, customCharacterClass)
{
for (let character of customCharacterClass.characters)
bitSet[_bitSetIndexForCharacter(character)] = true;
}
function _canonicalizedPropertyValues(propertyValues, keepCustomCharacterClassFormatCompliant)
{
let asciiPrintableBitSet = new Array("~".codePointAt(0) - " ".codePointAt(0) + 1);
for (let propertyValue of propertyValues) {
if (propertyValue instanceof NamedCharacterClass) {
if (propertyValue.name === Identifier.UNICODE)
return [new NamedCharacterClass(Identifier.UNICODE)];
if (propertyValue.name === Identifier.ASCII_PRINTABLE)
return [new NamedCharacterClass(Identifier.ASCII_PRINTABLE)];
_markBitsForNamedCharacterClass(asciiPrintableBitSet, propertyValue);
} else if (propertyValue instanceof CustomCharacterClass)
_markBitsForCustomCharacterClass(asciiPrintableBitSet, propertyValue);
}
let charactersSeen = [];
function checkRange(start, end) {
let temp = [];
for (let i = _bitSetIndexForCharacter(start); i <= _bitSetIndexForCharacter(end); ++i) {
if (asciiPrintableBitSet[i])
temp.push(_characterAtBitSetIndex(i));
}
let result = temp.length === (_bitSetIndexForCharacter(end) - _bitSetIndexForCharacter(start) + 1);
if (!result)
charactersSeen = charactersSeen.concat(temp);
return result;
}
let hasAllUpper = checkRange("A", "Z");
let hasAllLower = checkRange("a", "z");
let hasAllDigits = checkRange("0", "9");
// Check for special characters, accounting for characters that are given special treatment (i.e. '-' and ']')
let hasAllSpecial = false;
let hasDash = false;
let hasRightSquareBracket = false;
let temp = [];
for (let i = _bitSetIndexForCharacter(" "); i <= _bitSetIndexForCharacter("/"); ++i) {
if (!asciiPrintableBitSet[i])
continue;
let character = _characterAtBitSetIndex(i);
if (keepCustomCharacterClassFormatCompliant && character === "-")
hasDash = true;
else
temp.push(character);
}
for (let i = _bitSetIndexForCharacter(":"); i <= _bitSetIndexForCharacter("@"); ++i) {
if (asciiPrintableBitSet[i])
temp.push(_characterAtBitSetIndex(i));
}
for (let i = _bitSetIndexForCharacter("["); i <= _bitSetIndexForCharacter("`"); ++i) {
if (!asciiPrintableBitSet[i])
continue;
let character = _characterAtBitSetIndex(i);
if (keepCustomCharacterClassFormatCompliant && character === "]")
hasRightSquareBracket = true;
else
temp.push(character);
}
for (let i = _bitSetIndexForCharacter("{"); i <= _bitSetIndexForCharacter("~"); ++i) {
if (asciiPrintableBitSet[i])
temp.push(_characterAtBitSetIndex(i));
}
if (hasDash)
temp.unshift("-");
if (hasRightSquareBracket)
temp.push("]");
let numberOfSpecialCharacters = (_bitSetIndexForCharacter("/") - _bitSetIndexForCharacter(" ") + 1)
+ (_bitSetIndexForCharacter("@") - _bitSetIndexForCharacter(":") + 1)
+ (_bitSetIndexForCharacter("`") - _bitSetIndexForCharacter("[") + 1)
+ (_bitSetIndexForCharacter("~") - _bitSetIndexForCharacter("{") + 1);
hasAllSpecial = temp.length === numberOfSpecialCharacters;
if (!hasAllSpecial)
charactersSeen = charactersSeen.concat(temp);
let result = [];
if (hasAllUpper && hasAllLower && hasAllDigits && hasAllSpecial)
return [new NamedCharacterClass(Identifier.ASCII_PRINTABLE)];
if (hasAllUpper)
result.push(new NamedCharacterClass(Identifier.UPPER));
if (hasAllLower)
result.push(new NamedCharacterClass(Identifier.LOWER));
if (hasAllDigits)
result.push(new NamedCharacterClass(Identifier.DIGIT));
if (hasAllSpecial)
result.push(new NamedCharacterClass(Identifier.SPECIAL));
if (charactersSeen.length)
result.push(new CustomCharacterClass(charactersSeen));
return result;
}
// MARK: Parser functions
function _indexOfNonWhitespaceCharacter(input, position = 0)
{
console.assert(position >= 0);
console.assert(position <= input.length);
let length = input.length;
while (position < length && _isASCIIWhitespace(input[position]))
++position;
return position;
}
function _parseIdentifier(input, position)
{
console.assert(position >= 0);
console.assert(position < input.length);
console.assert(_isIdentifierCharacter(input[position]));
let length = input.length;
let seenIdentifiers = [];
do {
let c = input[position];
if (!_isIdentifierCharacter(c))
break;
seenIdentifiers.push(c);
++position;
} while (position < length);
return [seenIdentifiers.join(""), position];
}
function _isValidRequiredOrAllowedPropertyValueIdentifier(identifier)
{
return identifier && Object.values(Identifier).includes(identifier.toLowerCase());
}
function _parseCustomCharacterClass(input, position)
{
console.assert(position >= 0);
console.assert(position < input.length);
console.assert(input[position] === CHARACTER_CLASS_START_SENTINEL);
let length = input.length;
++position;
if (position >= length) {
console.error("Found end-of-line instead of character class character");
return [null, position];
}
let initialPosition = position;
let result = [];
do {
let c = input[position];
if (!_isASCIIPrintableCharacter(c)) {
++position;
continue;
}
if (c === "-" && (position - initialPosition) > 0) {
// FIXME: Should this be an error?
console.warn("Ignoring '-'; a '-' may only appear as the first character in a character class");
++position;
continue;
}
result.push(c);
++position;
if (c === CHARACTER_CLASS_END_SENTINEL)
break;
} while (position < length);
if (position < length && input[position] !== CHARACTER_CLASS_END_SENTINEL || position == length && input[position - 1] == CHARACTER_CLASS_END_SENTINEL) {
// Fix up result; we over consumed.
result.pop();
return [result, position];
}
if (position < length && input[position] == CHARACTER_CLASS_END_SENTINEL)
return [result, position + 1];
console.error("Found end-of-line instead of end of character class");
return [null, position];
}
function _parsePasswordRequiredOrAllowedPropertyValue(input, position)
{
console.assert(position >= 0);
console.assert(position < input.length);
let length = input.length;
let propertyValues = [];
while (true) {
if (_isIdentifierCharacter(input[position])) {
let identifierStartPosition = position;
var [propertyValue, position] = _parseIdentifier(input, position);
if (!_isValidRequiredOrAllowedPropertyValueIdentifier(propertyValue)) {
console.error("Unrecognized property value identifier: " + propertyValue);
return [null, identifierStartPosition];
}
propertyValues.push(new NamedCharacterClass(propertyValue));
} else if (input[position] == CHARACTER_CLASS_START_SENTINEL) {
var [propertyValue, position] = _parseCustomCharacterClass(input, position);
if (propertyValue && propertyValue.length)
propertyValues.push(new CustomCharacterClass(propertyValue));
} else {
console.error("Failed to find start of property value: " + input.substr(position));
return [null, position];
}
position = _indexOfNonWhitespaceCharacter(input, position);
if (position >= length || input[position] === PROPERTY_SEPARATOR)
break;
if (input[position] === PROPERTY_VALUE_SEPARATOR) {
position = _indexOfNonWhitespaceCharacter(input, position + 1);
if (position >= length) {
console.error("Found end-of-line instead of start of next property value");
return [null, position];
}
continue;
}
console.error("Failed to find start of next property or property value: " + input.substr(position));
return [null, position];
}
return [propertyValues, position];
}
function _parsePasswordRule(input, position)
{
console.assert(position >= 0);
console.assert(position < input.length);
console.assert(_isIdentifierCharacter(input[position]));
let length = input.length;
var mayBeIdentifierStartPosition = position;
var [identifier, position] = _parseIdentifier(input, position);
if (!Object.values(RuleName).includes(identifier)) {
console.error("Unrecognized property name: " + identifier);
return [null, mayBeIdentifierStartPosition];
}
if (position >= length) {
console.error("Found end-of-line instead of start of property value");
return [null, position];
}
if (input[position] !== PROPERTY_VALUE_START_SENTINEL) {
console.error("Failed to find start of property value: " + input.substr(position));
return [null, position];
}
let property = { name: identifier, value: null };
position = _indexOfNonWhitespaceCharacter(input, position + 1);
// Empty value
if (position >= length || input[position] === PROPERTY_SEPARATOR)
return [new Rule(property.name, property.value), position];
switch (identifier) {
case RuleName.ALLOWED:
case RuleName.REQUIRED: {
var [propertyValue, position] = _parsePasswordRequiredOrAllowedPropertyValue(input, position);
if (propertyValue)
property.value = propertyValue;
return [new Rule(property.name, property.value), position];
}
case RuleName.MAX_CONSECUTIVE: {
var [propertyValue, position] = _parseMaxConsecutivePropertyValue(input, position);
if (propertyValue)
property.value = propertyValue;
return [new Rule(property.name, property.value), position];
}
case RuleName.MIN_LENGTH:
case RuleName.MAX_LENGTH: {
var [propertyValue, position] = _parseMinLengthMaxLengthPropertyValue(input, position);
if (propertyValue)
property.value = propertyValue;
return [new Rule(property.name, property.value), position];
}
}
console.assert(false, SHOULD_NOT_BE_REACHED);
}
function _parseMinLengthMaxLengthPropertyValue(input, position)
{
return _parseInteger(input, position);
}
function _parseMaxConsecutivePropertyValue(input, position)
{
return _parseInteger(input, position);
}
function _parseInteger(input, position)
{
console.assert(position >= 0);
console.assert(position < input.length);
if (!_isASCIIDigit(input[position])) {
console.error("Failed to parse value of type integer; not a number: " + input.substr(position));
return [null, position];
}
let length = input.length;
let initialPosition = position;
let result = 0;
do {
result = 10 * result + parseInt(input[position], 10);
++position;
} while (position < length && input[position] !== PROPERTY_SEPARATOR && _isASCIIDigit(input[position]));
if (position >= length || input[position] === PROPERTY_SEPARATOR)
return [result, position];
console.error("Failed to parse value of type integer; not a number: " + input.substr(initialPosition));
return [null, position];
}
function _parsePasswordRulesInternal(input)
{
let parsedProperties = [];
let length = input.length;
var position = _indexOfNonWhitespaceCharacter(input);
while (position < length) {
if (!_isIdentifierCharacter(input[position])) {
console.warn("Failed to find start of property: " + input.substr(position));
return parsedProperties;
}
var [parsedProperty, position] = _parsePasswordRule(input, position)
if (parsedProperty && parsedProperty.value)
parsedProperties.push(parsedProperty);
position = _indexOfNonWhitespaceCharacter(input, position);
if (position >= length)
break;
if (input[position] === PROPERTY_SEPARATOR) {
position = _indexOfNonWhitespaceCharacter(input, position + 1);
if (position >= length)
return parsedProperties;
continue;
}
console.error("Failed to find start of next property: " + input.substr(position));
return null;
}
return parsedProperties;
}
function parsePasswordRules(input, formatRulesForMinifiedVersion)
{
let passwordRules = _parsePasswordRulesInternal(input) || [];
// When formatting rules for minified version, we should keep the formatted rules
// as similar to the input as possible. Avoid copying required rules to allowed rules.
let suppressCopyingRequiredToAllowed = formatRulesForMinifiedVersion;
let newPasswordRules = [];
let newAllowedValues = [];
let minimumMaximumConsecutiveCharacters = null;
let maximumMinLength = 0;
let minimumMaxLength = null;
for (let rule of passwordRules) {
switch (rule.name) {
case RuleName.MAX_CONSECUTIVE:
minimumMaximumConsecutiveCharacters = minimumMaximumConsecutiveCharacters ? Math.min(rule.value, minimumMaximumConsecutiveCharacters) : rule.value;
break;
case RuleName.MIN_LENGTH:
maximumMinLength = Math.max(rule.value, maximumMinLength);
break;
case RuleName.MAX_LENGTH:
minimumMaxLength = minimumMaxLength ? Math.min(rule.value, minimumMaxLength) : rule.value;
break;
case RuleName.REQUIRED:
rule.value = _canonicalizedPropertyValues(rule.value, formatRulesForMinifiedVersion);
newPasswordRules.push(rule);
if (!suppressCopyingRequiredToAllowed)
newAllowedValues = newAllowedValues.concat(rule.value);
break;
case RuleName.ALLOWED:
newAllowedValues = newAllowedValues.concat(rule.value);
break;
}
}
newAllowedValues = _canonicalizedPropertyValues(newAllowedValues, suppressCopyingRequiredToAllowed);
if (!suppressCopyingRequiredToAllowed && !newAllowedValues.length)
newAllowedValues = [new NamedCharacterClass(Identifier.ASCII_PRINTABLE)];
if (newAllowedValues.length)
newPasswordRules.push(new Rule(RuleName.ALLOWED, newAllowedValues));
if (minimumMaximumConsecutiveCharacters !== null)
newPasswordRules.push(new Rule(RuleName.MAX_CONSECUTIVE, minimumMaximumConsecutiveCharacters));
if (maximumMinLength > 0)
newPasswordRules.push(new Rule(RuleName.MIN_LENGTH, maximumMinLength));
if (minimumMaxLength !== null)
newPasswordRules.push(new Rule(RuleName.MAX_LENGTH, minimumMaxLength));
return newPasswordRules;
}