kryptheon 0.1.71 → 0.1.73
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/bin/kryptheon.js +30 -3
- package/kryptheon-account.js +22 -3
- package/kryptheon-aiapp.js +416 -0
- package/kryptheon-api.js +131 -5
- package/kryptheon-autostart.js +47 -4
- package/kryptheon-dashboard-page.js +120 -4
- package/kryptheon-dashboard.html +24 -0
- package/kryptheon-dashboard.js +5 -0
- package/kryptheon-map.js +30 -0
- package/kryptheon-tour.js +697 -0
- package/package.json +6 -3
package/kryptheon-api.js
CHANGED
|
@@ -27,6 +27,7 @@ const authz = require('./kryptheon-authz.js');
|
|
|
27
27
|
const webhook = require('./kryptheon-webhook.js');
|
|
28
28
|
const csv = require('./kryptheon-csv.js');
|
|
29
29
|
const witnessDb = require('./kryptheon-witness.js');
|
|
30
|
+
const aiapp = require('./kryptheon-aiapp.js');
|
|
30
31
|
|
|
31
32
|
const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
|
|
32
33
|
const SIGN_IN = /(^|\/)(log-?in|sign-?in|session|auth\/(login|signin|token))$/i;
|
|
@@ -3161,6 +3162,10 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps, r
|
|
|
3161
3162
|
v.verdict = 'not tried';
|
|
3162
3163
|
v.why = (hook && hook.notTried ? hook.notTried : webhooks && !webhooks.ran ? webhooks.why : 'a webhook this run did not send to') + '; a provider\'s own webhook is the payments check\'s (npx kryptheon payments)';
|
|
3163
3164
|
}
|
|
3165
|
+
} else if (/^ai-/.test(t.kind)) {
|
|
3166
|
+
// a route that asks an AI is never sent to: each answer costs the owner money, and some send real email
|
|
3167
|
+
v.verdict = 'not tried';
|
|
3168
|
+
v.why = 'read from the code only: Kryptheon never sends a request to a route that asks an AI - each answer costs you money, and some send real messages';
|
|
3164
3169
|
} else if (kind === 'role') {
|
|
3165
3170
|
// "held" only when the roles run really tried this route as a role the policy forbids
|
|
3166
3171
|
// a try of a change no rule names (as the fewest permissions) is never "held" nor "confirmed": no rule says who may
|
|
@@ -3300,6 +3305,118 @@ async function runForged(root, options) {
|
|
|
3300
3305
|
return out;
|
|
3301
3306
|
}
|
|
3302
3307
|
|
|
3308
|
+
// --- what the app sends to the browser ------------------------------------------------
|
|
3309
|
+
|
|
3310
|
+
/**
|
|
3311
|
+
* Every page and list the app answers with no record in its address (and each one-record page, at a record the list
|
|
3312
|
+
* gave), read as each test account and with no session - GET only, nothing written - and looked through for:
|
|
3313
|
+
* a key or stored token that is only ever the server's (an AI provider's key, a Gmail refresh token), and a quiz sent
|
|
3314
|
+
* with its right answers. A key the same for two people, or sent to nobody signed in, is confirmed; one sent only to
|
|
3315
|
+
* the person it may belong to is a thing to check. No value is ever shown or saved: its kind and length only.
|
|
3316
|
+
* { ran, why, tried, findings }
|
|
3317
|
+
*/
|
|
3318
|
+
async function runAnswers(root, options) {
|
|
3319
|
+
const opts = options || {};
|
|
3320
|
+
const plan = planOf(root, opts);
|
|
3321
|
+
if (!plan.ran) return { ran: false, why: plan.why };
|
|
3322
|
+
const j = plan.journey;
|
|
3323
|
+
let origin;
|
|
3324
|
+
try {
|
|
3325
|
+
origin = authz.assertLocalTarget(opts.origin, null, { readOnly: opts.readOnly === true });
|
|
3326
|
+
} catch (err) {
|
|
3327
|
+
return { ran: false, why: 'the app must be on this computer (localhost or 127.0.0.1): ' + (opts.origin || 'no address was given') };
|
|
3328
|
+
}
|
|
3329
|
+
const signInPath = j.signIn ? normRoute(j.signIn.path || '') : null;
|
|
3330
|
+
const gets = [];
|
|
3331
|
+
for (const r of plan.map.routes || []) {
|
|
3332
|
+
if (r.unmounted || !r.path || r.method !== 'GET' || r.kind === 'webhook') continue;
|
|
3333
|
+
const template = normRoute(r.path);
|
|
3334
|
+
const params = (template.match(/\{[^}]+\}/g) || []).length;
|
|
3335
|
+
if (params > 1 || /\*/.test(template) || template === signInPath || /log-?out|sign-?out/i.test(template) || PLUMBING.test(template) || gets.some((g) => g.template === template)) continue;
|
|
3336
|
+
gets.push({ template, params });
|
|
3337
|
+
}
|
|
3338
|
+
gets.splice(30);
|
|
3339
|
+
if (!gets.length) return { ran: false, why: 'the map found no page or list to read' };
|
|
3340
|
+
const accounts = j.signIn ? j.accounts.usable.slice(0, 2) : [];
|
|
3341
|
+
const ctx = authz.makeContext({ baseUrl: origin, allowOrigins: [origin], fetch: opts.fetch, passwords: Object.fromEntries(accounts.map((a) => [a.email, a.password])),
|
|
3342
|
+
maxRequests: 10 + (accounts.length + 1) * gets.length * 2, readOnly: opts.readOnly === true,
|
|
3343
|
+
allowWrites: j.signIn && j.signIn.path && !j.signIn.bearer ? [String(j.signIn.method || 'POST').toUpperCase() + ' ' + j.signIn.path] : [] });
|
|
3344
|
+
const readers = [{ who: 'nobody signed in', session: authz.makeSession(ctx, 'nobody', 'nobody', '') }];
|
|
3345
|
+
for (const a of accounts) {
|
|
3346
|
+
const s = authz.makeSession(ctx, 'account', a.email, a.password);
|
|
3347
|
+
const f = { [j.signIn.emailField]: a.email, [j.signIn.passwordField]: a.password };
|
|
3348
|
+
const r = authz.replyOf(await s.send(j.signIn.method, j.signIn.path, j.signIn.encoding === 'form' ? { form: f } : { json: f }));
|
|
3349
|
+
if (r.kind !== 'refused' && r.kind !== 'server-error' && r.kind !== 'no-answer') readers.push({ who: a.email, session: s, account: true });
|
|
3350
|
+
}
|
|
3351
|
+
const listIn = (json) => (Array.isArray(json) ? json : json && typeof json === 'object' ? Object.values(json).find((v) => Array.isArray(v)) || null : null);
|
|
3352
|
+
const out = { ran: true, tried: [], findings: [] };
|
|
3353
|
+
const seenKeys = new Map(); // value -> [{ who, at, field, path, label, account }]
|
|
3354
|
+
const quiz = new Map(); // route -> { field, who }
|
|
3355
|
+
for (const rd of readers) {
|
|
3356
|
+
const lists = new Map();
|
|
3357
|
+
for (const a of gets) {
|
|
3358
|
+
let at = a.template;
|
|
3359
|
+
if (a.params) {
|
|
3360
|
+
const listing = a.template.slice(0, a.template.indexOf('/{'));
|
|
3361
|
+
const items = lists.get(listing);
|
|
3362
|
+
const first = items && items.find((it) => it && typeof it === 'object' && (it.id !== undefined || it.uuid !== undefined || it.slug !== undefined));
|
|
3363
|
+
if (!first) continue;
|
|
3364
|
+
at = a.template.replace(/\{[^}]+\}/, encodeURIComponent(String(first.id !== undefined ? first.id : first.uuid !== undefined ? first.uuid : first.slug)));
|
|
3365
|
+
}
|
|
3366
|
+
let res;
|
|
3367
|
+
try { res = await rd.session.send('GET', at, {}); } catch (err) { if (authz.isRequestLimit(err)) break; throw err; }
|
|
3368
|
+
out.tried.push({ what: 'GET ' + a.template, as: rd.who, status: res.status });
|
|
3369
|
+
if (res.status !== 200 || res.json === undefined) continue;
|
|
3370
|
+
if (!a.params) { const l = listIn(res.json); if (l) lists.set(a.template, l); }
|
|
3371
|
+
const found = aiapp.scanAnswer(res.json);
|
|
3372
|
+
for (const s of found.secrets) {
|
|
3373
|
+
// a person's own token where signing in or connecting an account is the point is not a leak by itself
|
|
3374
|
+
if (!/^an? (Anthropic|OpenAI|Google API|Groq|Replicate|Hugging|OpenRouter|xAI|Stripe|Resend|SendGrid|Slack|GitHub)/.test(s.label) && aiapp.TOKEN_MEANT.test(a.template)) continue;
|
|
3375
|
+
if (!seenKeys.has(s.value)) seenKeys.set(s.value, []);
|
|
3376
|
+
seenKeys.get(s.value).push({ who: rd.who, account: !!rd.account, at: 'GET ' + a.template, field: s.field, path: s.path, label: s.label, length: s.value.length });
|
|
3377
|
+
}
|
|
3378
|
+
if (found.quiz.length && !aiapp.ANSWERS_MEANT.test(a.template) && !quiz.has('GET ' + a.template)) quiz.set('GET ' + a.template, { field: found.quiz[0].field, path: found.quiz[0].path, who: rd.who, count: found.quiz.length });
|
|
3379
|
+
}
|
|
3380
|
+
}
|
|
3381
|
+
const done = new Set();
|
|
3382
|
+
for (const sightings of seenKeys.values()) {
|
|
3383
|
+
const first = sightings[0];
|
|
3384
|
+
if (done.has(first.at + '|' + first.field)) continue;
|
|
3385
|
+
done.add(first.at + '|' + first.field);
|
|
3386
|
+
const people = Array.from(new Set(sightings.map((x) => x.who)));
|
|
3387
|
+
const shared = people.length > 1 || people.includes('nobody signed in');
|
|
3388
|
+
const f = {
|
|
3389
|
+
kind: 'secret-in-answer', where: first.at, field: first.field || null, status: shared ? 'confirmed' : 'verification required', severity: shared ? 'HIGH' : 'MEDIUM',
|
|
3390
|
+
headline: shared
|
|
3391
|
+
? first.at + ' sends ' + first.label + ' to the browser of ' + (people.includes('nobody signed in') ? 'anyone, signed in or not' : 'more than one person') + ': whoever has it can use it as if they were your server'
|
|
3392
|
+
: first.at + ' sends ' + first.label + ' to the browser - to check: even shown only to its owner, anything running in that page can take it; the server should keep it and send at most its last 4 characters',
|
|
3393
|
+
proof: sightings.slice(0, 3).map((x) => 'As ' + x.who + ': ' + x.at + ' answered with ' + x.label + ' in ' + x.path + ' (' + x.length + ' characters, not shown).'),
|
|
3394
|
+
};
|
|
3395
|
+
f.fixPrompt = ['Kryptheon read what my running app sends to the browser:', '', f.headline + '.', '', f.proof.join('\n'), '',
|
|
3396
|
+
'Keep this value on the server only: remove it from that answer (send at most its last 4 characters, to show which one is set). If it is an API key that has been sent like this, make a new one at the provider and delete the old one. Change nothing else.'].join('\n');
|
|
3397
|
+
out.findings.push(f);
|
|
3398
|
+
}
|
|
3399
|
+
for (const [where, q] of quiz) {
|
|
3400
|
+
const f = {
|
|
3401
|
+
kind: 'quiz-answers-sent', where, field: q.field, status: 'verification required', severity: 'MEDIUM',
|
|
3402
|
+
headline: where + ' sends each question\'s right answer (' + q.field + ') along with it - to check: a student can read the answers in the browser before answering; fine only after they answer, or for a teacher',
|
|
3403
|
+
proof: ['As ' + q.who + ': ' + where + ' answered with ' + q.count + ' question' + (q.count === 1 ? '' : 's') + ' that each carry ' + q.field + ' (values not shown).'],
|
|
3404
|
+
};
|
|
3405
|
+
f.fixPrompt = ['Kryptheon read what my running app sends to the browser:', '', f.headline + '.', '', f.proof[0], '',
|
|
3406
|
+
'First check whether students see this answer. If they do, leave the right answers out of it, and check each answer on the server when it is sent; send which ones were right only in the result after answering. Change nothing else.'].join('\n');
|
|
3407
|
+
out.findings.push(f);
|
|
3408
|
+
}
|
|
3409
|
+
return out;
|
|
3410
|
+
}
|
|
3411
|
+
|
|
3412
|
+
/** Which answer finding a headline is, for a re-check that has only the headline: 'secret-in-answer', 'quiz-answers-sent' or null. */
|
|
3413
|
+
function answerKindOf(headline) {
|
|
3414
|
+
const h = String(headline || '');
|
|
3415
|
+
if (/^GET \S+ sends .+ to the browser/.test(h)) return 'secret-in-answer';
|
|
3416
|
+
if (/^GET \S+ sends each question's right answer/.test(h)) return 'quiz-answers-sent';
|
|
3417
|
+
return null;
|
|
3418
|
+
}
|
|
3419
|
+
|
|
3303
3420
|
/**
|
|
3304
3421
|
* The whole run on an app on this computer: across organizations and without
|
|
3305
3422
|
* a session, then bad values, then (only with the owner's permissions file and
|
|
@@ -3329,6 +3446,8 @@ async function runApi(root, options) {
|
|
|
3329
3446
|
}
|
|
3330
3447
|
};
|
|
3331
3448
|
const jobsRun = await contained('Jobs run twice', () => runJobs(root, shared));
|
|
3449
|
+
// read-only, and before anything below changes a record: what the app sends to the browser
|
|
3450
|
+
const answersRun = await contained('Keys and answers in what the app sends', () => runAnswers(root, shared));
|
|
3332
3451
|
const wall = await contained('Across organizations and without a session', () => runWall(root, shared));
|
|
3333
3452
|
const forged = await contained('Who is calling, as the request says', () => runForged(root, shared));
|
|
3334
3453
|
const webhooks = await contained('Webhooks', () => webhook.run(root, shared));
|
|
@@ -3349,14 +3468,14 @@ async function runApi(root, options) {
|
|
|
3349
3468
|
if (witness.ok && !opts.witness) await witness.close();
|
|
3350
3469
|
const verdicts = verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, stepsRun, redirectsRun);
|
|
3351
3470
|
const seen = new Set();
|
|
3352
|
-
const findings = (grantsRun.ran ? grantsRun.findings : []).concat(refsRun.ran ? refsRun.findings : []).concat(wall.ran ? wall.findings : []).concat(redirectsRun.ran ? redirectsRun.findings : []).concat(refundsRun.ran ? refundsRun.findings : []).concat(forged.ran ? forged.findings : []).concat(webhooks.ran ? webhooks.findings : []).concat(exportsRun.ran ? exportsRun.findings : []).concat(jobsRun.ran ? jobsRun.findings : []).concat(keptRun.ran ? keptRun.findings : []).concat(createsRun.ran ? createsRun.findings : []).concat(limitsRun.ran ? limitsRun.findings : []).concat(stepsRun.ran ? stepsRun.findings : []).concat(onceRun.ran ? onceRun.findings : []).concat(roleRun && roleRun.ran ? roleRun.findings : []).concat(invalid.ran ? invalid.findings : []).filter((f) => {
|
|
3471
|
+
const findings = (grantsRun.ran ? grantsRun.findings : []).concat(answersRun.ran ? answersRun.findings : []).concat(refsRun.ran ? refsRun.findings : []).concat(wall.ran ? wall.findings : []).concat(redirectsRun.ran ? redirectsRun.findings : []).concat(refundsRun.ran ? refundsRun.findings : []).concat(forged.ran ? forged.findings : []).concat(webhooks.ran ? webhooks.findings : []).concat(exportsRun.ran ? exportsRun.findings : []).concat(jobsRun.ran ? jobsRun.findings : []).concat(keptRun.ran ? keptRun.findings : []).concat(createsRun.ran ? createsRun.findings : []).concat(limitsRun.ran ? limitsRun.findings : []).concat(stepsRun.ran ? stepsRun.findings : []).concat(onceRun.ran ? onceRun.findings : []).concat(roleRun && roleRun.ran ? roleRun.findings : []).concat(invalid.ran ? invalid.findings : []).filter((f) => {
|
|
3353
3472
|
const k = f.kind + '|' + f.where + '|' + (f.field || '');
|
|
3354
3473
|
return seen.has(k) ? false : (seen.add(k), true);
|
|
3355
3474
|
});
|
|
3356
3475
|
const left = (grantsRun.ran ? grantsRun.left : []).concat(refsRun.ran ? refsRun.left : []).concat(webhooks.ran ? webhooks.left : []).concat(refundsRun.ran ? refundsRun.left : []).concat(exportsRun.ran ? exportsRun.left : []).concat(jobsRun.ran ? jobsRun.left : []).concat(keptRun.ran ? keptRun.left : []).concat(createsRun.ran ? createsRun.left : []).concat(limitsRun.ran ? limitsRun.left : []).concat(stepsRun.ran ? stepsRun.left : []).concat(onceRun.ran ? onceRun.left : []).concat(wall.ran ? wall.result.seeded || [] : []).concat(roleRun && roleRun.ran ? roleRun.result.seeded || [] : []).concat(wall.ran ? leftBehind(wall.result.attempts) : []).concat(invalid.ran ? invalid.left : []).concat(roleRun && roleRun.ran ? leftBehind(roleRun.result.attempts) : []);
|
|
3357
3476
|
return {
|
|
3358
3477
|
ran: wall.ran || invalid.ran, why: wall.ran || invalid.ran ? null : wall.why, checkedAt: new Date().toISOString(),
|
|
3359
|
-
origin: opts.origin, grants: grantsRun, refs: refsRun, wall: wall, forged: forged, webhooks: webhooks, exports: exportsRun, jobs: jobsRun, kept: keptRun, creates: createsRun, limits: limitsRun, steps: stepsRun, redirects: redirectsRun, refunds: refundsRun, stepsAtOnce: onceRun, invalid: invalid, roles: roleRun, verdicts: verdicts, findings: findings, left: left,
|
|
3478
|
+
origin: opts.origin, grants: grantsRun, refs: refsRun, wall: wall, forged: forged, webhooks: webhooks, exports: exportsRun, jobs: jobsRun, kept: keptRun, creates: createsRun, limits: limitsRun, steps: stepsRun, redirects: redirectsRun, refunds: refundsRun, stepsAtOnce: onceRun, answers: answersRun, invalid: invalid, roles: roleRun, verdicts: verdicts, findings: findings, left: left,
|
|
3360
3479
|
notTried: (wall.plan ? wall.plan.notTried : []).concat(invalid.ran ? invalid.notTried : []),
|
|
3361
3480
|
writes: writesOf(m, wall),
|
|
3362
3481
|
};
|
|
@@ -3465,6 +3584,13 @@ async function runLive(root, options) {
|
|
|
3465
3584
|
}
|
|
3466
3585
|
}
|
|
3467
3586
|
const stub = { ran: false, why: 'not on a live app - it writes; run it on a test copy' };
|
|
3587
|
+
let answersRun;
|
|
3588
|
+
try {
|
|
3589
|
+
answersRun = await runAnswers(root, Object.assign({}, opts, { map: m, origin, readOnly: true }));
|
|
3590
|
+
} catch (err) {
|
|
3591
|
+
if (!(err && (err.code === authz.READ_ONLY || authz.isRequestLimit(err)))) throw err;
|
|
3592
|
+
answersRun = { ran: false, why: 'stopped: ' + err.message };
|
|
3593
|
+
}
|
|
3468
3594
|
// Judged first, then every string kept from the tries masked - the answers, their excerpts, the lines printed from
|
|
3469
3595
|
// them: a live app's records are real people's, and none of their values is shown or saved.
|
|
3470
3596
|
const maskDeep = (v, depth) => {
|
|
@@ -3487,7 +3613,7 @@ async function runLive(root, options) {
|
|
|
3487
3613
|
if (roleRun.ran) { roleRun.result = maskDeep(roleRun.result, 0); roleRun.findings = maskDeep(roleRun.findings, 0); }
|
|
3488
3614
|
// the roles run keeps organizations apart too, so it finds the same reads across organizations again: said once
|
|
3489
3615
|
const seenLive = new Set();
|
|
3490
|
-
const findings = (wall.findings || []).concat(roleRun.ran ? roleRun.findings : []).filter((f) => {
|
|
3616
|
+
const findings = (wall.findings || []).concat(roleRun.ran ? roleRun.findings : []).concat(answersRun.ran ? answersRun.findings : []).filter((f) => {
|
|
3491
3617
|
const k = f.kind + '|' + f.where + '|' + (f.field || '');
|
|
3492
3618
|
return seenLive.has(k) ? false : (seenLive.add(k), true);
|
|
3493
3619
|
}).map((f) => maskDeep(Object.assign({}, f, { live: true }), 0));
|
|
@@ -3495,7 +3621,7 @@ async function runLive(root, options) {
|
|
|
3495
3621
|
return {
|
|
3496
3622
|
ran: true, live: true, why: null, checkedAt: new Date().toISOString(), origin,
|
|
3497
3623
|
wall, forged: stub, webhooks: stub, exports: stub, jobs: stub, kept: stub, creates: stub, limits: stub, steps: stub, redirects: stub, refunds: stub, stepsAtOnce: stub,
|
|
3498
|
-
roles: roleRun, invalid: stub, grants: stub, refs: stub,
|
|
3624
|
+
roles: roleRun, invalid: stub, grants: stub, refs: stub, answers: answersRun,
|
|
3499
3625
|
findings, left: [], leftOut: LIVE_LEFT_OUT,
|
|
3500
3626
|
verdicts: verdictsFor(toCheck, wall, stub, roleRun.ran ? roleRun : null, stub, stub, stub, stub),
|
|
3501
3627
|
notTried: wall.plan ? wall.plan.notTried : [],
|
|
@@ -3685,4 +3811,4 @@ function apiLines(run) {
|
|
|
3685
3811
|
return out;
|
|
3686
3812
|
}
|
|
3687
3813
|
|
|
3688
|
-
module.exports = { dbTargetsFor, stepTableOf, dbRecordsFor, runLive, maskValues, LIVE_LEFT_OUT, tokenAccountsOf, TOKEN_PREFIX, limitPairsIn, dbDoubleEffects, oneLeft, inferPermissions, grantRulesOf, runGrants, runRefs, probesOf, stepEffectOf, reconcile, isUpdateRoute, storedAs, updateProbesOf, heldStrength, runSteps, runRedirects, OUTSIDE, runRefundCap, PLUMBING, runStepsAtOnce, doubleEffects, numbersMoved, runKept, runCreates, COSTLY_RECORD, runLimits, limitPairOf, valueIn, plainFieldOf, runJobs, countsIn, JOB_PATH, runForged, personIn, REPORT_FILE, verdictsFor, runApi, reportOf, saveReport, apiLines, badValueFor, runInvalid, signInOf, emailsIn, accountsOf, wordsOf, sampleValue, allowedByName, actionOf, journeyFromMap, planOf, planLines, wallPolicy, runWall, findingsOf, fixPrompt, leftBehind, wallLines, DRAFT_FILE, permissionName, draftPolicy, writeDraft, runRoles };
|
|
3814
|
+
module.exports = { answerKindOf, runAnswers, dbTargetsFor, stepTableOf, dbRecordsFor, runLive, maskValues, LIVE_LEFT_OUT, tokenAccountsOf, TOKEN_PREFIX, limitPairsIn, dbDoubleEffects, oneLeft, inferPermissions, grantRulesOf, runGrants, runRefs, probesOf, stepEffectOf, reconcile, isUpdateRoute, storedAs, updateProbesOf, heldStrength, runSteps, runRedirects, OUTSIDE, runRefundCap, PLUMBING, runStepsAtOnce, doubleEffects, numbersMoved, runKept, runCreates, COSTLY_RECORD, runLimits, limitPairOf, valueIn, plainFieldOf, runJobs, countsIn, JOB_PATH, runForged, personIn, REPORT_FILE, verdictsFor, runApi, reportOf, saveReport, apiLines, badValueFor, runInvalid, signInOf, emailsIn, accountsOf, wordsOf, sampleValue, allowedByName, actionOf, journeyFromMap, planOf, planLines, wallPolicy, runWall, findingsOf, fixPrompt, leftBehind, wallLines, DRAFT_FILE, permissionName, draftPolicy, writeDraft, runRoles };
|
package/kryptheon-autostart.js
CHANGED
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
* the folder itself. The file says what it is and runs one thing:
|
|
10
10
|
* npx kryptheon@latest dashboard, in a minimized window on the taskbar. A
|
|
11
11
|
* window, not a hidden process: something that starts by itself at sign-in
|
|
12
|
-
* should be seen, and closing it stops it.
|
|
12
|
+
* should be seen, and closing it stops it. The page itself opens in the
|
|
13
|
+
* browser once a day, at the first sign-in of the day - asked for by the
|
|
14
|
+
* owner, so the dashboard is in front of the person daily without a command.
|
|
13
15
|
*
|
|
14
16
|
* Only the file this module wrote is ever removed: it is recognised by its
|
|
15
17
|
* first lines, never by its name alone.
|
|
@@ -77,10 +79,12 @@ function script(root) {
|
|
|
77
79
|
':run',
|
|
78
80
|
'title Kryptheon dashboard - ' + name,
|
|
79
81
|
'rem npx starts the command "kryptheon": never look for it in the current folder,',
|
|
80
|
-
'rem where a Kryptheon.cmd launcher may sit
|
|
82
|
+
'rem where a Kryptheon.cmd launcher may sit. The dashboard opens in the browser',
|
|
83
|
+
'rem once a day - at the first sign-in of the day - and not again that day.',
|
|
81
84
|
'set NoDefaultCurrentDirectoryInExePath=1',
|
|
82
85
|
'set KRYPTHEON_LAUNCHER=1',
|
|
83
|
-
'set KRYPTHEON_NO_OPEN=
|
|
86
|
+
'set KRYPTHEON_NO_OPEN=',
|
|
87
|
+
'set KRYPTHEON_OPEN_DAILY=1',
|
|
84
88
|
'cd /d ' + quoted + ' || goto gone',
|
|
85
89
|
'echo.',
|
|
86
90
|
'echo Kryptheon dashboard, started when you signed in, for:',
|
|
@@ -145,4 +149,43 @@ function setAutostart(root, on, env, platform) {
|
|
|
145
149
|
return Object.assign({ ok: true }, status(root, env, platform));
|
|
146
150
|
}
|
|
147
151
|
|
|
148
|
-
|
|
152
|
+
/**
|
|
153
|
+
* A file this module wrote with an older version's text - one that never
|
|
154
|
+
* opened the browser - is written again with today's. Only a file that carries
|
|
155
|
+
* the mark, and only when it is on; anything else is left as it is.
|
|
156
|
+
*/
|
|
157
|
+
function refresh(root, env, platform) {
|
|
158
|
+
const s = status(root, env, platform);
|
|
159
|
+
if (!s.on) return { ok: true, changed: false };
|
|
160
|
+
try {
|
|
161
|
+
const now = fs.readFileSync(s.file, 'utf8');
|
|
162
|
+
const want = script(root);
|
|
163
|
+
if (now === want) return { ok: true, changed: false };
|
|
164
|
+
fs.writeFileSync(s.file, want, 'utf8');
|
|
165
|
+
return { ok: true, changed: true };
|
|
166
|
+
} catch (err) {
|
|
167
|
+
return { ok: false, changed: false, why: err.message };
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Whether the dashboard started at sign-in should open the browser now: yes
|
|
173
|
+
* the first time on a day, no after that. The day is kept in the project's own
|
|
174
|
+
* Kryptheon folder. Asked only when started with KRYPTHEON_OPEN_DAILY.
|
|
175
|
+
*/
|
|
176
|
+
function firstOpenToday(dir, now) {
|
|
177
|
+
const day = (now || new Date()).toLocaleDateString('en-CA');
|
|
178
|
+
const file = path.join(dir, 'opened-on.txt');
|
|
179
|
+
let last = '';
|
|
180
|
+
try { last = fs.readFileSync(file, 'utf8').trim(); } catch (err) { last = ''; }
|
|
181
|
+
if (last === day) return false;
|
|
182
|
+
try {
|
|
183
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
184
|
+
fs.writeFileSync(file, day + '\n', 'utf8');
|
|
185
|
+
} catch (err) {
|
|
186
|
+
/* opened anyway: a page shown twice is better than never */
|
|
187
|
+
}
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
module.exports = { startupDir, fileFor, script, status, setAutostart, refresh, firstOpenToday, MARK };
|
|
@@ -53,6 +53,7 @@
|
|
|
53
53
|
terminal: 'M4 5h16v14H4zM7 9l3 3-3 3M13 15h4',
|
|
54
54
|
folder: 'M3 6h6l2 2h10v11H3z',
|
|
55
55
|
dot: 'M12 12h.01',
|
|
56
|
+
up: 'M12 19V5m-6 6l6-6 6 6',
|
|
56
57
|
};
|
|
57
58
|
function icon(name, size) {
|
|
58
59
|
var s = svgEl('svg', {
|
|
@@ -104,6 +105,26 @@
|
|
|
104
105
|
busy = on;
|
|
105
106
|
Array.prototype.forEach.call(document.querySelectorAll('[data-action]'), function (b) { b.disabled = on; });
|
|
106
107
|
if (state) renderLaunch();
|
|
108
|
+
tell();
|
|
109
|
+
}
|
|
110
|
+
// The set-up is finished (the guide's end): kryptheon.tech is told once, so its account page opens instead of the
|
|
111
|
+
// first-time journey. Asked again on a later load while it has not been recorded there.
|
|
112
|
+
var setupSaid = false;
|
|
113
|
+
function sayDone() {
|
|
114
|
+
if (setupSaid || !state || !state.account || !state.account.connected || state.account.setupReported) return;
|
|
115
|
+
setupSaid = true;
|
|
116
|
+
post('/api/account/setup-done', {}).then(function () { load(); }, function () { setupSaid = false; });
|
|
117
|
+
}
|
|
118
|
+
window.addEventListener('kryptheon:setup-done', sayDone);
|
|
119
|
+
function guideFinished() {
|
|
120
|
+
try { if (JSON.parse(window.localStorage.getItem('kryptheon.guide.v1') || '{}').done) return true; } catch (e) { /* read below */ }
|
|
121
|
+
// set up before the guide existed: the address saved and a flow recorded is a finished set-up too
|
|
122
|
+
var rec = (state && state.steps || []).filter(function (s) { return s.action && s.action.kind === 'record'; })[0];
|
|
123
|
+
return !!(state && state.app && state.app.address && rec && rec.count > 0);
|
|
124
|
+
}
|
|
125
|
+
// The guide (kryptheon-tour.js) follows the page: what the server last said, and whether something runs.
|
|
126
|
+
function tell() {
|
|
127
|
+
try { window.dispatchEvent(new CustomEvent('kryptheon:state', { detail: { state: state, busy: busy } })); } catch (e) { /* no guide then */ }
|
|
107
128
|
}
|
|
108
129
|
// The clipboard, and when a browser refuses it, the older way: the text
|
|
109
130
|
// put in a box off the screen, selected and copied.
|
|
@@ -181,6 +202,14 @@
|
|
|
181
202
|
connectInput.setAttribute('aria-label', 'Your connect code');
|
|
182
203
|
connectInput.autocomplete = 'off';
|
|
183
204
|
connectInput.spellcheck = false;
|
|
205
|
+
// Handed over by kryptheon.tech's "Open my dashboard" (#connect=kd_...): put in the box, never sent by itself -
|
|
206
|
+
// the person presses Connect, so a link from anywhere else cannot tie this dashboard to someone else's account.
|
|
207
|
+
// Taken out of the address at once; the guide then starts at Connect.
|
|
208
|
+
var handed = /^#connect=(kd_[A-Za-z0-9_-]{20,100})$/.exec(window.location.hash || '');
|
|
209
|
+
if (handed) {
|
|
210
|
+
connectInput.value = handed[1];
|
|
211
|
+
try { window.history.replaceState(null, '', '#tour-connect'); } catch (e) { window.location.hash = 'tour-connect'; }
|
|
212
|
+
}
|
|
184
213
|
|
|
185
214
|
/* ------------------------------------ jobs ------------------------------------ */
|
|
186
215
|
|
|
@@ -329,6 +358,7 @@
|
|
|
329
358
|
{ id: 'fixes', title: 'Proven fixes', icon: 'wrench' },
|
|
330
359
|
{ id: 'checks', title: 'Checks', icon: 'toggle' },
|
|
331
360
|
{ id: 'runs', title: 'Runs', icon: 'play' },
|
|
361
|
+
{ id: 'plan', title: 'Upgrade your plan', icon: 'up' },
|
|
332
362
|
{ id: 'storage', title: 'Where this lives', icon: 'box' },
|
|
333
363
|
];
|
|
334
364
|
|
|
@@ -1293,8 +1323,8 @@
|
|
|
1293
1323
|
if (a.available) title.appendChild(el('span', 'tag ' + (a.on ? 'leaf' : ''), a.on ? 'on' : 'off'));
|
|
1294
1324
|
text.appendChild(title);
|
|
1295
1325
|
text.appendChild(el('span', null, !a.available ? (a.why || 'Not on this computer.')
|
|
1296
|
-
: a.on ? 'When you sign in to Windows, this dashboard starts by itself in a small window on the taskbar,
|
|
1297
|
-
: 'Switch it on and this dashboard starts by itself every time you sign in to Windows, in a small window on the taskbar
|
|
1326
|
+
: a.on ? 'When you sign in to Windows, this dashboard starts by itself in a small window on the taskbar, and opens in your browser the first time each day. Closing that taskbar window stops it until you sign in again.'
|
|
1327
|
+
: 'Switch it on and this dashboard starts by itself every time you sign in to Windows, in a small window on the taskbar - and opens in your browser once a day, at your first sign-in. Switch it off here any time.'));
|
|
1298
1328
|
row.appendChild(text);
|
|
1299
1329
|
box.appendChild(row);
|
|
1300
1330
|
renderDaily(box);
|
|
@@ -1798,7 +1828,11 @@
|
|
|
1798
1828
|
connectInput.value = '';
|
|
1799
1829
|
toast('Connected.');
|
|
1800
1830
|
load();
|
|
1801
|
-
}, function (err) {
|
|
1831
|
+
}, function (err) {
|
|
1832
|
+
toast(err.message);
|
|
1833
|
+
// the guide says it too, beside the box, with where a working code comes from
|
|
1834
|
+
try { window.dispatchEvent(new CustomEvent('kryptheon:connect-failed', { detail: { why: err.message } })); } catch (e) { /* no guide */ }
|
|
1835
|
+
});
|
|
1802
1836
|
}));
|
|
1803
1837
|
box.appendChild(row2);
|
|
1804
1838
|
var help = el('div', 'fallback');
|
|
@@ -1842,12 +1876,91 @@
|
|
|
1842
1876
|
if (!small) wrap.appendChild(el('div', 'd-text', 'This month\'s 5 free fix prompts are used.'));
|
|
1843
1877
|
wrap.appendChild(button('sm', 'arrow', 'Unlock with Pro - ₹499/month', function (e) {
|
|
1844
1878
|
if (e) e.stopPropagation();
|
|
1845
|
-
|
|
1879
|
+
go('plan');
|
|
1846
1880
|
}));
|
|
1847
1881
|
}
|
|
1848
1882
|
return wrap;
|
|
1849
1883
|
}
|
|
1850
1884
|
|
|
1885
|
+
/* ------------------------------- upgrade your plan ------------------------------- */
|
|
1886
|
+
|
|
1887
|
+
// The plans, and a way to move up any day. Payment is never taken here: the button opens the account page on
|
|
1888
|
+
// kryptheon.tech, where Razorpay is. When the person comes back to this tab, the plan is asked for again (and every
|
|
1889
|
+
// 20 seconds for half an hour), so the new plan shows here without a button - the entitlement function's word, never
|
|
1890
|
+
// this page's guess.
|
|
1891
|
+
var PLAN_CARDS = [
|
|
1892
|
+
{ id: 'starter', name: 'Starter', price: 'Free', per: 'no card needed', lines: ['Every problem your checks find, with proof', '5 fix prompts an app, every month', '1 app checked every night, with counts'] },
|
|
1893
|
+
{ id: 'pro', name: 'Pro', price: '₹499', per: '/ month', best: true, lines: ['Every fix prompt, for every problem', 'One prompt that fixes them all at once', 'Every night, a test break-in on a copy of your database', 'A morning email, and an alert when a new problem appears', 'Export your findings as a CSV file', 'Up to 3 apps, 90 days of history'] },
|
|
1894
|
+
{ id: 'studio', name: 'Studio', price: '₹799', per: '/ month', lines: ['Everything in Pro', 'Every client app on one screen - up to 15', 'A report you can hand a client, under your own name', 'Every app\'s findings in one CSV file', 'Alerts to Slack or any webhook', 'A year of history'] },
|
|
1895
|
+
];
|
|
1896
|
+
var PAY_PAGE = 'https://kryptheon.tech/dashboard/#plan';
|
|
1897
|
+
var upgradeSince = 0;
|
|
1898
|
+
var upgradeFrom = null;
|
|
1899
|
+
function planNow() { var a = state && state.account; return a && a.connected ? a.plan : null; }
|
|
1900
|
+
function askPlanAgain() {
|
|
1901
|
+
if (!upgradeSince || Date.now() - upgradeSince > 30 * 60 * 1000) { upgradeSince = 0; return; }
|
|
1902
|
+
post('/api/account/refresh', {}).then(function () { return load(); }).then(function () {
|
|
1903
|
+
var now = planNow();
|
|
1904
|
+
if (now && now !== upgradeFrom && now !== 'starter') {
|
|
1905
|
+
upgradeSince = 0;
|
|
1906
|
+
toast('You are on ' + (PLAN_WORD[now] || now) + ' now - every fix prompt is open.');
|
|
1907
|
+
}
|
|
1908
|
+
}, function () {});
|
|
1909
|
+
}
|
|
1910
|
+
window.addEventListener('focus', askPlanAgain);
|
|
1911
|
+
document.addEventListener('visibilitychange', function () { if (!document.hidden) askPlanAgain(); });
|
|
1912
|
+
setInterval(askPlanAgain, 20000);
|
|
1913
|
+
function renderPlan() {
|
|
1914
|
+
var box = byId('planBox');
|
|
1915
|
+
if (!box) return;
|
|
1916
|
+
clear(box);
|
|
1917
|
+
var now = planNow();
|
|
1918
|
+
var rank = { starter: 0, pro: 1, studio: 2 };
|
|
1919
|
+
box.appendChild(el('p', 'plan-now', now ? 'You are on ' + (PLAN_WORD[now] || now) + '.' : 'This dashboard is not connected to an account yet.'));
|
|
1920
|
+
if (!now) {
|
|
1921
|
+
var hint = el('div', 'plan-hint');
|
|
1922
|
+
hint.appendChild(el('span', null, 'Connect it first - Dashboard, Your account - so a plan you pick shows up here by itself.'));
|
|
1923
|
+
hint.appendChild(button('sm', 'arrow', 'Connect my account', function () {
|
|
1924
|
+
go('dashboard');
|
|
1925
|
+
setTimeout(function () { var c = byId('accountCard'); if (c) c.scrollIntoView({ behavior: 'smooth', block: 'center' }); connectInput.focus(); }, 60);
|
|
1926
|
+
}));
|
|
1927
|
+
box.appendChild(hint);
|
|
1928
|
+
}
|
|
1929
|
+
var grid = el('div', 'plan-grid');
|
|
1930
|
+
PLAN_CARDS.forEach(function (p) {
|
|
1931
|
+
var cardEl = el('div', 'plan-card' + (p.best ? ' best' : '') + (now === p.id ? ' mine' : ''));
|
|
1932
|
+
var head = el('div', 'plan-top');
|
|
1933
|
+
head.appendChild(el('b', null, p.name));
|
|
1934
|
+
if (now === p.id) head.appendChild(el('span', 'tag leaf', 'your plan'));
|
|
1935
|
+
else if (p.best) head.appendChild(el('span', 'tag sun', 'most picked'));
|
|
1936
|
+
cardEl.appendChild(head);
|
|
1937
|
+
var price = el('div', 'plan-price');
|
|
1938
|
+
price.appendChild(el('strong', null, p.price));
|
|
1939
|
+
price.appendChild(el('span', null, ' ' + p.per));
|
|
1940
|
+
cardEl.appendChild(price);
|
|
1941
|
+
var ul = el('ul');
|
|
1942
|
+
p.lines.forEach(function (t) { ul.appendChild(el('li', null, t)); });
|
|
1943
|
+
cardEl.appendChild(ul);
|
|
1944
|
+
if (p.id !== 'starter' && (!now || rank[p.id] > rank[now])) {
|
|
1945
|
+
var link = el('a', 'btn' + (p.best ? ' sun' : ''));
|
|
1946
|
+
link.href = PAY_PAGE;
|
|
1947
|
+
link.target = '_blank';
|
|
1948
|
+
link.rel = 'noopener noreferrer';
|
|
1949
|
+
link.appendChild(icon('up', 15));
|
|
1950
|
+
link.appendChild(el('span', null, 'Choose ' + p.name));
|
|
1951
|
+
link.addEventListener('click', function () {
|
|
1952
|
+
upgradeSince = Date.now();
|
|
1953
|
+
upgradeFrom = now;
|
|
1954
|
+
toast('Pay on kryptheon.tech - this page switches to ' + p.name + ' by itself when you come back.');
|
|
1955
|
+
});
|
|
1956
|
+
cardEl.appendChild(link);
|
|
1957
|
+
}
|
|
1958
|
+
grid.appendChild(cardEl);
|
|
1959
|
+
});
|
|
1960
|
+
box.appendChild(grid);
|
|
1961
|
+
box.appendChild(el('p', 'fallback', 'Paid on kryptheon.tech with Razorpay - UPI or card. Any offer running is shown there. Cancel any time; 7-day full refund on any charge.'));
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1851
1964
|
function render(next) {
|
|
1852
1965
|
if (!next) return;
|
|
1853
1966
|
state = next;
|
|
@@ -1866,6 +1979,9 @@
|
|
|
1866
1979
|
renderChecks();
|
|
1867
1980
|
renderRuns();
|
|
1868
1981
|
renderStorage();
|
|
1982
|
+
renderPlan();
|
|
1983
|
+
if (guideFinished()) sayDone();
|
|
1984
|
+
tell();
|
|
1869
1985
|
}
|
|
1870
1986
|
|
|
1871
1987
|
function load() {
|
package/kryptheon-dashboard.html
CHANGED
|
@@ -114,6 +114,22 @@
|
|
|
114
114
|
.view { margin-top: 28px; }
|
|
115
115
|
.view[hidden] { display: none; }
|
|
116
116
|
.card { min-width: 0; }
|
|
117
|
+
/* upgrade your plan: three plans side by side, hairlines like the rest; Pro on ink */
|
|
118
|
+
.plan-now { margin: 18px 0 6px; font-weight: 700; }
|
|
119
|
+
.plan-hint { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin: 8px 0 4px; color: var(--muted); }
|
|
120
|
+
.plan-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0; margin: 18px 0 14px; border: 1px solid var(--line); }
|
|
121
|
+
.plan-card { display: flex; flex-direction: column; gap: 12px; padding: 22px 20px; min-width: 0; }
|
|
122
|
+
.plan-card + .plan-card { border-left: 1px solid var(--line); }
|
|
123
|
+
.plan-card.best { color: var(--on-dark); background: var(--ink); }
|
|
124
|
+
.plan-card.best .plan-price span, .plan-card.best ul { color: rgba(233, 237, 242, 0.75); }
|
|
125
|
+
.plan-card.mine { box-shadow: inset 0 0 0 2px var(--orange); }
|
|
126
|
+
.plan-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
|
127
|
+
.plan-top b { font-weight: 900; font-stretch: 63%; font-size: 1.6rem; text-transform: uppercase; }
|
|
128
|
+
.plan-price strong { font-weight: 900; font-stretch: 70%; font-size: 2.4rem; }
|
|
129
|
+
.plan-price span { color: var(--muted); }
|
|
130
|
+
.plan-card ul { margin: 0; padding-left: 18px; display: grid; gap: 6px; color: var(--muted); }
|
|
131
|
+
.plan-card .btn { margin-top: auto; text-decoration: none; }
|
|
132
|
+
@media (max-width: 900px) { .plan-grid { grid-template-columns: minmax(0, 1fr); } .plan-card + .plan-card { border-left: 0; border-top: 1px solid var(--line); } }
|
|
117
133
|
.card + .card, .view > .card.gap { margin-top: 44px; }
|
|
118
134
|
.card-head { display: flex; align-items: flex-end; gap: 14px; flex-wrap: wrap; padding-bottom: 14px; border-bottom: 1px solid var(--line); }
|
|
119
135
|
.card-head h3 { font-size: clamp(1.6rem, 2.8vw, 2.2rem); }
|
|
@@ -512,6 +528,13 @@
|
|
|
512
528
|
</div>
|
|
513
529
|
</section>
|
|
514
530
|
|
|
531
|
+
<section class="view" id="view-plan" hidden>
|
|
532
|
+
<div class="card">
|
|
533
|
+
<div class="card-head"><div><div class="c-sub">Move up any day - you pay on kryptheon.tech, and this page follows</div></div></div>
|
|
534
|
+
<div id="planBox"></div>
|
|
535
|
+
</div>
|
|
536
|
+
</section>
|
|
537
|
+
|
|
515
538
|
<section class="view" id="view-storage" hidden>
|
|
516
539
|
<div class="card">
|
|
517
540
|
<div class="card-head"><div><div class="c-sub">On this machine, outside your project</div></div></div>
|
|
@@ -524,5 +547,6 @@
|
|
|
524
547
|
</div>
|
|
525
548
|
<div class="toast" id="toast" role="status" aria-live="polite"></div>
|
|
526
549
|
<script src="/dashboard.js"></script>
|
|
550
|
+
<script src="/tour.js"></script>
|
|
527
551
|
</body>
|
|
528
552
|
</html>
|
package/kryptheon-dashboard.js
CHANGED
|
@@ -1356,6 +1356,10 @@ function createServer(root, options) {
|
|
|
1356
1356
|
if (req.method === 'GET' && url.pathname === '/dashboard.js') {
|
|
1357
1357
|
return send(res, 200, 'text/javascript; charset=utf-8', fs.readFileSync(path.join(__dirname, 'kryptheon-dashboard-page.js'), 'utf8'));
|
|
1358
1358
|
}
|
|
1359
|
+
// The first-time guide: lights one part of the page at a time while the person does it.
|
|
1360
|
+
if (req.method === 'GET' && url.pathname === '/tour.js') {
|
|
1361
|
+
return send(res, 200, 'text/javascript; charset=utf-8', fs.readFileSync(path.join(__dirname, 'kryptheon-tour.js'), 'utf8'));
|
|
1362
|
+
}
|
|
1359
1363
|
if (req.method === 'GET' && Object.prototype.hasOwnProperty.call(ASSETS, url.pathname)) {
|
|
1360
1364
|
const [type, file] = ASSETS[url.pathname];
|
|
1361
1365
|
let body;
|
|
@@ -1426,6 +1430,7 @@ function createServer(root, options) {
|
|
|
1426
1430
|
.catch(() => json(res, 500, { ok: false, why: 'something went wrong' }));
|
|
1427
1431
|
if (url.pathname === '/api/account/connect') return answer(account.connect(root, env, input.code));
|
|
1428
1432
|
if (url.pathname === '/api/account/refresh') return answer(account.refresh(root, env));
|
|
1433
|
+
if (url.pathname === '/api/account/setup-done') return answer(account.setupDone(root, env));
|
|
1429
1434
|
if (url.pathname === '/api/account/disconnect') return json(res, 200, account.disconnect(root, env));
|
|
1430
1435
|
if (url.pathname === '/api/prompt/unlock') {
|
|
1431
1436
|
const id = String(input.id || '');
|
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)));
|