kryptheon 0.1.64 → 0.1.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/kryptheon-map.js CHANGED
@@ -345,7 +345,18 @@ function resolveRef(ctx, mod, p, depth = 0, seen = new Set()) {
345
345
  }
346
346
 
347
347
  /** What a binding names, as a path resolveRef can follow: a declaration's value, an import's local name, a function. */
348
- const bindingTarget = (b) => (b.path.isVariableDeclarator() ? b.path.get('init') : b.path.isImportSpecifier() || b.path.isImportDefaultSpecifier() || b.path.isImportNamespaceSpecifier() ? b.path.get('local') : b.path);
348
+ const bindingTarget = (b) => {
349
+ if (b.path.isVariableDeclarator()) {
350
+ // const { sameHex } = require('./sig'): the name inside the pattern, which resolveRef follows into that file - not the
351
+ // whole module (round 33: an app's own compare helper was not followed, and a real signature check read as none)
352
+ if (b.path.node.id && b.path.node.id.type === 'ObjectPattern') {
353
+ const hit = b.path.get('id.properties').find((q) => q.isObjectProperty() && q.get('value').isIdentifier({ name: b.identifier.name }));
354
+ if (hit) return hit.get('value');
355
+ }
356
+ return b.path.get('init');
357
+ }
358
+ return b.path.isImportSpecifier() || b.path.isImportDefaultSpecifier() || b.path.isImportNamespaceSpecifier() ? b.path.get('local') : b.path;
359
+ };
349
360
 
350
361
  const calleeText = (p) => (memberChain(p.node.callee) || ['(call)']).join('.');
351
362
 
@@ -826,6 +837,12 @@ function readGuardFn(ctx, ref, opts = {}) {
826
837
  if (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') {
827
838
  const chain = memberChain(n);
828
839
  if (chain && ROLE_SEGS.test(chain[chain.length - 1]) && (identityChain(n.object) || identityLocals.has(chain[0]))) return true;
840
+ // user(req).role: the role of whoever a helper says is calling. Found on
841
+ // blind round 30 (StudioPulse): permit(resource, action) compared
842
+ // user(req).role with permissions-policy.json and the map said no route
843
+ // checked a role.
844
+ const prop = !n.computed && n.property ? n.property.name : n.property && n.property.type === 'StringLiteral' ? n.property.value : null;
845
+ if (prop && ROLE_SEGS.test(prop) && (n.object.type === 'CallExpression' || n.object.type === 'OptionalCallExpression') && isIdentityNode(n.object)) return true;
829
846
  }
830
847
  if (n.type === 'Identifier' && roleLocals.has(n.name)) return true;
831
848
  if (n.type === 'CallExpression' || n.type === 'OptionalCallExpression') {
@@ -1045,7 +1062,18 @@ function readGuardFn(ctx, ref, opts = {}) {
1045
1062
  else if (id && mixed) out.authPartial = out.authPartial || ev('a sign-in check that applies only in some cases');
1046
1063
  else if (!s && !k && !present) anyOther = true;
1047
1064
  }
1048
- if (anyRole) out.role = out.role || Object.assign(ev('turns away a role that is not allowed'), { roles: roleList.length ? roleList : rolesIn(t, testNode) });
1065
+ if (anyRole && !out.role) {
1066
+ // requireRole('admin'): the factory's words are roles when the check compares
1067
+ // with them. permit('products', 'read') looks a rule up instead (blind round
1068
+ // 30): its words name a permission, and the roles are in the policy file.
1069
+ const comparesList = roleList.length && refersTo(testNode, (x) => x.type === 'Identifier' && factoryParams.includes(x.name));
1070
+ const looksLikePermission = roleList.length && (roleList.some((a) => /[.:]/.test(a)) ||
1071
+ (roleList.length === 2 && /^(read|write|create|update|delete|destroy|remove|manage|approve|view|edit|list|export|refund|admin)$/i.test(roleList[1])));
1072
+ const asPermission = looksLikePermission && !comparesList;
1073
+ const found = roleList.length && !asPermission ? roleList : rolesIn(t, testNode);
1074
+ out.role = Object.assign(ev('turns away a role that is not allowed'), found.length ? { roles: found } : {},
1075
+ asPermission ? { permission: roleList.join('.') } : {});
1076
+ }
1049
1077
  if (anyIdentity || (anyRole && !out.auth)) {
1050
1078
  if (anyIdentity) out.auth = out.auth || ev('turns away a request with nobody signed in');
1051
1079
  }
@@ -1299,6 +1327,7 @@ function judge(route, elements) {
1299
1327
  out.partial = partial;
1300
1328
  const roleEv = out.role.evidence;
1301
1329
  if (roleEv && roleEv.roles) out.role.roles = roleEv.roles;
1330
+ if (roleEv && roleEv.permission) out.role.permission = roleEv.permission;
1302
1331
  return out;
1303
1332
  }
1304
1333
 
@@ -2081,6 +2110,104 @@ function scopeVerdict(mod, line, st, filters, insertCols, schema, via, partlyUnr
2081
2110
  return Object.assign(base, { scoping: { status: STATUS.NOT, applies: true, why: (isInsert ? 'the row is written without an organisation or owner column' : 'no organisation or owner limit in the statement') } });
2082
2111
  }
2083
2112
 
2113
+ // --- redirects: an address the request names, sent back as Location -------------------------
2114
+
2115
+ const REQUEST_PARTS = /^(query|body|params|headers|cookies)$/;
2116
+ const CHECKS_A_PLACE = /^(startsWith|endsWith|test|match|includes|indexOf|has|isSafe\w*|isLocal\w*|isAllowed\w*|isRelative\w*|isValid\w*)$/;
2117
+
2118
+ /**
2119
+ * Redirects whose address comes from the request with nothing testing it first: res.redirect(req.query.next || '/').
2120
+ * One that passes the value through a test (startsWith('/'), a regex, an allow list, new URL(...).origin)
2121
+ * before it is used is left alone. Found on blind round 32 (Northstar): the sign-in answered 302 to any
2122
+ * address given as ?next=. [{ line, code, field, from }]
2123
+ */
2124
+ function readRedirects(ctx, fnRef) {
2125
+ const t = ctx.t;
2126
+ const fn = fnRef && fnRef.path;
2127
+ if (!fn || !fn.node || !fn.node.params) return [];
2128
+ const p0 = fn.node.params[0];
2129
+ const p1 = fn.node.params[1];
2130
+ const reqName = p0 && p0.type === 'Identifier' ? p0.name : null;
2131
+ const resName = p1 && p1.type === 'Identifier' ? p1.name : null;
2132
+ if (!reqName || !resName) return [];
2133
+ const mod = fnRef.mod;
2134
+ // tests anywhere in the handler: an if, a ternary, a && / || used as a condition
2135
+ const tests = [];
2136
+ fn.traverse({
2137
+ IfStatement(p) { tests.push(p.node.test); },
2138
+ ConditionalExpression(p) { tests.push(p.node.test); },
2139
+ CallExpression(p) {
2140
+ const name = calledName(p.node);
2141
+ if (CHECKS_A_PLACE.test(name)) tests.push(p.node);
2142
+ if ((name === 'URL' || (p.node.callee && p.node.callee.type === 'Identifier' && p.node.callee.name === 'URL'))) tests.push(p.node);
2143
+ },
2144
+ NewExpression(p) { if (p.node.callee && p.node.callee.type === 'Identifier' && p.node.callee.name === 'URL') tests.push(p.node); },
2145
+ });
2146
+ const mentions = (node, name) => {
2147
+ let hit = false;
2148
+ t.traverseFast(node, (x) => { if (x.type === 'Identifier' && x.name === name) hit = true; });
2149
+ return hit;
2150
+ };
2151
+ const tested = (name) => tests.some((n) => {
2152
+ if (!mentions(n, name)) return false;
2153
+ let isCheck = false;
2154
+ t.traverseFast(n, (x) => { if ((x.type === 'CallExpression' && (CHECKS_A_PLACE.test(calledName(x)) || calledName(x) === 'URL')) || x.type === 'NewExpression' || (x.type === 'BinaryExpression' && /^(===|!==|==|!=)$/.test(x.operator))) isCheck = true; });
2155
+ return isCheck;
2156
+ });
2157
+ // where a value comes from: { field, from } when it is the request's own, null otherwise; 'tested' when a test stands on the way
2158
+ const origin = (node, depth) => {
2159
+ if (!node || depth > 4) return null;
2160
+ if (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') {
2161
+ const chain = memberChain(node);
2162
+ if (chain && chain[0] === reqName && REQUEST_PARTS.test(chain[1] || '')) return { field: chain[2] || chain[1], from: chain[1] };
2163
+ return null;
2164
+ }
2165
+ if (node.type === 'LogicalExpression' && (node.operator === '||' || node.operator === '??')) return origin(node.left, depth + 1);
2166
+ if (node.type === 'ConditionalExpression') return 'tested';
2167
+ if (node.type === 'CallExpression') {
2168
+ const name = calledName(node);
2169
+ if (/^(String|decodeURIComponent|decodeURI|trim|toString)$/.test(name)) {
2170
+ const inner = node.arguments[0] || (node.callee && node.callee.object);
2171
+ return origin(inner, depth + 1);
2172
+ }
2173
+ return null;
2174
+ }
2175
+ if (node.type === 'TemplateLiteral' && node.expressions.length) {
2176
+ const head = node.quasis[0].value.cooked || '';
2177
+ if (/^\/[^/\\]/.test(head)) return null; // '/app/' + ... stays on this site
2178
+ return origin(node.expressions[0], depth + 1);
2179
+ }
2180
+ if (node.type === 'BinaryExpression' && node.operator === '+') {
2181
+ if (node.left.type === 'StringLiteral' && /^\/[^/\\]/.test(node.left.value)) return null;
2182
+ return node.left.type === 'StringLiteral' ? origin(node.right, depth + 1) : origin(node.left, depth + 1);
2183
+ }
2184
+ if (node.type === 'Identifier') {
2185
+ if (tested(node.name)) return 'tested';
2186
+ const b = fn.scope.getBinding(node.name);
2187
+ if (!b || !b.path.isVariableDeclarator() || b.constantViolations.length) return null;
2188
+ return origin(b.path.node.init, depth + 1);
2189
+ }
2190
+ return null;
2191
+ };
2192
+ const out = [];
2193
+ fn.traverse({
2194
+ CallExpression(p) {
2195
+ const chain = memberChain(p.node.callee);
2196
+ if (!chain || chain[0] !== resName) return;
2197
+ let target = null;
2198
+ if (chain[1] === 'redirect') target = p.node.arguments[p.node.arguments.length - 1];
2199
+ else if (chain[1] === 'location') target = p.node.arguments[0];
2200
+ else if (/^(set|header|setHeader)$/.test(chain[1] || '') && p.node.arguments[0] && p.node.arguments[0].type === 'StringLiteral' && /^location$/i.test(p.node.arguments[0].value)) target = p.node.arguments[1];
2201
+ if (!target) return;
2202
+ const o = origin(target, 0);
2203
+ if (!o || o === 'tested') return;
2204
+ const line = p.node.loc ? p.node.loc.start.line : null;
2205
+ out.push({ line: line, code: line && mod ? snippet(mod, line) : '', field: o.field, from: o.from, file: mod ? mod.rel : null });
2206
+ },
2207
+ });
2208
+ return out;
2209
+ }
2210
+
2084
2211
  /** The handler of a route: the last element in front of it that is the app's own code. */
2085
2212
  function handlerOf(r) {
2086
2213
  for (let i = r.chain.length - 1; i >= 0; i--) if (r.chain[i].ref.kind === 'fn' && !r.chain[i].inherited) return r.chain[i].ref;
@@ -2194,6 +2321,10 @@ function readValidation(ctx, fnRef, elements, db) {
2194
2321
  const fs2 = fieldsIn(init);
2195
2322
  if (fs2.length === 1 && reshapes(init)) {
2196
2323
  localField.set(id.name, fs2[0]);
2324
+ // const delta = Number(req.body.delta): the code reads a number (round 33: sent as text, the route crashed and
2325
+ // nothing about the stock was ever tried)
2326
+ const conv = init.type === 'CallExpression' ? init : init.type === 'UnaryExpression' && init.operator === '+' ? { unary: true } : null;
2327
+ if (conv && (conv.unary || /^(Number|parseInt|parseFloat)$/.test((memberChain(conv.callee) || ['']).slice(-1)[0]))) note(fs2[0], q.node.loc.start.line).numeric = true;
2197
2328
  // Math.min(100, Math.max(1, Number(req.query.limit))): kept in bounds rather than turned away
2198
2329
  if (clamps(init)) note(fs2[0], q.node.loc.start.line).checks.push({ kind: 'clamped', file: mod.rel, line: q.node.loc.start.line, code: snippet(mod, q.node.loc.start.line) });
2199
2330
  }
@@ -2372,7 +2503,7 @@ function readValidation(ctx, fnRef, elements, db) {
2372
2503
  let status = e.checks.length ? STATUS.DETECTED : (e.schemaUnread || unread ? STATUS.UNKNOWN : STATUS.NOT);
2373
2504
  const items = itemNames.get(key(e.from, e.name));
2374
2505
  return Object.assign({ name: e.name, from: e.from, line: e.line, file: mod.rel, status, checks: e.checks, reachesWrite: e.reachesWrite || [], why: status === STATUS.UNKNOWN ? 'checked by a schema or middleware whose rules are not read' : null },
2375
- items && items.size ? { items: Array.from(items).sort() } : {});
2506
+ items && items.size ? { items: Array.from(items).sort() } : {}, e.numeric ? { numeric: true } : {});
2376
2507
  });
2377
2508
  return { fields: out.sort((a, b) => a.line - b.line), schemas };
2378
2509
  }
@@ -2893,6 +3024,7 @@ function mapProject(root, options) {
2893
3024
  const h = handlerOf(r);
2894
3025
  const db = h ? readDb(ctx, h, schema) : [];
2895
3026
  const validation = h ? readValidation(ctx, h, elements, db) : { fields: [], schemas: [], why: 'the handler could not be followed' };
3027
+ const redirects = h ? readRedirects(ctx, h) : [];
2896
3028
  return {
2897
3029
  method: r.method,
2898
3030
  path: r.path,
@@ -2907,6 +3039,7 @@ function mapProject(root, options) {
2907
3039
  partialChecks: g.partial,
2908
3040
  db,
2909
3041
  validation,
3042
+ redirects,
2910
3043
  };
2911
3044
  });
2912
3045
  routes.push(...edgeRoutes(ctx, root, schema));
@@ -2940,6 +3073,7 @@ const ADVICE = {
2940
3073
  'tenant-from-request': 'take the organisation from the signed-in person\'s session, never from the request body or query string; for an id the request sends, look the record up with the organisation condition before using it.',
2941
3074
  'tenant-unscoped': 'add the signed-in person\'s organisation (or owner) to the statement - WHERE org_id = <the session\'s org> - or, for a row found by its id, check that the row belongs to that organisation before using it.',
2942
3075
  'no-role': 'allow only the roles that should be able to do this, and answer 403 for the others.',
3076
+ 'open-redirect': 'send the browser only to an address on this site: accept a path that starts with a single "/" (not "//", not "/\\\\", no "http"), or a name from a fixed list of places, and fall back to "/" for anything else. Keep the rest of the route as it is.',
2943
3077
  'no-state-check': 'look at the record\'s status first and refuse the step when the record is not in the status it must come from (WHERE status = <the one before> in the same statement, or a check that answers 409). A second call must change nothing - no stock, money or log entry added again.',
2944
3078
  'identity-from-request': 'take who is calling only from something the server itself issued and can check - a signed session cookie (express-session, a signed JWT) - never from a bare user id in a cookie or a header the browser can set. Look the session up on the server and set req.user from that.',
2945
3079
  };
@@ -2983,6 +3117,10 @@ function toCheck(map) {
2983
3117
  }
2984
3118
  continue;
2985
3119
  }
3120
+ // an address the request names, sent back as the place to go: a link that signs a person in and lands them on another site
3121
+ for (const rd of r.redirects || []) {
3122
+ add(r, 'open-redirect', 'MEDIUM', name + ' sends the browser to the address in ' + rd.from + '.' + rd.field + ' with nothing checking it first: a link to your app can land people on any other site', [(rd.file || r.file) + ':' + rd.line + ' ' + rd.code]);
3123
+ }
2986
3124
  // a route with no sign-in that changes something - sign-in and sign-up routes are open by nature
2987
3125
  if (writes && r.auth.status === STATUS.NOT && changing.length && !AUTH_PATH.test(r.path || '')) {
2988
3126
  add(r, 'no-sign-in', 'HIGH', name + ' ' + tables(changing) + ', and no sign-in check was found in front of it', [r.file + ':' + r.line].concat(changing.slice(0, 3).map((d) => d.file + ':' + d.line + ' ' + d.sql)));
@@ -0,0 +1,87 @@
1
+ // Is a newer version of this package on npm?
2
+ //
3
+ // Someone who ran `npx kryptheon` once can keep getting that same copy
4
+ // from npx's cache, and a nightly check installed in a database never updates
5
+ // itself - so without this, a fix released later never reaches them.
6
+ //
7
+ // One request, to the npm registry npx itself talks to, at most once a day (the
8
+ // answer is kept in ~/.kryptheon). It gives up after 1.5 seconds and never fails
9
+ // a run. KRYPTHEON_NO_UPDATE_CHECK=1, or CI, turns it off.
10
+
11
+ const https = require('https');
12
+ const fs = require('fs');
13
+ const os = require('os');
14
+ const path = require('path');
15
+
16
+ const DAY = 24 * 60 * 60 * 1000;
17
+
18
+ /** -1, 0 or 1, for versions written 1.2.3. */
19
+ function compare(a, b) {
20
+ const x = String(a || '').split('.').map((n) => parseInt(n, 10) || 0);
21
+ const y = String(b || '').split('.').map((n) => parseInt(n, 10) || 0);
22
+ for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) < (y[i] || 0) ? -1 : 1;
23
+ return 0;
24
+ }
25
+
26
+ function cacheFile(name) {
27
+ return path.join(process.env.KRYPTHEON_HOME || path.join(os.homedir(), '.kryptheon'), 'newer-' + name + '.json');
28
+ }
29
+
30
+ /** The cached latest version, or null - never a request. */
31
+ function cachedLatest(name) {
32
+ try {
33
+ const c = JSON.parse(fs.readFileSync(cacheFile(name), 'utf8'));
34
+ return typeof c.latest === 'string' ? c.latest : null;
35
+ } catch (err) {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ /** The latest version on npm (from the day's cache, or one request), or null. Never throws. */
41
+ function latestOf(name, options) {
42
+ const opts = options || {};
43
+ if (process.env.KRYPTHEON_NO_UPDATE_CHECK || process.env.CI) return Promise.resolve(null);
44
+ try {
45
+ const c = JSON.parse(fs.readFileSync(cacheFile(name), 'utf8'));
46
+ if (c && typeof c.latest === 'string' && Date.now() - c.at < DAY) return Promise.resolve(c.latest);
47
+ } catch (err) {
48
+ /* no cache yet */
49
+ }
50
+ return new Promise((resolve) => {
51
+ let done = false;
52
+ const finish = (v) => { if (!done) { done = true; resolve(v); } };
53
+ try {
54
+ const req = https.get('https://registry.npmjs.org/' + encodeURIComponent(name) + '/latest',
55
+ { timeout: opts.timeoutMs || 1500, headers: { accept: 'application/json' } }, (res) => {
56
+ let text = '';
57
+ res.on('data', (d) => { text += d; if (text.length > 200000) req.destroy(); });
58
+ res.on('end', () => {
59
+ try {
60
+ const v = JSON.parse(text).version;
61
+ if (typeof v !== 'string') return finish(null);
62
+ try {
63
+ fs.mkdirSync(path.dirname(cacheFile(name)), { recursive: true });
64
+ fs.writeFileSync(cacheFile(name), JSON.stringify({ at: Date.now(), latest: v }));
65
+ } catch (err) { /* a cache that cannot be written only means asking again tomorrow */ }
66
+ finish(v);
67
+ } catch (err) {
68
+ finish(null);
69
+ }
70
+ });
71
+ });
72
+ req.on('timeout', () => { req.destroy(); finish(null); });
73
+ req.on('error', () => finish(null));
74
+ if (req.unref) req.unref();
75
+ } catch (err) {
76
+ finish(null);
77
+ }
78
+ });
79
+ }
80
+
81
+ /** The line to show when a newer version is out, or null. */
82
+ function notice(name, current, latest, command) {
83
+ if (!latest || compare(latest, current) <= 0) return null;
84
+ return 'A newer ' + name + ' is out (' + current + ' -> ' + latest + '). Run: ' + command;
85
+ }
86
+
87
+ module.exports = { compare, latestOf, cachedLatest, notice, cacheFile };
@@ -65,8 +65,19 @@ const ROW_PICK = /getByRole\(\s*['"](row|cell|gridcell|listitem|article)['"]\s*,
65
65
  // Fields whose value should never be committed to a file.
66
66
  const SECRET_FIELD = /(password|passcode|\bpin\b|secret|security[\s_-]?code|card[\s_-]?number|cvv)/i;
67
67
 
68
+ // A field known only by its id or selector, with no words: #pw, #pwd,
69
+ // input[name=pass], [type=password]. Found on blind round 30 (StudioPulse):
70
+ // the password box was locator('#pw'), so the typed password stayed in the
71
+ // recording as plain text. Only for names without spaces, so a label like
72
+ // "Bus pass number" is not taken for a password.
73
+ const SECRET_SELECTOR = /(^|[^a-z0-9])(pw|pwd|pword|psw|pswd|passwd|pass|passwort)([^a-z0-9]|$)|type\s*=\s*['"]?password/i;
74
+
75
+ function isPasswordSelector(name) {
76
+ return !!name && !/\s/.test(String(name).trim()) && SECRET_SELECTOR.test(String(name));
77
+ }
78
+
68
79
  function isSecretField(name) {
69
- return !!name && SECRET_FIELD.test(name);
80
+ return !!name && (SECRET_FIELD.test(name) || isPasswordSelector(name));
70
81
  }
71
82
 
72
83
  // A recording is only useful if running it again does the same thing. These
@@ -224,7 +235,10 @@ function accountPart(account) {
224
235
  // real value never reaches the file. Named for the account when one was typed
225
236
  // before it, so each account has its own - in every recording that uses it.
226
237
  function envNameFor(fieldName, taken, account) {
227
- const field = String(fieldName || 'password')
238
+ // '#pw' is a password box: KRYPTHEON_PASSWORD_<account>, the name api and
239
+ // roles already read, not KRYPTHEON_PW_<account>.
240
+ const selectorOnly = isPasswordSelector(fieldName) && !SECRET_FIELD.test(fieldName);
241
+ const field = String(selectorOnly ? 'password' : fieldName || 'password')
228
242
  .toUpperCase()
229
243
  .replace(/[^A-Z0-9]+/g, '_')
230
244
  .replace(/^_+|_+$/g, '')
@@ -242,7 +256,18 @@ function envNameFor(fieldName, taken, account) {
242
256
 
243
257
  // Replaces literal secrets with process.env references. Returns the new source
244
258
  // plus what the user now has to put in .env.
245
- function scrubSecrets(source) {
259
+ //
260
+ // options.known: { NAME: value } of passwords already set (KRYPTHEON_PASSWORD_*
261
+ // in .env). A literal equal to one of them is taken out whatever the field is
262
+ // called, and points at that same name - the second guard for a password box
263
+ // whose name says nothing (blind round 30).
264
+ function scrubSecrets(source, options) {
265
+ const known = [];
266
+ const given = (options && options.known) || {};
267
+ for (const name of Object.keys(given)) {
268
+ const value = given[name];
269
+ if (/^KRYPTHEON_PASSWORD/.test(name) && typeof value === 'string' && value.length >= 4) known.push({ name: name, value: value });
270
+ }
246
271
  const text = String(source || '');
247
272
  const lines = text.split('\n');
248
273
  const replacements = [];
@@ -255,13 +280,29 @@ function scrubSecrets(source) {
255
280
  const updated = lines.map((line, index) => {
256
281
  if (!/\.fill\(/.test(line)) return line;
257
282
  const fieldName = nameInLine(line);
258
- if (!isSecretField(fieldName)) return line;
259
283
 
260
284
  // Only a literal is a problem; an existing process.env reference is fine.
261
285
  const filled = line.match(/\.fill\(\s*(['"])((?:\\.|(?!\1).)*)\1\s*\)/);
262
286
  if (!filled) return line;
263
287
  if (!filled[2]) return line; // nothing typed
264
288
 
289
+ const typed = filled[2].replace(/\\(.)/g, '$1');
290
+ // Accounts that share one password all match it: the name of the account typed in this form is the one meant
291
+ // (round 30: every recording pointed at the first account's name, KRYPTHEON_PASSWORD_OWNER_...); the first
292
+ // match only when the account has no name of its own that holds this value.
293
+ const matches = known.filter((k) => k.value === typed);
294
+ const typedFor = matches.length > 1 ? accountBefore(lines, index) : null;
295
+ const ownName = typedFor ? 'KRYPTHEON_PASSWORD_' + accountPart(typedFor) : null;
296
+ const knownHit = (ownName && matches.find((k) => k.name.toUpperCase() === ownName)) || matches[0];
297
+ if (knownHit) {
298
+ if (!replacements.some((r) => r.envName === knownHit.name)) {
299
+ taken.push(knownHit.name);
300
+ replacements.push({ envName: knownHit.name, field: fieldName || 'password', known: true });
301
+ }
302
+ return line.replace(filled[0], '.fill(process.env.' + knownHit.name + " || '')");
303
+ }
304
+ if (!isSecretField(fieldName)) return line;
305
+
265
306
  const account = accountBefore(lines, index);
266
307
  const key = String(fieldName) + '\u0000' + (account || '') + '\u0000' + filled[2];
267
308
  let envName = seen[key];
@@ -447,6 +488,7 @@ module.exports = {
447
488
  scrubSecrets: scrubSecrets,
448
489
  dropTrailingLogout: dropTrailingLogout,
449
490
  isSecretField: isSecretField,
491
+ isPasswordSelector: isPasswordSelector,
450
492
  accountPart: accountPart,
451
493
  nameInLine: nameInLine,
452
494
  CREATES: CREATES,