kryptheon 0.1.43 → 0.1.44

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-code.js CHANGED
@@ -44,6 +44,11 @@ const MAKES_SAFE = /^(escape\w*|\w*escape|sanitize\w*|sanitise\w*|\w*sanitize|pu
44
44
  // formatted number/date - nothing that can carry a tag.
45
45
  const NUMERIC_CALLS = /^(Number|parseInt|parseFloat|Boolean|isNaN|isFinite|toFixed|toPrecision|toLocaleString|toLocaleDateString|toLocaleTimeString|getTime|getFullYear|getMonth|getDate|getDay|getHours|getMinutes|getSeconds|round|floor|ceil|abs|min|max|indexOf|findIndex|size)$/;
46
46
  const NUMERIC_PROPS = /^(length|size|count|total|id|index|width|height|top|left|x|y)$/;
47
+ // A field whose name says it is a quantity of something: quantity_on_hand,
48
+ // reserved_quantity, itemCount, unit_price. Found on blind round 16
49
+ // (Meridian), once rows from the database were followed into the page: the
50
+ // stock counts were written unescaped, and an integer column holds digits.
51
+ const NUMERIC_NAMES = /^(quantity|qty|count|total|amount|price|cost|balance|percent|score)(_|[A-Z]|$)|((^|_)(quantity|qty|count|total|amount|price|cost|balance|percent|score)|[a-z](Quantity|Qty|Count|Total|Amount|Price|Cost|Balance|Percent|Score))$/;
47
52
 
48
53
  /** Every file worth reading, relative paths, skipping what is not the app's source. */
49
54
  function listFiles(root) {
@@ -70,6 +75,86 @@ function listFiles(root) {
70
75
  return out.sort();
71
76
  }
72
77
 
78
+ // Column types that can hold no tag: numbers, yes/no, ids, dates and times.
79
+ const TAGLESS_TYPE = /^(smallint|integer|int|int2|int4|int8|bigint|smallserial|serial|bigserial|numeric|decimal|real|float4|float8|double precision|money|boolean|bool|uuid|date|time|timetz|timestamp|timestamptz|interval)\b/i;
80
+ const NOT_A_COLUMN = /^(constraint|primary|foreign|unique|check|exclude|like)$/i;
81
+
82
+ /**
83
+ * Column names the project's own SQL declares only with a type that cannot
84
+ * hold a tag - every table that has the name gives it a number, a yes/no, an
85
+ * id or a date. Read from the .sql files in the project (migrations, a schema
86
+ * dump), never guessed from the name.
87
+ *
88
+ * Found on blind round 16, once rows from the database were followed into the
89
+ * page: stock counts and ticket numbers - integer and bigint columns - were
90
+ * reported as text of unknown origin. A name declared as text anywhere, or
91
+ * not declared at all, is not on the list.
92
+ */
93
+ function taglessColumns(root) {
94
+ const types = new Map();
95
+ let read = 0;
96
+ (function walk(dir, depth) {
97
+ if (depth > 8 || read > 200) return;
98
+ let entries;
99
+ try {
100
+ entries = fs.readdirSync(dir, { withFileTypes: true });
101
+ } catch (err) {
102
+ return;
103
+ }
104
+ for (const entry of entries) {
105
+ const full = path.join(dir, entry.name);
106
+ if (entry.isDirectory()) {
107
+ if (!entry.name.startsWith('.') && !SKIP_DIRS.has(entry.name)) walk(full, depth + 1);
108
+ continue;
109
+ }
110
+ if (!/\.sql$/i.test(entry.name)) continue;
111
+ let sql;
112
+ try {
113
+ if (fs.statSync(full).size > 4 * MAX_BYTES) continue;
114
+ sql = fs.readFileSync(full, 'utf8');
115
+ } catch (err) {
116
+ continue;
117
+ }
118
+ read++;
119
+ sql = sql.replace(/--[^\n]*/g, ' ').replace(/\/\*[\s\S]*?\*\//g, ' ');
120
+ const add = (name, type) => {
121
+ const n = String(name).replace(/"/g, '');
122
+ if (!types.has(n)) types.set(n, []);
123
+ types.get(n).push(String(type).trim());
124
+ };
125
+ // CREATE TABLE name ( ... ): split at the commas outside brackets.
126
+ const table = /create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?[\w."]+\s*\(/gi;
127
+ let m;
128
+ while ((m = table.exec(sql)) !== null) {
129
+ let level = 1;
130
+ let i = table.lastIndex;
131
+ let start = i;
132
+ const parts = [];
133
+ for (; i < sql.length && level > 0; i++) {
134
+ const ch = sql[i];
135
+ if (ch === '(') level++;
136
+ else if (ch === ')') { level--; if (level === 0) parts.push(sql.slice(start, i)); }
137
+ else if (ch === ',' && level === 1) { parts.push(sql.slice(start, i)); start = i + 1; }
138
+ }
139
+ for (const part of parts) {
140
+ const cm = /^\s*("[^"]+"|[A-Za-z_][\w$]*)\s+([A-Za-z][\w ]*?)(?=\s*(\(|\[|not\b|null\b|default\b|primary\b|references\b|unique\b|check\b|generated\b|constraint\b|collate\b|$))/i.exec(part);
141
+ if (!cm || NOT_A_COLUMN.test(cm[1])) continue;
142
+ add(cm[1], cm[2]);
143
+ }
144
+ }
145
+ // ALTER TABLE ... ADD COLUMN name type
146
+ const added = /add\s+column\s+(?:if\s+not\s+exists\s+)?("[^"]+"|[A-Za-z_][\w$]*)\s+([A-Za-z][\w ]*?)(?=\s*(\(|\[|not\b|null\b|default\b|references\b|unique\b|check\b|generated\b|;|,|$))/gi;
147
+ while ((m = added.exec(sql)) !== null) add(m[1], m[2]);
148
+ }
149
+ })(root, 0);
150
+ const out = new Set();
151
+ for (const [name, list] of types) {
152
+ if (list.length && list.every((t) => TAGLESS_TYPE.test(t))) out.add(name);
153
+ }
154
+ return out;
155
+ }
156
+ let TAGLESS_COLUMNS = new Set();
157
+
73
158
  /** The parser, or null when this Playwright does not have it where expected. */
74
159
  function loadParser(packageDir) {
75
160
  const candidates = [];
@@ -197,7 +282,12 @@ function classify(node, scope, code, depth, aliases) {
197
282
  const local = node.callee.type === 'Identifier' ? localFunction(node.callee.name, scope) : null;
198
283
  if (local) {
199
284
  const returns = returnsOf(local);
200
- if (returns.length) return worst(returns.map((r) => classify(r.node, r.scope, code, depth + 1, aliases)));
285
+ // Judged with what THIS call passes: field("Title", ...) is not made
286
+ // dangerous by another call of field() that passes a name from the
287
+ // database (blind round 16, Meridian). An object written out in the
288
+ // call is kept whole, so options.placeholder is that call's own.
289
+ const inner = argumentAliases(local.node, node.arguments, scope, local.scope, code, depth, aliases);
290
+ if (returns.length) return worst(returns.map((r) => classify(r.node, r.scope, code, depth + 1, inner)));
201
291
  }
202
292
  // String methods pass through whatever they were called on, and so do
203
293
  // the array methods that only pick or reorder items: notes.filter(...)
@@ -220,7 +310,7 @@ function classify(node, scope, code, depth, aliases) {
220
310
  // adds nothing that was not already there. textContent is not this - it
221
311
  // is text, and a "<" in it becomes a tag when written as HTML.
222
312
  if (prop === 'innerHTML' || prop === 'outerHTML') return 'safe';
223
- if (NUMERIC_PROPS.test(prop || '')) return 'safe';
313
+ if (NUMERIC_PROPS.test(prop || '') || NUMERIC_NAMES.test(prop || '') || TAGLESS_COLUMNS.has(prop || '')) return 'safe';
224
314
  // The value of one of the page's own <select>s: one of its options.
225
315
  if (prop === 'value' && SELECT_IDS.has(pickedId(node.object, scope) || '')) return 'safe';
226
316
  if (prop === 'message' && isCatchParam(node.object, scope)) return 'error';
@@ -229,9 +319,34 @@ function classify(node, scope, code, depth, aliases) {
229
319
  let base = node.object;
230
320
  while (base && /MemberExpression$/.test(base.type)) base = base.object;
231
321
  if (base && (/CallExpression$/.test(base.type) || base.type === 'AwaitExpression')) return again(base);
232
- const ofItems = !(aliases && base && Object.prototype.hasOwnProperty.call(aliases, base.name)) &&
233
- itemPropertyOrigin(node, scope, code, depth);
322
+ // An item's property is judged by that property in every item, even
323
+ // where the item itself is known only as a whole: inside a helper's
324
+ // map(), item.value can be an id in every item while item.label is a
325
+ // name (blind round 16, Meridian's field()).
326
+ const ofItems = itemPropertyOrigin(node, scope, code, depth);
234
327
  if (ofItems) return ofItems;
328
+ const aliased = aliases && base && Object.prototype.hasOwnProperty.call(aliases, base.name);
329
+ const filled = !aliased && base && base.type === 'Identifier' ? objectPropertyOrigin(node, base, scope, code, depth, aliases) : null;
330
+ if (filled) return filled;
331
+ let first = node;
332
+ while (first.object && /MemberExpression$/.test(first.object.type)) first = first.object;
333
+ const named = first.object === base && !first.computed && first.property && first.property.type === 'Identifier';
334
+ // options.placeholder inside a call judged with its own arguments
335
+ // (argumentAliases): that call's object, that one property.
336
+ const written = aliases && base && named && Object.prototype.hasOwnProperty.call(aliases, OBJECT_ARG + base.name)
337
+ ? aliases[OBJECT_ARG + base.name] : null;
338
+ if (written) {
339
+ const p = written.node.properties.find((x) => (x.key.type === 'Identifier' ? x.key.name : x.key.value) === first.property.name);
340
+ return p ? classify(p.value, written.scope, code, depth + 1, written.aliases) : 'safe';
341
+ }
342
+ // options.placeholder, where every call of the function writes options
343
+ // out as an object: judged by what the calls give that one property.
344
+ if (!aliased && base && base.type === 'Identifier') {
345
+ if (named) {
346
+ const values = paramPropertyValues(base, first.property.name, scope);
347
+ if (values) return worst(values.map((v) => classify(v.node, v.scope, code, depth + 1, aliases)));
348
+ }
349
+ }
235
350
  return fromBinding(rootIdentifier(node), scope, code, depth, aliases);
236
351
  }
237
352
  case 'Identifier':
@@ -584,12 +699,91 @@ function fromBinding(id, scope, code, depth, aliases) {
584
699
  RESOLVING.delete(binding);
585
700
  }
586
701
  }
702
+ // An object the code fills in later: as dangerous as what it starts with
703
+ // and every value written into it. Found on blind round 16 (Meridian):
704
+ // `const state = { sites: [] }`, then `state.sites = data` from Supabase,
705
+ // then a site's name rendered - judged by the empty list it started with,
706
+ // a name from the database read as safe. Only `state.x = value` is
707
+ // followed; written through any other way, what it holds is not in one
708
+ // place.
709
+ if (init && /^(ObjectExpression|ArrayExpression)$/.test(init.type)) {
710
+ const writes = (binding.referencePaths || []).filter((r) => writtenThrough(r));
711
+ if (writes.length) {
712
+ if (RESOLVING.has(binding)) return 'safe';
713
+ RESOLVING.add(binding);
714
+ try {
715
+ const origins = [classify(init, binding.path.scope, code, depth + 1, aliases)];
716
+ for (const r of writes) {
717
+ const member = r.parentPath;
718
+ const assign = member && member.parentPath;
719
+ if (!member || !/MemberExpression$/.test(member.node.type) || member.node.object !== r.node ||
720
+ !assign || assign.node.type !== 'AssignmentExpression' || assign.node.left !== member.node ||
721
+ assign.node.operator !== '=') {
722
+ return 'unknown';
723
+ }
724
+ origins.push(classify(assign.node.right, assign.scope, code, depth + 1, aliases));
725
+ }
726
+ return worst(origins);
727
+ } finally {
728
+ RESOLVING.delete(binding);
729
+ }
730
+ }
731
+ }
587
732
  // Destructured from a response body: const { name } = await res.json()
588
733
  // Aliases carry through: inside a map() callback, `const t = r.title` is as
589
734
  // dangerous as the item r it was read from.
590
735
  return classify(init, binding.path.scope, code, depth + 1, aliases);
591
736
  }
592
737
 
738
+ /**
739
+ * state.page, where state is an object the code declared and fills in: judged
740
+ * by what it starts with under that name and every write to that name -
741
+ * state.page = 1, state.page += 1, state.page++ - and not by what is written
742
+ * under its other names. Null when the object is written any other way
743
+ * (Object.assign(state, ...), state[key] = ...), or is not that kind of name.
744
+ *
745
+ * Found on blind round 16, once filled-in objects were followed: state.page,
746
+ * a page number, read as unknown because state.tickets was filled from the
747
+ * database.
748
+ */
749
+ function objectPropertyOrigin(node, base, scope, code, depth, aliases) {
750
+ let first = node;
751
+ while (first.object && /MemberExpression$/.test(first.object.type)) first = first.object;
752
+ if (first.object !== base || first.computed || !first.property || first.property.type !== 'Identifier') return null;
753
+ const prop = first.property.name;
754
+ const binding = scope && scope.getBinding(base.name);
755
+ if (!binding || binding.kind === 'param' || binding.kind === 'module' ||
756
+ (binding.constantViolations && binding.constantViolations.length)) return null;
757
+ const init = binding.path && binding.path.node && binding.path.node.init;
758
+ if (!init || init.type !== 'ObjectExpression' ||
759
+ init.properties.some((p) => p.type !== 'ObjectProperty' || p.computed)) return null;
760
+ if (RESOLVING.has(node)) return 'safe';
761
+ RESOLVING.add(node);
762
+ try {
763
+ const own = init.properties.find((p) => (p.key.type === 'Identifier' ? p.key.name : p.key.value) === prop);
764
+ const origins = [own ? classify(own.value, binding.path.scope, code, depth + 1) : 'safe'];
765
+ for (const ref of binding.referencePaths || []) {
766
+ if (!writtenThrough(ref)) continue;
767
+ const member = ref.parentPath;
768
+ if (!member || !/MemberExpression$/.test(member.node.type) || member.node.object !== ref.node || member.node.computed) return null;
769
+ if (member.node.property.name !== prop) continue;
770
+ const holder = member.parentPath;
771
+ if (holder.node.type === 'UpdateExpression') continue; // state.page++ holds a number
772
+ if (holder.node.type === 'AssignmentExpression' && holder.node.left === member.node) {
773
+ if (holder.node.operator === '=' || holder.node.operator === '+=') {
774
+ origins.push(classify(holder.node.right, holder.scope, code, depth + 1, aliases));
775
+ continue;
776
+ }
777
+ if (/^[-*/%]=$/.test(holder.node.operator)) continue; // arithmetic: a number
778
+ }
779
+ return 'unknown'; // state.items.push(...), state.page.x = ...: not followed here
780
+ }
781
+ return worst(origins);
782
+ } finally {
783
+ RESOLVING.delete(node);
784
+ }
785
+ }
786
+
593
787
  // Array methods that hand their callback the list's own items.
594
788
  const ITEM_CALLBACKS = /^(map|forEach|filter|find|findLast|findIndex|findLastIndex|some|every|flatMap|sort|toSorted)$/;
595
789
 
@@ -660,6 +854,94 @@ function addedItems(binding) {
660
854
 
661
855
  const SAME_ITEMS = /^(filter|slice|sort|toSorted|reverse|toReversed)$/;
662
856
 
857
+ // The key under which argumentAliases keeps an object written out in a call,
858
+ // beside the parameter's own name. Not a name any code can have.
859
+ const OBJECT_ARG = '\u0000object:';
860
+
861
+ /**
862
+ * A function's parameters as one call fills them: each name judged by the
863
+ * argument this call passes (its default when left out, undefined when it has
864
+ * none), and an object literal also kept whole under OBJECT_ARG, so a
865
+ * property of it is judged alone. A parameter that is not a plain name, or
866
+ * one behind a spread, is left to be judged from every call.
867
+ */
868
+ function argumentAliases(fn, args, scope, fnScope, code, depth, aliases) {
869
+ const inner = Object.assign({}, aliases || {});
870
+ const params = (fn && fn.params) || [];
871
+ for (let i = 0; i < params.length; i++) {
872
+ if ((args || []).slice(0, i + 1).some((a) => a.type === 'SpreadElement')) break;
873
+ const param = params[i];
874
+ const id = param.type === 'AssignmentPattern' ? param.left : param;
875
+ if (id.type !== 'Identifier') continue;
876
+ delete inner[OBJECT_ARG + id.name];
877
+ const arg = args[i];
878
+ const source = arg ? { node: arg, scope: scope, aliases: aliases }
879
+ : param.type === 'AssignmentPattern' ? { node: param.right, scope: fnScope, aliases: aliases } : null;
880
+ inner[id.name] = source ? classify(source.node, source.scope, code, depth + 1, source.aliases) : 'safe';
881
+ if (source && source.node.type === 'ObjectExpression' &&
882
+ source.node.properties.every((p) => p.type === 'ObjectProperty' && !p.computed)) {
883
+ inner[OBJECT_ARG + id.name] = source;
884
+ }
885
+ }
886
+ return inner;
887
+ }
888
+
889
+ /**
890
+ * The calls of the function a parameter belongs to: what each passes in that
891
+ * place ({ arg, scope }, arg null when it is left out) and the parameter's
892
+ * own default. Null when the function is used any way but being called here.
893
+ */
894
+ function callsOfParam(binding) {
895
+ const fn = binding && binding.path && binding.path.parentPath;
896
+ if (!fn || !/Function/.test(fn.node.type)) return null;
897
+ const index = fn.node.params.indexOf(binding.path.node);
898
+ if (index === -1) return null;
899
+ let name = fn.node.id && fn.node.id.name;
900
+ if (!name && fn.parentPath && fn.parentPath.node.type === 'VariableDeclarator' && fn.parentPath.node.id.type === 'Identifier') {
901
+ name = fn.parentPath.node.id.name;
902
+ }
903
+ const fnBinding = name && fn.parentPath && fn.parentPath.scope.getBinding(name);
904
+ if (!fnBinding || (fnBinding.constantViolations && fnBinding.constantViolations.length)) return null;
905
+ const refs = fnBinding.referencePaths || [];
906
+ if (!refs.length) return null;
907
+ const calls = [];
908
+ for (const ref of refs) {
909
+ const call = ref.parent;
910
+ if (!call || !/CallExpression$/.test(call.type) || call.callee !== ref.node) return null;
911
+ if (call.arguments.slice(0, index + 1).some((a) => a.type === 'SpreadElement')) return null;
912
+ calls.push({ arg: call.arguments[index] || null, scope: ref.scope });
913
+ }
914
+ const fallback = binding.path.node.type === 'AssignmentPattern' ? { node: binding.path.node.right, scope: fn.scope } : null;
915
+ return { calls: calls, fallback: fallback };
916
+ }
917
+
918
+ /**
919
+ * options.prop, where options is a parameter: what every call gives that one
920
+ * property, as { node, scope } - nothing for a call that leaves it out. Null
921
+ * unless every call writes the argument out as an object literal right there.
922
+ *
923
+ * Found on blind round 16 (Meridian): field(label, name, type, options) built
924
+ * every form field from constant labels, a placeholder and a list of options
925
+ * whose values were ids - but one call's options also held a list read from
926
+ * the database, so the whole of options, and every field, read as unknown.
927
+ */
928
+ function paramPropertyValues(id, prop, scope) {
929
+ const binding = id && scope && scope.getBinding(id.name);
930
+ if (!binding || binding.kind !== 'param' || (binding.constantViolations && binding.constantViolations.length)) return null;
931
+ const found = callsOfParam(binding);
932
+ if (!found) return null;
933
+ const values = [];
934
+ for (const c of found.calls) {
935
+ const source = c.arg ? { node: c.arg, scope: c.scope } : found.fallback;
936
+ if (!source) continue; // left out, no default: undefined
937
+ if (source.node.type !== 'ObjectExpression' ||
938
+ source.node.properties.some((p) => p.type !== 'ObjectProperty' || p.computed)) return null;
939
+ const p = source.node.properties.find((x) => (x.key.type === 'Identifier' ? x.key.name : x.key.value) === prop);
940
+ if (p) values.push({ node: p.value, scope: source.scope });
941
+ }
942
+ return values;
943
+ }
944
+
663
945
  /**
664
946
  * Every item a list can hold, as { node, scope }: its literal elements and
665
947
  * what is pushed into it, through filter / slice / sort and the file's own
@@ -669,12 +951,51 @@ const SAME_ITEMS = /^(filter|slice|sort|toSorted|reverse|toReversed)$/;
669
951
  function listItems(node, scope, depth) {
670
952
  if (!node || !scope || depth > 8) return null;
671
953
  if (node.type === 'ArrayExpression') {
672
- if (node.elements.some((e) => !e || e.type === 'SpreadElement')) return null;
673
- return node.elements.map((e) => ({ node: e, scope: scope }));
954
+ if (node.elements.some((e) => !e)) return null;
955
+ // [first, ...more]: what is spread in is items too, when it can be listed.
956
+ const all = [];
957
+ for (const e of node.elements) {
958
+ if (e.type !== 'SpreadElement') {
959
+ all.push({ node: e, scope: scope });
960
+ continue;
961
+ }
962
+ const spread = listItems(e.argument, scope, depth + 1);
963
+ if (!spread) return null;
964
+ all.push(...spread);
965
+ }
966
+ return all;
967
+ }
968
+ // list || []: either one.
969
+ if (node.type === 'LogicalExpression' && (node.operator === '||' || node.operator === '??')) {
970
+ const left = listItems(node.left, scope, depth + 1);
971
+ const right = left && listItems(node.right, scope, depth + 1);
972
+ return left && right ? left.concat(right) : null;
973
+ }
974
+ // options.items, where every call writes options out (paramPropertyValues).
975
+ if (/MemberExpression$/.test(node.type) && !node.computed && node.object.type === 'Identifier' && node.property.type === 'Identifier') {
976
+ const values = paramPropertyValues(node.object, node.property.name, scope);
977
+ if (!values) return null;
978
+ const all = [];
979
+ for (const v of values) {
980
+ const items = listItems(v.node, v.scope, depth + 1);
981
+ if (!items) return null;
982
+ all.push(...items);
983
+ }
984
+ return all;
674
985
  }
675
986
  if (/CallExpression$/.test(node.type)) {
676
987
  const callee = node.callee;
677
988
  if (/MemberExpression$/.test(callee.type) && SAME_ITEMS.test(calleeName(callee))) return listItems(callee.object, scope, depth + 1);
989
+ // sites.map(site => ({ value: site.id, label: site.name })): the items
990
+ // are what the callback returns, judged where the callback runs - so
991
+ // site.id is an id of a site, whatever else a site holds.
992
+ if (/MemberExpression$/.test(callee.type) && calleeName(callee) === 'map' && node.arguments[0] &&
993
+ /Function/.test(node.arguments[0].type)) {
994
+ const fnPath = FN_PATHS.get(node.arguments[0]);
995
+ if (!fnPath) return null;
996
+ const returns = returnsOf(fnPath);
997
+ return returns.length ? returns : null;
998
+ }
678
999
  const local = callee.type === 'Identifier' ? localFunction(callee.name, scope) : null;
679
1000
  if (!local) return null;
680
1001
  const all = [];
@@ -1323,6 +1644,7 @@ function sinksIn(parser, code, file, lineOffset, resolver) {
1323
1644
  */
1324
1645
  function scanProject(root, options) {
1325
1646
  SELECT_IDS = new Set();
1647
+ TAGLESS_COLUMNS = taglessColumns(root);
1326
1648
  const packageDir = (options && options.packageDir) || __dirname;
1327
1649
  const parser = (options && options.parser) || loadParser(packageDir);
1328
1650
  if (!parser) {
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kryptheon",
3
- "version": "0.1.43",
3
+ "version": "0.1.44",
4
4
  "description": "Record what you do in your app and get plain-language reports when it breaks.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "commonjs",