kryptheon 0.1.58 → 0.1.62

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
@@ -61,7 +61,10 @@ const OTHER_FRAMEWORKS = /^(fastify|koa|@koa\/router|koa-router|hono|@hono\/hono
61
61
  const IDENTITY_SEGS = /^(user|users|session|auth|actor|account|member|currentUser|identity|principal|claims|userId|user_id|uid|sub|me|profile|viewer|isAuthenticated|isLoggedIn|token|kauth|apiKey|api_key|tenant|org|workspace)$/;
62
62
  const IDENTITY_NAMES = /^(user|currentUser|current_user|me|actor|member|account|profile|viewer|identity|principal|session|sessionUser|authUser|auth|claims)$/i;
63
63
  // A cookie or header that says who is calling: a session token (sid, token) or, worse, the user id itself.
64
- const COOKIE_IDENTITY = /^(uid|user|userId|user_id|userid|id|sid|session|sessionId|session_id|token|auth|jwt|access_token|accessToken|connect\.sid)$/i;
64
+ // a session cookie, not a bare id: its value is a secret only the caller holds
65
+ const SESSION_COOKIE = /^(?!.*(csrf|xsrf))(?:[a-z0-9]+[_.-])*(sid|session|sessionId|session_id|token|jwt|access_token|accessToken)$/i;
66
+ // the name may carry the app's own prefix: wayline_sid, app-session, myapp.token (round 26) - never a CSRF token
67
+ const COOKIE_IDENTITY = /^(?!.*(csrf|xsrf))(?:[a-z0-9]+[_.-])*(uid|user|userId|user_id|userid|id|sid|session|sessionId|session_id|token|auth|jwt|access_token|accessToken)$/i;
65
68
  const HEADER_IDENTITY = /^x-(user|uid|user-id|userid|account|account-id|member|member-id|actor|actor-id)$/i;
66
69
  // Of those, the ones that hold the bare id - nothing a server signed, so anyone can write another person's.
67
70
  const BARE_ID = /^(uid|user|userId|user_id|userid|id)$/i;
@@ -206,6 +209,16 @@ function makeContext(root, parser) {
206
209
  }
207
210
 
208
211
  /** ['req', 'session', 'user'] for req.session.user; null when any part is computed and not a fixed text. */
212
+ /** The function a name of this scope is bound to (function name() {} or const name = () => {}), or null. */
213
+ function localFunction(scope, name) {
214
+ const b = scope.getBinding(name);
215
+ const n = b && b.path && b.path.node;
216
+ if (!n) return null;
217
+ if (n.type === 'FunctionDeclaration') return n;
218
+ if (n.type === 'VariableDeclarator' && n.init && /Function/.test(n.init.type)) return n.init;
219
+ return null;
220
+ }
221
+
209
222
  function memberChain(node) {
210
223
  const out = [];
211
224
  let n = node;
@@ -213,6 +226,8 @@ function memberChain(node) {
213
226
  if (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') {
214
227
  if (!n.computed && n.property.type === 'Identifier') out.unshift(n.property.name);
215
228
  else if (n.computed && n.property.type === 'StringLiteral') out.unshift(n.property.value);
229
+ // rows[0]: one item of the list, read by the same names (round 28: p.rows[0].id is the id of p's row)
230
+ else if (n.computed && n.property.type === 'NumericLiteral') { /* skipped */ }
216
231
  else return null;
217
232
  n = n.object;
218
233
  } else if (n.type === 'Identifier') {
@@ -644,12 +659,15 @@ function refText(p) {
644
659
  return chain ? chain.join('.') : '(' + n.type + ')';
645
660
  }
646
661
 
647
- /** '/api' + '/x/' -> '/api/x' */
662
+ /**
663
+ * '/api' + '/x/' -> '/api/x'. A parameter written with a pattern is the same parameter: /work-orders/:id(\d+) is
664
+ * /work-orders/:id (round 27: the detail route kept its pattern and was never aimed).
665
+ */
648
666
  function joinPath(a, b) {
649
667
  const x = (a || '').replace(/\/+$/, '');
650
668
  const y = (b || '/').startsWith('/') ? b || '/' : '/' + b;
651
669
  const out = (x + (y === '/' ? '' : y)) || '/';
652
- return out.replace(/\/{2,}/g, '/');
670
+ return out.replace(/\/{2,}/g, '/').replace(/(:[A-Za-z_]\w*)\((?:[^()\\]|\\.)*\)/g, '$1');
653
671
  }
654
672
 
655
673
  /** Whether middleware used at `prefix` runs for a request to `full`. */
@@ -1515,6 +1533,9 @@ function sourceReader(ctx, fnRef, env) {
1515
1533
  if (!chain) return null;
1516
1534
  if (locals.has(chain[0])) return locals.get(chain[0]);
1517
1535
  if (reqName && chain[0] === reqName) {
1536
+ // the caller's own session cookie: a token nobody else holds, so a row found by it is the caller's own
1537
+ // (round 26: DELETE FROM app_sessions WHERE session_token = req.cookies.wayline_sid). A bare id (uid) is not.
1538
+ if (/^(cookies|signedCookies)$/.test(chain[1] || '') && chain[2] && SESSION_COOKIE.test(chain[2])) return 'identity';
1518
1539
  if (/^(body|query|params|headers|cookies|files|file|nextUrl|url)$/.test(chain[1] || '')) return 'client';
1519
1540
  if (chain[1] && IDENTITY_SEGS.test(chain[1])) return 'identity';
1520
1541
  if (/^(db|client|tx)$/.test(chain[1] || '')) return null;
@@ -1542,6 +1563,17 @@ function sourceReader(ctx, fnRef, env) {
1542
1563
  }
1543
1564
  case 'CallExpression': case 'OptionalCallExpression': {
1544
1565
  const callee = memberChain(n.callee) || [];
1566
+ // hashToken(token): a one-argument helper of the file that runs no query hands its argument on - the hash of the
1567
+ // caller's own session cookie is still the caller's (round 28 logout)
1568
+ if (n.callee.type === 'Identifier' && n.arguments.length === 1) {
1569
+ const helper = localFunction(fn.scope, n.callee.name);
1570
+ const text = helper ? mod.source.slice(helper.start, helper.end) : '';
1571
+ // only when the argument tells something: scopedOrg(req) is decided by what it returns, below
1572
+ // a database call, not a hash's .update(token)
1573
+ const readsDb = /\bquery\s*\(|\.from\s*\(|\bfind\w*\s*\(|\bfetch\s*\(|\bsql`|\$queryRaw/.test(text);
1574
+ const passed = helper && helper.params.length === 1 && !readsDb ? of(n.arguments[0], depth + 1) : 'unknown';
1575
+ if (passed !== 'unknown') return passed;
1576
+ }
1545
1577
  // a Fetch-style request: await req.json(), req.formData(), req.headers.get(...)
1546
1578
  if (reqName && callee[0] === reqName && /^(json|formData|text|arrayBuffer|blob)$/.test(callee[callee.length - 1] || '')) return 'client';
1547
1579
  // body.get('x'), url.searchParams.get('x'): a method of something the request sent
@@ -1592,6 +1624,11 @@ function sourceReader(ctx, fnRef, env) {
1592
1624
  const awaited = init.type === 'AwaitExpression' ? init.argument : init;
1593
1625
  if (s === 'unknown' && isSessionLookup(awaited)) s = 'identity';
1594
1626
  if (s === 'unknown' && /query|rows|select|find|maybeSingle|single\(/i.test(mod.source.slice(init.start, init.end))) s = 'record';
1627
+ // const ev = await getOrgEvent(id, org): a helper of the file that runs a query returns a row (round 28)
1628
+ if (s === 'unknown' && awaited && awaited.type === 'CallExpression' && awaited.callee.type === 'Identifier') {
1629
+ const fnNode = localFunction(q.scope, awaited.callee.name);
1630
+ if (fnNode && /\b(query|select|find\w*)\s*\(/i.test(mod.source.slice(fnNode.start, fnNode.end))) s = 'record';
1631
+ }
1595
1632
  for (const name of patternNames(id)) if (!locals.has(name)) locals.set(name, s);
1596
1633
  },
1597
1634
  // for (const s of pending): each item is a row of the list it walks
@@ -1723,6 +1760,10 @@ function readDb(ctx, fnRef, schema, opts = {}) {
1723
1760
  });
1724
1761
  const inner = readDb(ctx, r, schema, { depth: depth + 1, paramSources, reqName: null });
1725
1762
  for (const op of inner) out.push(Object.assign({}, op, { via: callee.node.name + '() at ' + mod.rel + ':' + line }));
1763
+ // const ev = await getOrgEvent(id, org): the row the helper returns was found the way its query found it
1764
+ const holder = q.findParent((x) => x.isVariableDeclarator() || x.isFunction());
1765
+ const found = inner.find((x) => x.op === 'SELECT' && !x.joinedTo);
1766
+ if (found && holder && holder.isVariableDeclarator() && t.isIdentifier(holder.node.id)) recordScopes.set(holder.node.id.name, { table: found.table, status: found.scoping.status, line, file: mod.rel });
1726
1767
  }
1727
1768
  };
1728
1769
  fnRef.path.traverse({
@@ -2007,7 +2048,8 @@ function scopeVerdict(mod, line, st, filters, insertCols, schema, via, partlyUnr
2007
2048
  const tenantList = all.filter((f) => TENANT_COLS.test(f.col) || (TENANT_TABLES.test(table) && f.col === 'id'));
2008
2049
  const list = tenantList.length ? Array.from(new Set(tenantList.concat(all.filter(viaRow)))) : all;
2009
2050
  const cols = (fs2) => Array.from(new Set(fs2.map((f) => f.col))).join(', ');
2010
- const byIdentity = list.filter((f) => scopeCol(f.col) && f.src === 'identity');
2051
+ // a session or token column found by the caller's own session is the caller's own row too
2052
+ const byIdentity = list.filter((f) => (scopeCol(f.col) || /(^|_)(session|token|sid)(_?(id|hash|token))?$/i.test(f.col)) && f.src === 'identity');
2011
2053
  const byScopedRow = list.filter((f) => viaRow(f) && f.row.status === STATUS.DETECTED);
2012
2054
  const byClient = list.filter((f) => scopeCol(f.col) && f.src === 'client');
2013
2055
  const byOpenRow = list.filter((f) => viaRow(f) && f.row.status === STATUS.NOT);
@@ -1,29 +1,29 @@
1
- // Says one line per probe run as it ends, in a form kryptheon-probe.js reads
2
- // back and turns into words: "KXPROBE <done> <total> <id> <status>". Nothing
3
- // else - a probe that fails is usually the app refusing a bad value, and a
4
- // failure report for it would say the opposite of what happened.
5
-
6
- class ProbeReporter {
7
- onBegin(config, suite) {
8
- this.total = suite.allTests().length;
9
- this.done = 0;
10
- }
11
-
12
- onTestEnd(test, result) {
13
- this.done += 1;
14
- const id = String(test.location.file).replace(/^.*[\\/]/, '').replace(/\.kxprobe\.js$/, '');
15
- console.log('KXPROBE ' + this.done + ' ' + this.total + ' ' + id + ' ' + result.status);
16
- }
17
-
18
- onError(error) {
19
- // The run itself could not start - a broken copy, a missing browser.
20
- const text = String((error && error.message) || error).split(/\r?\n/)[0];
21
- console.log('KXPROBE-ERROR ' + text.slice(0, 300));
22
- }
23
-
24
- printsToStdio() {
25
- return true;
26
- }
27
- }
28
-
29
- module.exports = ProbeReporter;
1
+ // Says one line per probe run as it ends, in a form kryptheon-probe.js reads
2
+ // back and turns into words: "KXPROBE <done> <total> <id> <status>". Nothing
3
+ // else - a probe that fails is usually the app refusing a bad value, and a
4
+ // failure report for it would say the opposite of what happened.
5
+
6
+ class ProbeReporter {
7
+ onBegin(config, suite) {
8
+ this.total = suite.allTests().length;
9
+ this.done = 0;
10
+ }
11
+
12
+ onTestEnd(test, result) {
13
+ this.done += 1;
14
+ const id = String(test.location.file).replace(/^.*[\\/]/, '').replace(/\.kxprobe\.js$/, '');
15
+ console.log('KXPROBE ' + this.done + ' ' + this.total + ' ' + id + ' ' + result.status);
16
+ }
17
+
18
+ onError(error) {
19
+ // The run itself could not start - a broken copy, a missing browser.
20
+ const text = String((error && error.message) || error).split(/\r?\n/)[0];
21
+ console.log('KXPROBE-ERROR ' + text.slice(0, 300));
22
+ }
23
+
24
+ printsToStdio() {
25
+ return true;
26
+ }
27
+ }
28
+
29
+ module.exports = ProbeReporter;
@@ -1,37 +1,37 @@
1
- // @ts-check
2
- // The Playwright config for probe copies (kryptheon-probe.js). Kept apart from
3
- // playwright.config.js on purpose: probes live in the store, not in tests/;
4
- // they report through their own reporter; and their screenshots and traces
5
- // go to a folder of their own - Playwright empties its output folder on every
6
- // run, and the last check's evidence must not be wiped by a probe.
7
- const path = require('path');
8
- const { defineConfig } = require('@playwright/test');
9
-
10
- const PACKAGE_DIR = __dirname;
11
- const USER_DIR = process.cwd();
12
- const PROBE_DIR = process.env.KRYPTHEON_PROBE_DIR || path.join(USER_DIR, 'tests');
13
-
14
- // The same .env reading as playwright.config.js, for the same reasons.
15
- const secrets = require(path.join(PACKAGE_DIR, 'kryptheon-secrets.js'));
16
- const values = secrets.readEnvFile(path.join(USER_DIR, '.env'));
17
- for (const name of Object.keys(values)) {
18
- if (!secrets.isSet(process.env[name])) process.env[name] = values[name];
19
- }
20
-
21
- module.exports = defineConfig({
22
- testDir: PROBE_DIR,
23
- testMatch: ['**/*.kxprobe.js'],
24
- outputDir: path.join(PROBE_DIR, 'output'),
25
- fullyParallel: false,
26
- workers: 1,
27
- retries: 0,
28
- // Room for the gap before each run and for opening the page again after it.
29
- timeout: 60000,
30
- reporter: [[path.join(PACKAGE_DIR, 'kryptheon-probe-reporter.js')]],
31
- use: {
32
- headless: true,
33
- channel: 'chromium',
34
- screenshot: 'off',
35
- trace: 'off',
36
- },
37
- });
1
+ // @ts-check
2
+ // The Playwright config for probe copies (kryptheon-probe.js). Kept apart from
3
+ // playwright.config.js on purpose: probes live in the store, not in tests/;
4
+ // they report through their own reporter; and their screenshots and traces
5
+ // go to a folder of their own - Playwright empties its output folder on every
6
+ // run, and the last check's evidence must not be wiped by a probe.
7
+ const path = require('path');
8
+ const { defineConfig } = require('@playwright/test');
9
+
10
+ const PACKAGE_DIR = __dirname;
11
+ const USER_DIR = process.cwd();
12
+ const PROBE_DIR = process.env.KRYPTHEON_PROBE_DIR || path.join(USER_DIR, 'tests');
13
+
14
+ // The same .env reading as playwright.config.js, for the same reasons.
15
+ const secrets = require(path.join(PACKAGE_DIR, 'kryptheon-secrets.js'));
16
+ const values = secrets.readEnvFile(path.join(USER_DIR, '.env'));
17
+ for (const name of Object.keys(values)) {
18
+ if (!secrets.isSet(process.env[name])) process.env[name] = values[name];
19
+ }
20
+
21
+ module.exports = defineConfig({
22
+ testDir: PROBE_DIR,
23
+ testMatch: ['**/*.kxprobe.js'],
24
+ outputDir: path.join(PROBE_DIR, 'output'),
25
+ fullyParallel: false,
26
+ workers: 1,
27
+ retries: 0,
28
+ // Room for the gap before each run and for opening the page again after it.
29
+ timeout: 60000,
30
+ reporter: [[path.join(PACKAGE_DIR, 'kryptheon-probe-reporter.js')]],
31
+ use: {
32
+ headless: true,
33
+ channel: 'chromium',
34
+ screenshot: 'off',
35
+ trace: 'off',
36
+ },
37
+ });