kryptheon 0.1.67 → 0.1.69

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.
@@ -0,0 +1,217 @@
1
+ // The setup a person who cannot read code can still do: plain questions instead of files to write.
2
+ //
3
+ // Who may do what - each thing the app does, read from its code, as a line in plain words ("Refund invoices"),
4
+ // with the roles the code lets do it today ticked. A line with no role check in the code at all
5
+ // is marked: every signed-in role can do it, and that is the line most worth a look. The
6
+ // answers are written as permissions-policy.json - by Kryptheon, never typed by the person.
7
+ // Who signs in - each account the project names, with a box for its password; or, for an app that signs people
8
+ // in with a token, a name and a token. Written to .env as KRYPTHEON_PASSWORD_<NAME> /
9
+ // KRYPTHEON_TOKEN_<NAME>, ADDED at the end only: a line already in .env is never changed, and
10
+ // nothing else in the file is touched (a real user's .env was once wiped by a tool that wrote it).
11
+ //
12
+ // Nothing here prints or returns a password or token: answers say only which names were written.
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const api = require('./kryptheon-api.js');
17
+ const roles = require('./kryptheon-roles.js');
18
+ const replay = require('./kryptheon-replay.js');
19
+ const secrets = require('./kryptheon-secrets.js');
20
+
21
+ const ENV_NAME = /^KRYPTHEON_(PASSWORD|TOKEN)_[A-Z0-9_]{1,80}$/;
22
+ const ROLE_NAME = /^[A-Za-z][A-Za-z0-9_ -]{0,39}$/;
23
+ const GRANT_WORDS = /(^|\/)(invite|invites|invitations?|members?|team|users?|roles?|staff)(\/|$)/i;
24
+
25
+ const titleOf = (w) => String(w).replace(/[_-]+/g, ' ').trim();
26
+ const VERB = { read: 'See', create: 'Add', update: 'Change', delete: 'Delete' };
27
+ // the last word of an address that is a step done to the record (POST /orders/{id}/refund), not a thing added to it
28
+ const STEP_WORD = /^(activate|deactivate|assign|unassign|complete|confirm|refund|release|redeem|consume|reopen|return|publish|unpublish|cancel|approve|reject|archive|restore|invite|export|run|send|settle|link|unlink|check-?in|scan|transfer|close|open|pay|capture|void|accept|decline|submit|verify|resend|retry|lock|unlock|enable|disable|block|unblock|ship|deliver|book|reserve|hold|dispatch|start|stop|pause|resume|sign|login|logout)$/i;
29
+ const FILE_WORD = /\.(csv|xlsx?|pdf|json|txt)$/i;
30
+
31
+ /** A line in plain words for one route: "POST /api/invoices/{id}/refund" -> "Refund invoices". */
32
+ function routeLabel(method, template) {
33
+ const segs = String(template).split('/').filter((x) => x && x !== '{id}' && !/^(api|v\d+)$/i.test(x));
34
+ const thing = titleOf(segs[0] || 'records');
35
+ const tail = segs.length > 1 ? segs[segs.length - 1] : null;
36
+ const m = String(method).toUpperCase();
37
+ if (!tail) return ({ GET: 'See ', POST: 'Add ', PUT: 'Change ', PATCH: 'Change ', DELETE: 'Remove ' }[m] || m + ' ') + thing;
38
+ if (FILE_WORD.test(tail)) return 'Download the ' + titleOf(tail.replace(FILE_WORD, '')) + ' file (' + thing + ')';
39
+ if (m === 'GET') return 'See the ' + titleOf(tail) + ' of ' + thing;
40
+ if (m === 'DELETE') return 'Remove ' + titleOf(tail) + ' of ' + thing;
41
+ if (STEP_WORD.test(tail)) { const v = titleOf(tail); return v.charAt(0).toUpperCase() + v.slice(1) + ' ' + thing; }
42
+ if (m === 'PATCH' || m === 'PUT') return 'Change the ' + titleOf(tail) + ' of ' + thing;
43
+ return 'Add ' + titleOf(tail) + ' to ' + thing;
44
+ }
45
+
46
+ /** "invoices.refund" -> "Refund invoices"; "work_orders.read" -> "See work orders"; "work_orders.status" -> "Change the status of work orders". */
47
+ function labelOf(permission) {
48
+ const parts = String(permission).split('.');
49
+ const thing = titleOf(parts[0]);
50
+ if (parts.length === 2 && VERB[parts[1]]) return VERB[parts[1]] + ' ' + thing;
51
+ if (parts.length === 3 && parts[2] === 'read') return 'See the ' + titleOf(parts[1]) + ' of ' + thing;
52
+ const step = titleOf(parts[1] || '');
53
+ if (/^(status|state|priority|role|settings?)$/.test(step)) return 'Change the ' + step + ' of ' + thing;
54
+ return step.charAt(0).toUpperCase() + step.slice(1) + ' ' + thing;
55
+ }
56
+
57
+ /**
58
+ * The questions for this project. { ran, why, roles, rows, tenants, grants, accounts, policy }.
59
+ * rows: [{ permission, label, routes: ['POST /api/x'], allowed: [roles] , everyone: true when the code checks no role }]
60
+ * policy: { exists, ok, problems } - an existing permissions-policy.json is the starting point and is never replaced
61
+ * unless the person says so.
62
+ */
63
+ function questionsOf(root, options) {
64
+ const opts = options || {};
65
+ const plan = api.planOf(root, opts);
66
+ if (!plan.ran) return { ran: false, why: plan.why };
67
+ const existing = roles.loadPolicy(root);
68
+ const policy = existing.ok ? existing.policy : null;
69
+ const names = new Set(policy ? Object.keys(policy.roles) : []);
70
+ const norm = (p) => String(p).replace(/:(\w+)\*?/g, '{id}');
71
+ const routes = (plan.map.routes || []).filter((r) => !r.unmounted && r.path && /^(GET|POST|PUT|PATCH|DELETE)$/.test(r.method) && r.kind !== 'webhook' &&
72
+ !(r.auth && r.auth.status === 'not_detected') && !/(^|\/)(log-?in|log-?out|sign-?in|sign-?out|sign-?up|register|health|me|whoami|session)$/i.test(r.path));
73
+ const guardOf = (r) => (r.role && r.role.status === 'guard_detected' && Array.isArray(r.role.roles) ? r.role.roles.map(String) : null);
74
+ for (const r of routes) for (const g of guardOf(r) || []) names.add(g);
75
+ // roles the app gives people: the accounts' own names (northstar-viewer), and extra roles the person adds
76
+ for (const extra of opts.extraRoles || []) if (ROLE_NAME.test(extra)) names.add(String(extra));
77
+ const roleList = Array.from(names);
78
+ const byPerm = new Map();
79
+ for (const r of routes) {
80
+ const template = norm(r.path);
81
+ const named = policy ? roles.permissionFor(r.method, template, policy) : null;
82
+ const permission = named && named.permission ? named.permission : api.permissionName(r.method, template);
83
+ const row = byPerm.get(permission) || { permission, label: routeLabel(r.method, template), routes: [], allowed: new Set(), everyone: false };
84
+ row.routes.push(r.method + ' ' + template);
85
+ if (policy) {
86
+ for (const x of roleList) if ((policy.roles[x] || []).includes(permission) || (policy.roles[x] || []).includes('*')) row.allowed.add(x);
87
+ } else if (guardOf(r)) {
88
+ for (const x of guardOf(r)) row.allowed.add(x);
89
+ } else {
90
+ row.everyone = true;
91
+ for (const r of roleList) row.allowed.add(r);
92
+ }
93
+ byPerm.set(permission, row);
94
+ }
95
+ const rows = Array.from(byPerm.values()).map((r) => Object.assign({}, r, { allowed: Array.from(r.allowed) }))
96
+ .sort((a, b) => Number(b.everyone) - Number(a.everyone) || a.label.localeCompare(b.label));
97
+ // an app that keeps organizations apart: a statement limited to one, or one that names an organization column
98
+ const scoped = routes.some((r) => (r.db || []).some((d) => d.level === 'organisation' || /\b(org|organi[sz]ation|tenant|workspace|company|team)_id\b/i.test(String(d.sql || ''))));
99
+ const grantRoutes = routes.filter((r) => r.method !== 'GET' && GRANT_WORDS.test(r.path) && ((r.validation && r.validation.fields) || []).some((f) => /role/i.test(f.name))).map((r) => ({ method: r.method, template: norm(r.path) }));
100
+ let grantRules = null;
101
+ try {
102
+ const raw = JSON.parse(fs.readFileSync(path.join(root, roles.POLICY_FILE), 'utf8').replace(/^/, ''));
103
+ if (raw && raw.roleGrantRules && typeof raw.roleGrantRules === 'object') grantRules = raw.roleGrantRules;
104
+ } catch (err) { /* no file, or not JSON: no rules yet */ }
105
+ return {
106
+ ran: true,
107
+ roles: roleList,
108
+ rows,
109
+ tenants: { now: policy ? Boolean(policy.tenants) : null, suggested: scoped },
110
+ grants: { routes: grantRoutes.map((a) => a.method + ' ' + a.template), rules: grantRules },
111
+ accounts: accountsOf(root, plan, opts.env),
112
+ policy: { exists: existing.ok || !existing.missing, ok: existing.ok, problems: existing.ok ? [] : existing.problems || [] },
113
+ };
114
+ }
115
+
116
+ /** Who Kryptheon can sign in as, and who it could with a password: never a value, only whether it is set. */
117
+ function accountsOf(root, plan, env) {
118
+ const fromFile = secrets.readEnvFile(secrets.envFileFor(root));
119
+ const here = env || process.env;
120
+ const isSet = (n) => secrets.isSet(here[n]) || secrets.isSet(fromFile[n]);
121
+ if (plan.signIn && !plan.signIn.bearer) {
122
+ const list = [];
123
+ for (const [email, where] of api.emailsIn(root)) {
124
+ if (/^tests[\\/]/.test(where)) continue;
125
+ const envName = 'KRYPTHEON_PASSWORD_' + replay.accountPart(email);
126
+ list.push({ name: email, envName, set: isSet(envName), from: where });
127
+ }
128
+ return { mode: 'password', signIn: plan.signIn.method + ' ' + plan.signIn.path, list };
129
+ }
130
+ const tokens = api.tokenAccountsOf(root, env).map((a) => ({ name: a.email, envName: a.envName, set: true, from: a.from }));
131
+ return { mode: 'token', signIn: null, why: plan.signIn ? null : 'no sign-in route with an email and a password was found, so accounts sign in with a token', list: tokens };
132
+ }
133
+
134
+ /** The policy file the answers make. answers: { roles: [names], allow: { permission: [roles] }, tenants: bool, grants: { role: [roles] } }. */
135
+ function policyFrom(q, answers) {
136
+ const a = answers || {};
137
+ const roleList = (Array.isArray(a.roles) && a.roles.length ? a.roles : q.roles).map(String).filter((r) => ROLE_NAME.test(r));
138
+ if (roleList.length < 2) return { ok: false, why: 'name at least two roles' };
139
+ const out = { roles: {} };
140
+ for (const r of roleList) out.roles[r] = [];
141
+ const known = new Set(q.rows.map((r) => r.permission));
142
+ for (const row of q.rows) {
143
+ const who = a.allow && Array.isArray(a.allow[row.permission]) ? a.allow[row.permission] : row.allowed;
144
+ for (const r of who) if (out.roles[r] && !out.roles[r].includes(row.permission)) out.roles[r].push(row.permission);
145
+ }
146
+ for (const k of Object.keys(a.allow || {})) if (!known.has(k)) return { ok: false, why: 'an answer names something this app does not do: ' + k };
147
+ if (a.tenants) out.tenantBoundary = 'A user may only read or change records of their own organization.';
148
+ if (a.grants && typeof a.grants === 'object') {
149
+ const rules = {};
150
+ for (const r of roleList) rules[r] = (Array.isArray(a.grants[r]) ? a.grants[r] : []).filter((x) => roleList.includes(x));
151
+ if (Object.values(rules).some((list) => list.length)) out.roleGrantRules = rules;
152
+ }
153
+ // every route named with the permission the person answered for, so nothing is matched by a guess later
154
+ out.kryptheon = { actions: [] };
155
+ for (const row of q.rows) for (const route of row.routes) {
156
+ const sp = route.indexOf(' ');
157
+ out.kryptheon.actions.push({ method: route.slice(0, sp), path: route.slice(sp + 1), permission: row.permission });
158
+ }
159
+ out.written = 'Written by Kryptheon from your answers on ' + new Date().toISOString().slice(0, 10) + '. Change it from the dashboard, or edit it here.';
160
+ return { ok: true, policy: out };
161
+ }
162
+
163
+ /** Writes permissions-policy.json. An existing one is replaced only when `replace` is true; the file is checked as it is read. */
164
+ function savePolicy(root, policy, replace) {
165
+ const file = path.join(root, roles.POLICY_FILE);
166
+ if (fs.existsSync(file) && replace !== true) return { ok: false, why: roles.POLICY_FILE + ' is already there - say to replace it, or edit it' };
167
+ const tmp = file + '.kryptheon-' + process.pid + '.tmp';
168
+ try {
169
+ fs.writeFileSync(tmp, JSON.stringify(policy, null, 2) + '\n', 'utf8');
170
+ fs.renameSync(tmp, file);
171
+ } catch (err) {
172
+ try { fs.unlinkSync(tmp); } catch (e) { /* not there */ }
173
+ return { ok: false, why: 'it could not be written: ' + err.code };
174
+ }
175
+ const back = roles.loadPolicy(root);
176
+ return back.ok ? { ok: true, file } : { ok: false, file, why: 'written, but it does not read back: ' + (back.problems || []).join(' ') };
177
+ }
178
+
179
+ /**
180
+ * Adds accounts to .env: [{ envName, value }] - only KRYPTHEON_PASSWORD_ / KRYPTHEON_TOKEN_ names, only names not set yet,
181
+ * appended at the end. A name already set is listed and left exactly as it is. { ok, written: [names], kept: [names] }.
182
+ */
183
+ function saveAccounts(root, entries) {
184
+ const file = secrets.envFileFor(root);
185
+ const there = secrets.readEnvFile(file);
186
+ const written = [];
187
+ const kept = [];
188
+ const lines = [];
189
+ for (const e of entries || []) {
190
+ const name = String(e && e.envName || '');
191
+ const value = String(e && e.value || '').trim();
192
+ if (!ENV_NAME.test(name)) return { ok: false, why: 'not a name Kryptheon writes: ' + name.slice(0, 60) };
193
+ if (!value) continue;
194
+ if (/[\r\n]/.test(value)) return { ok: false, why: 'a value with a line break cannot go in .env' };
195
+ if (secrets.isSet(there[name]) || written.includes(name)) { kept.push(name); continue; }
196
+ lines.push(name + '=' + value);
197
+ written.push(name);
198
+ }
199
+ if (!lines.length) return { ok: true, written, kept };
200
+ try {
201
+ let raw = '';
202
+ try { raw = fs.readFileSync(file, 'utf8'); } catch (err) { raw = ''; }
203
+ fs.appendFileSync(file, (raw.length && !raw.endsWith('\n') ? '\n' : '') + lines.join('\n') + '\n', 'utf8');
204
+ } catch (err) {
205
+ return { ok: false, why: '.env could not be written: ' + err.code };
206
+ }
207
+ secrets.updateGitignore(root, ['.env']);
208
+ return { ok: true, written, kept };
209
+ }
210
+
211
+ /** A name for a token account: "Northstar owner" -> KRYPTHEON_TOKEN_NORTHSTAR_OWNER. */
212
+ function tokenEnvName(label) {
213
+ const n = String(label || '').toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 60);
214
+ return n ? 'KRYPTHEON_TOKEN_' + n : null;
215
+ }
216
+
217
+ module.exports = { routeLabel, questionsOf, policyFrom, savePolicy, saveAccounts, accountsOf, labelOf, tokenEnvName, ENV_NAME };
@@ -657,10 +657,11 @@ async function checkAccess(input) {
657
657
  const journey = input.journey;
658
658
  const say = typeof input.say === 'function' ? input.say : () => {};
659
659
  const stopped = typeof input.stopped === 'function' ? input.stopped : () => false;
660
- const origin = authz.assertLocalTarget(input.origin, input.allowOrigins || [input.origin]);
660
+ const origin = authz.assertLocalTarget(input.origin, input.allowOrigins || [input.origin], { readOnly: input.readOnly === true });
661
661
  const passwords = {};
662
662
  for (const a of input.accounts) passwords[a.email] = a.password;
663
- const ctx = authz.makeContext({ baseUrl: origin, allowOrigins: [origin], fetch: input.fetch, passwords: passwords, maxRequests: input.maxRequests || 30000, timeoutMs: input.timeoutMs });
663
+ const ctx = authz.makeContext({ baseUrl: origin, allowOrigins: [origin], fetch: input.fetch, passwords: passwords, maxRequests: input.maxRequests || 30000, timeoutMs: input.timeoutMs,
664
+ readOnly: input.readOnly === true, allowWrites: journey.signIn && journey.signIn.path && !journey.signIn.bearer ? [String(journey.signIn.method || 'POST').toUpperCase() + ' ' + journey.signIn.path] : [] });
664
665
  const hide = [].concat(Object.values(passwords));
665
666
  const notes = [];
666
667
  const skipped = [];
@@ -855,7 +856,7 @@ async function checkAccess(input) {
855
856
  };
856
857
  return find(json, 0);
857
858
  };
858
- if (input.seed) {
859
+ if (input.seed && !input.readOnly) {
859
860
  for (const action of journey.actions) {
860
861
  if (action.params.length !== 1) continue;
861
862
  const listing = '/' + action.segs.slice(0, action.params[0].index).join('/');