kryptheon 0.1.70 → 0.1.72

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
@@ -38,6 +38,7 @@ const fs = require('fs');
38
38
  const path = require('path');
39
39
  const keys = require('./kryptheon-keys.js');
40
40
  const code = require('./kryptheon-code.js');
41
+ const aiapp = require('./kryptheon-aiapp.js');
41
42
 
42
43
  const SKIP_DIRS = new Set([
43
44
  'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.svelte-kit',
@@ -103,6 +104,9 @@ function listFiles(root) {
103
104
  }
104
105
 
105
106
  /** A line of code fit to print: trimmed, short, and with any key in it masked. */
107
+ // what kryptheon-aiapp.js borrows to read a handler: the same names, the same way of following them
108
+ const AI_HELPERS = { requireOf: (t, n) => requireOf(t, n), memberChain: (n) => memberChain(n), resolveRef: (ctx, mod, p) => resolveRef(ctx, mod, p), snippet: (mod, line) => snippet(mod, line) };
109
+
106
110
  function snippet(mod, line) {
107
111
  let text = (mod.lines[line - 1] || '').trim();
108
112
  try {
@@ -2682,6 +2686,7 @@ function edgeRoutes(ctx, root, schema) {
2682
2686
  const g = judge({}, [element]);
2683
2687
  const db = readDb(ctx, handler, schema);
2684
2688
  const validation = readValidation(ctx, handler, [element], db);
2689
+ const ai = aiapp.routeAi(ctx, AI_HELPERS, handler, { path: '/functions/v1/' + name, middleware: [] });
2685
2690
  // true / false from supabase/config.toml; null when it does not say (a deploy flag like --no-verify-jwt is not in the code)
2686
2691
  const verify = jwt.has(name) ? jwt.get(name) : null;
2687
2692
  routes.push({
@@ -2703,6 +2708,7 @@ function edgeRoutes(ctx, root, schema) {
2703
2708
  : 'supabase/config.toml does not say: the platform asks for a JWT unless the function is deployed with --no-verify-jwt, which the code does not show - and the public anon key is a valid JWT, so this alone never means signed in' },
2704
2709
  db,
2705
2710
  validation,
2711
+ ...(ai ? { ai } : {}),
2706
2712
  });
2707
2713
  }
2708
2714
  return routes;
@@ -2838,6 +2844,7 @@ function nextRoutes(ctx, schema) {
2838
2844
  const methods = el && el.guards && el.guards.methods;
2839
2845
  const db = handlerRef.kind === 'fn' ? readDb(ctx, handlerRef, schema) : [];
2840
2846
  const validation = handlerRef.kind === 'fn' ? readValidation(ctx, handlerRef, elements, db) : { fields: [], schemas: [] };
2847
+ const ai = handlerRef.kind === 'fn' ? aiapp.routeAi(ctx, AI_HELPERS, handlerRef, { path: p, middleware: elements.map((e) => ({ name: e.text, source: e.source || null, file: e.file || null, line: e.line || null, usedFile: e.usedFile, usedLine: e.usedLine })) }) : null;
2841
2848
  routes.push({
2842
2849
  method: method === 'ANY' && methods && methods.size === 1 ? Array.from(methods)[0] : method,
2843
2850
  methods: method === 'ANY' && methods && methods.size > 1 ? Array.from(methods).sort() : undefined,
@@ -2855,6 +2862,7 @@ function nextRoutes(ctx, schema) {
2855
2862
  note: f.note,
2856
2863
  db,
2857
2864
  validation,
2865
+ ...(ai ? { ai } : {}),
2858
2866
  });
2859
2867
  };
2860
2868
  // a package that wraps the handler: withApiAuthRequired(handler) protects it; another one is not read
@@ -3025,6 +3033,7 @@ function mapProject(root, options) {
3025
3033
  const db = h ? readDb(ctx, h, schema) : [];
3026
3034
  const validation = h ? readValidation(ctx, h, elements, db) : { fields: [], schemas: [], why: 'the handler could not be followed' };
3027
3035
  const redirects = h ? readRedirects(ctx, h) : [];
3036
+ const ai = h ? aiapp.routeAi(ctx, AI_HELPERS, h, { path: r.path, middleware: elements.map((e) => ({ name: e.text, source: e.source || null, file: e.file || null, line: e.line || null, usedFile: e.usedFile, usedLine: e.usedLine })) }) : null;
3028
3037
  return {
3029
3038
  method: r.method,
3030
3039
  path: r.path,
@@ -3040,6 +3049,7 @@ function mapProject(root, options) {
3040
3049
  db,
3041
3050
  validation,
3042
3051
  redirects,
3052
+ ...(ai ? { ai } : {}),
3043
3053
  };
3044
3054
  });
3045
3055
  routes.push(...edgeRoutes(ctx, root, schema));
@@ -3073,6 +3083,9 @@ const ADVICE = {
3073
3083
  '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.',
3074
3084
  '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.',
3075
3085
  'no-role': 'allow only the roles that should be able to do this, and answer 403 for the others.',
3086
+ 'ai-open': 'require a signed-in person before it asks the AI (answer 401 otherwise), and add a limit on how many questions one person and one address may ask per minute and per day, kept on the server. If this route is meant to be open to anyone (a public demo), keep it open but add that limit, and tell me so.',
3087
+ 'ai-no-limit': 'add a limit on how many questions one signed-in person may ask, per minute and per day, kept on the server (not in the browser), and answer 429 when it is reached. Keep the rest of the route as it is.',
3088
+ 'ai-acts-alone': 'do not send or call what the AI wrote straight away: save it as a draft, and send it only when the person presses an approve button - and only to an address the person chose, never one the AI picked from what it read. Keep the rest of the route as it is.',
3076
3089
  '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.',
3077
3090
  '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.',
3078
3091
  '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.',
@@ -3123,6 +3136,23 @@ function toCheck(map) {
3123
3136
  for (const rd of r.redirects || []) {
3124
3137
  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]);
3125
3138
  }
3139
+ // a route that asks an AI: every answer is on the owner's bill, and what the AI wrote may be sent in their name.
3140
+ // Never sent to on the running app - read from the code only.
3141
+ if (r.ai && r.ai.calls && r.ai.calls.length) {
3142
+ const prov = aiapp.providerName(r.ai.calls[0].provider);
3143
+ const callAt = r.ai.calls.slice(0, 2).map((c) => c.file + ':' + c.line + ' ' + (c.code || ''));
3144
+ if (r.auth.status === STATUS.NOT && !r.ai.limited && !AUTH_PATH.test(r.path || '')) {
3145
+ add(r, 'ai-open', 'HIGH', name + ' asks ' + prov + ', with no sign-in check and no limit in front of it: anyone who finds the address can use your AI account, and every answer is on your bill', [r.file + ':' + r.line].concat(callAt));
3146
+ } else if (r.auth.status === STATUS.DETECTED && !r.ai.limited) {
3147
+ add(r, 'ai-no-limit', 'MEDIUM', name + ' asks ' + prov + ', and no limit on how often one person may call it was found: one account, or a script signed in as one, can run up your AI bill', [r.file + ':' + r.line].concat(callAt));
3148
+ }
3149
+ const acts = r.ai.approval ? [] : r.ai.acts || [];
3150
+ if (acts.length) {
3151
+ const a = acts[0];
3152
+ add(r, 'ai-acts-alone', 'MEDIUM', name + ' ' + a.what + (a.tool ? ' whenever the AI decides to (it is one of the AI\'s tools)' : ' with what the AI wrote') + ', and no step where a person approves it first was found: text written to trick the AI, in an email or a page it reads, can make it ' + (a.what === 'calls an address the AI chose' ? 'call any address' : 'send anything to anyone'),
3153
+ acts.slice(0, 3).map((x) => x.file + ':' + x.line + ' ' + (x.code || '')).concat(callAt.slice(0, 1)));
3154
+ }
3155
+ }
3126
3156
  // a route with no sign-in that changes something - sign-in and sign-up routes are open by nature
3127
3157
  if (writes && r.auth.status === STATUS.NOT && changing.length && !AUTH_PATH.test(r.path || '')) {
3128
3158
  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)));
@@ -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
+ });