kryptheon 0.1.56 → 0.1.58
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/README.md +45 -5
- package/kryptheon-api.js +607 -13
- package/kryptheon-authz.js +1 -0
- package/kryptheon-code.js +60 -5
- package/kryptheon-csv.js +153 -0
- package/kryptheon-map.js +189 -9
- package/kryptheon-roles.js +152 -28
- package/kryptheon-webhook.js +407 -0
- package/package.json +8 -4
package/kryptheon-roles.js
CHANGED
|
@@ -88,7 +88,23 @@ function checkPolicy(json) {
|
|
|
88
88
|
// A draft Kryptheon wrote from the code says what the code does today, not what the owner wants.
|
|
89
89
|
if (json.draft !== undefined) return { ok: false, problems: ['it is still marked "draft": it lists what your code does today, not what you want. Edit each role to what you want, then delete the "draft" line.'] };
|
|
90
90
|
const roles = {};
|
|
91
|
-
|
|
91
|
+
// the other common shape: "roles": ["owner", "viewer"] and "rules": [{ "action": "read:orders", "allow": ["owner", "viewer"] }] (round 25)
|
|
92
|
+
if (Array.isArray(json.roles) && Array.isArray(json.rules)) {
|
|
93
|
+
const names = json.roles.filter((r) => typeof r === 'string' && r.trim()).map((r) => r.trim());
|
|
94
|
+
if (names.length !== json.roles.length) problems.push('"roles" must be a list of role names.');
|
|
95
|
+
for (const rule of json.rules) {
|
|
96
|
+
if (!rule || typeof rule.action !== 'string' || !rule.action.trim() || !Array.isArray(rule.allow) || rule.allow.some((r) => typeof r !== 'string')) {
|
|
97
|
+
problems.push('each of "rules" must be { "action": "read:orders", "allow": ["owner", ...] }.');
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
const unknown = rule.allow.find((r) => !names.includes(r.trim()) && r.trim() !== '*');
|
|
101
|
+
if (unknown) problems.push('rule "' + rule.action + '" allows "' + unknown + '", which is not in "roles".');
|
|
102
|
+
}
|
|
103
|
+
if (!problems.length) {
|
|
104
|
+
for (const name of names) roles[name] = json.rules.filter((rule) => rule.allow.some((r) => r.trim() === name || r.trim() === '*')).map((rule) => rule.action.trim());
|
|
105
|
+
if (names.length < 2) problems.push('it needs at least two roles to compare.');
|
|
106
|
+
}
|
|
107
|
+
} else if (!json.roles || typeof json.roles !== 'object' || Array.isArray(json.roles)) problems.push('"roles" must say, for each role, the list of permissions it has.');
|
|
92
108
|
else {
|
|
93
109
|
for (const name of Object.keys(json.roles)) {
|
|
94
110
|
const list = json.roles[name];
|
|
@@ -102,8 +118,11 @@ function checkPolicy(json) {
|
|
|
102
118
|
problems.push('"kryptheon.actions" must be a list of { "permission", "method", "path" }.');
|
|
103
119
|
}
|
|
104
120
|
if (problems.length) return { ok: false, problems: problems };
|
|
105
|
-
|
|
106
|
-
|
|
121
|
+
// "tenant_rules": ["A user may only read or modify records belonging to their own workspace.", ...] says the same as "tenantBoundary"
|
|
122
|
+
const written = ['tenant_rules', 'tenantRules'].map((key) => json[key]).find((v) => Array.isArray(v) && v.some((x) => typeof x === 'string' && x.trim()));
|
|
123
|
+
const boundary = typeof json.tenantBoundary === 'string' ? json.tenantBoundary : written ? written.filter((x) => typeof x === 'string').join(' ') : '';
|
|
124
|
+
const tenants = boundary.trim() !== '' || json.tenants === true;
|
|
125
|
+
return { ok: true, problems: [], policy: { roles: roles, tenants: tenants, boundary: boundary, extra: k } };
|
|
107
126
|
}
|
|
108
127
|
|
|
109
128
|
/** Whether `role` has `permission` ("*" and "resource.*" are allowed in the file). */
|
|
@@ -209,6 +228,27 @@ function templateOfWritten(p) {
|
|
|
209
228
|
return '/' + String(p || '').split(/[?#]/)[0].split('/').filter(Boolean).map((s) => (/^(\{[^}]*\}|:[A-Za-z_]\w*|<[^>]*>|\*)$/.test(s) ? '{id}' : s)).join('/');
|
|
210
229
|
}
|
|
211
230
|
|
|
231
|
+
const VERB_WORDS = new Set([...READ_WORDS, 'create', 'add', 'update', 'edit', 'write', 'delete', 'remove', 'manage']);
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* A permission name split into what it is about and what it allows:
|
|
235
|
+
* "orders.read" -> orders / read; "read:purchase_orders" -> purchase, order / read;
|
|
236
|
+
* "orders:read" -> orders / read. Null when it is one word.
|
|
237
|
+
*/
|
|
238
|
+
function partsOf(perm) {
|
|
239
|
+
const colon = String(perm).indexOf(':');
|
|
240
|
+
if (colon > 0) {
|
|
241
|
+
const left = wordsOf(perm.slice(0, colon));
|
|
242
|
+
const right = wordsOf(perm.slice(colon + 1));
|
|
243
|
+
if (!left.length || !right.length) return null;
|
|
244
|
+
// "orders:read" names the resource first; "read:orders" the action
|
|
245
|
+
if (right.every((w) => VERB_WORDS.has(w)) && !left.every((w) => VERB_WORDS.has(w))) return { resource: left, actions: right };
|
|
246
|
+
return { resource: right, actions: left };
|
|
247
|
+
}
|
|
248
|
+
const w = wordsOf(perm);
|
|
249
|
+
return w.length < 2 ? null : { resource: [w[0]], actions: w.slice(1) };
|
|
250
|
+
}
|
|
251
|
+
|
|
212
252
|
/**
|
|
213
253
|
* The permission an action needs, found from the words in its address and its
|
|
214
254
|
* method - or null, or `ambiguous`. Strict on purpose: when two permissions
|
|
@@ -232,15 +272,16 @@ function permissionFor(method, pathOrTemplate, policy) {
|
|
|
232
272
|
const verb = METHOD_VERB[m];
|
|
233
273
|
const found = [];
|
|
234
274
|
for (const perm of permissionsOf(policy)) {
|
|
235
|
-
const
|
|
236
|
-
if (
|
|
237
|
-
const resource =
|
|
238
|
-
const actions =
|
|
239
|
-
|
|
275
|
+
const parts = partsOf(perm);
|
|
276
|
+
if (!parts) continue;
|
|
277
|
+
const resource = parts.resource;
|
|
278
|
+
const actions = parts.actions;
|
|
279
|
+
const hits = resource.filter((r) => pathWords.has(r)).length;
|
|
280
|
+
if (!hits) continue;
|
|
240
281
|
const readish = actions.every((a) => READ_WORDS.has(a));
|
|
241
282
|
if (isGet !== readish) continue;
|
|
242
|
-
let score =
|
|
243
|
-
let lastHit = last.has(
|
|
283
|
+
let score = hits;
|
|
284
|
+
let lastHit = resource.some((r) => last.has(r));
|
|
244
285
|
for (const a of actions) {
|
|
245
286
|
if (pathWords.has(a)) {
|
|
246
287
|
score += 2;
|
|
@@ -521,7 +562,10 @@ async function checkAccess(input) {
|
|
|
521
562
|
const me = await s.send('GET', p);
|
|
522
563
|
if (me.status === 200 && me.json) {
|
|
523
564
|
user = findUser(me.json) || (policy.anyRole ? findAnyUser(me.json) : null);
|
|
524
|
-
if (user)
|
|
565
|
+
if (user) {
|
|
566
|
+
s.identityPath = p;
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
525
569
|
}
|
|
526
570
|
}
|
|
527
571
|
if (!user) {
|
|
@@ -697,7 +741,14 @@ async function checkAccess(input) {
|
|
|
697
741
|
const listing = '/' + action.segs.slice(0, action.params[0].index).join('/');
|
|
698
742
|
if (!getTemplates.has(listing)) {
|
|
699
743
|
const mine = (seeded.get(listing) || []).filter((r) => r.org === orgKey);
|
|
700
|
-
|
|
744
|
+
if (mine.length) return mine;
|
|
745
|
+
// /team/:id, /users/:id with no list of them: the accounts signed in here are such records, with ids the app gave
|
|
746
|
+
if (PEOPLE.test(action.segs[action.params[0].index - 1] || '')) {
|
|
747
|
+
const people = accountsOf(orgKey).filter((ss) => ss.userId !== undefined && ss.userId !== null)
|
|
748
|
+
.map((ss) => ({ value: ss.userId, item: { id: ss.userId, email: ss.email, role: ss.role }, listing: listing, field: 'id' }));
|
|
749
|
+
return people.length ? people : null;
|
|
750
|
+
}
|
|
751
|
+
return null;
|
|
701
752
|
}
|
|
702
753
|
const items = await itemsOf(orgKey, listing);
|
|
703
754
|
if (!items) return null;
|
|
@@ -721,7 +772,7 @@ async function checkAccess(input) {
|
|
|
721
772
|
return text;
|
|
722
773
|
};
|
|
723
774
|
const markersOf = (value, known, requestText) =>
|
|
724
|
-
Array.from(new Set(authz.stringsOf(value, 5))).filter((m) => !known.includes(m) && !requestText.includes(m)).slice(0, 60);
|
|
775
|
+
Array.from(new Set(authz.stringsOf(value, 5))).filter((m) => !known.includes(m) && !requestText.includes(m) && !wordsOfAnyRecord(value).has(m)).slice(0, 60);
|
|
725
776
|
|
|
726
777
|
// 6. the tries
|
|
727
778
|
const plan = [];
|
|
@@ -734,7 +785,9 @@ async function checkAccess(input) {
|
|
|
734
785
|
plan.push({ action: action, actor: s, kind: 'role', expected: 'allow', org: s.org ? s.org.key : null });
|
|
735
786
|
if (tenants && s.org) {
|
|
736
787
|
if (aimable(action)) {
|
|
737
|
-
|
|
788
|
+
// a write that names records only in its body: each of them aimed in its turn (from_location_id, then to_location_id)
|
|
789
|
+
const keys = action.method !== 'GET' && !action.params.length ? bodyRecords(action, action.data || {}, getTemplates).map((r) => r.key) : [null];
|
|
790
|
+
for (const o of orgs.values()) if (o.key !== s.org.key) for (const k of keys) plan.push({ action: action, actor: s, kind: 'tenant', expected: 'deny', org: o.key, bodyKey: k || undefined });
|
|
738
791
|
} else if (!unaimed.has(action.method + ' ' + action.template)) {
|
|
739
792
|
unaimed.add(action.method + ' ' + action.template);
|
|
740
793
|
skipped.push({ what: action.method + ' ' + action.template, why: 'across organizations: nothing in the request names a record, so it cannot be aimed at another organization' });
|
|
@@ -815,16 +868,34 @@ async function checkAccess(input) {
|
|
|
815
868
|
* The key in a request body that names another record (shipmentId, order_id),
|
|
816
869
|
* with a stand-in for the address that lists those records: { key, like }.
|
|
817
870
|
*/
|
|
818
|
-
function bodyRecord(action, body, getTemplates) {
|
|
819
|
-
const
|
|
820
|
-
|
|
821
|
-
const stem = singular(key.replace(/_?[iI]d$/, '').toLowerCase());
|
|
822
|
-
const listing = Array.from(getTemplates || []).find((t) => !t.includes('{id}') && singular(t.split('/').pop().toLowerCase().replace(/[^a-z]/g, '')) === stem);
|
|
823
|
-
if (!listing) return null;
|
|
824
|
-
const segs = listing.split('/').filter(Boolean).concat('{id}');
|
|
825
|
-
return { key: key, like: { template: listing + '/{id}', segs: segs, params: [{ index: segs.length - 1, value: body[key] }], by: action.by } };
|
|
871
|
+
function bodyRecord(action, body, getTemplates, want) {
|
|
872
|
+
const all = bodyRecords(action, body, getTemplates);
|
|
873
|
+
return (want ? all.find((r) => r.key === want) : all[0]) || null;
|
|
826
874
|
}
|
|
827
875
|
|
|
876
|
+
/**
|
|
877
|
+
* Every key of a body that names another record and whose records the app
|
|
878
|
+
* lists, in the body's order: shipmentId, order_id - and from_location_id,
|
|
879
|
+
* to_location_id, each by its last word (round 25's transfer named its
|
|
880
|
+
* destination so, and was never aimed at another organization's location).
|
|
881
|
+
*/
|
|
882
|
+
function bodyRecords(action, body, getTemplates) {
|
|
883
|
+
const out = [];
|
|
884
|
+
for (const key of Object.keys(body || {})) {
|
|
885
|
+
if (!/^[A-Za-z]+(?:_[A-Za-z]+)*_?[iI]d$/.test(key) || key.toLowerCase() === 'id' || !['string', 'number'].includes(typeof body[key])) continue;
|
|
886
|
+
const words = key.replace(/_?[iI]d$/, '').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase().split('_').filter(Boolean);
|
|
887
|
+
const stem = singular(words[words.length - 1] || '');
|
|
888
|
+
const listing = Array.from(getTemplates || []).find((t) => !t.includes('{id}') && singular(t.split('/').pop().toLowerCase().replace(/[^a-z]/g, '')) === stem);
|
|
889
|
+
if (!listing) continue;
|
|
890
|
+
const segs = listing.split('/').filter(Boolean).concat('{id}');
|
|
891
|
+
out.push({ key: key, like: { template: listing + '/{id}', segs: segs, params: [{ index: segs.length - 1, value: body[key] }], by: action.by } });
|
|
892
|
+
}
|
|
893
|
+
return out;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// The last word of an address whose records are people.
|
|
897
|
+
const PEOPLE = /^(users?|team|teams|members?|memberships?|accounts?|staff|people|profiles?|employees?)$/i;
|
|
898
|
+
|
|
828
899
|
/** One try: send, look, judge, put back. Returns the evidence, or null when the try had nothing to aim at. */
|
|
829
900
|
async function tryOnce(x) {
|
|
830
901
|
const { p, policy } = x;
|
|
@@ -869,7 +940,7 @@ async function tryOnce(x) {
|
|
|
869
940
|
if (!isGet) {
|
|
870
941
|
body = sampleBody(a);
|
|
871
942
|
// a body that names another record (shipmentId, order_id) is pointed at the target's organization too
|
|
872
|
-
const named = bodyRecord(a, body, x.getTemplates);
|
|
943
|
+
const named = bodyRecord(a, body, x.getTemplates, p.bodyKey);
|
|
873
944
|
if (named) {
|
|
874
945
|
const alt = await x.targetsFor(named.like, targetOrg);
|
|
875
946
|
if (alt && alt.length) {
|
|
@@ -910,7 +981,23 @@ async function tryOnce(x) {
|
|
|
910
981
|
|
|
911
982
|
// what the app holds now
|
|
912
983
|
const reader = targetOrg !== null || p.kind === 'signin' || x.orgs.size === 0;
|
|
913
|
-
|
|
984
|
+
// a person's record: what they themselves are told about who they are shows the change (their role)
|
|
985
|
+
const person = !isGet && target.item && target.item.email ? x.sessions.find((ss) => ss.email === target.item.email && ss.identityPath) : null;
|
|
986
|
+
const withPerson = async (snap) => {
|
|
987
|
+
if (!person) return snap;
|
|
988
|
+
const r = await person.send('GET', person.identityPath);
|
|
989
|
+
if (r.status === 200 && r.json !== undefined) snap['who am I, as ' + person.email] = stable(r.json);
|
|
990
|
+
return snap;
|
|
991
|
+
};
|
|
992
|
+
const before = await withPerson(reader ? await x.snapshot(targetOrg) : {});
|
|
993
|
+
// a write to an address that is also read (POST /returns/5/notes, GET /returns/5/notes) shows there
|
|
994
|
+
const sameGet = reader && !isGet && a.params.length && x.getTemplates.has(a.template) ? pathNow : null;
|
|
995
|
+
const readSame = async () => {
|
|
996
|
+
const f = sameGet ? await x.readerFor(targetOrg, sameGet, null, false) : null;
|
|
997
|
+
return f ? stable(f.res.json) : undefined;
|
|
998
|
+
};
|
|
999
|
+
const sameBefore = await readSame();
|
|
1000
|
+
if (sameBefore !== undefined) before[sameGet] = sameBefore;
|
|
914
1001
|
const known = await x.knownTo(actor);
|
|
915
1002
|
|
|
916
1003
|
// truth: the records a read would disclose
|
|
@@ -929,12 +1016,27 @@ async function tryOnce(x) {
|
|
|
929
1016
|
}
|
|
930
1017
|
}
|
|
931
1018
|
|
|
1019
|
+
// a write that names another organization's record in its body: our own lists, before and after
|
|
1020
|
+
const pointing = p.kind === 'tenant' && !isGet && bodyItem && actor.org && markers.length > 0;
|
|
1021
|
+
const ownBefore = pointing ? JSON.stringify(await x.snapshot(actor.org.key)) : '';
|
|
932
1022
|
const res = await actor.send(a.method, pathNow, isGet ? {} : (a.encoding === 'form' ? { form: body } : { json: body }));
|
|
933
1023
|
const reply = authz.replyOf(res);
|
|
934
1024
|
const foreign = actor.org && isGet ? foreignRecords(res.json, actor.org.key) : [];
|
|
935
1025
|
const ownMarked = actor.org && isGet ? ownRecords(res.json, actor.org.key) : 0;
|
|
936
|
-
|
|
937
|
-
|
|
1026
|
+
let found = markers.length ? authz.foundIn(res, markers).length : 0;
|
|
1027
|
+
// their record's own words now in our lists: a record of ours points at theirs (round 25: a transfer whose
|
|
1028
|
+
// destination was another organization's location, shown by name in our list of transfers)
|
|
1029
|
+
let pointedAt = [];
|
|
1030
|
+
if (pointing && (reply.kind === 'accepted' || reply.kind === 'redirect')) {
|
|
1031
|
+
const ownAfter = JSON.stringify(await x.snapshot(actor.org.key));
|
|
1032
|
+
pointedAt = markers.filter((m) => ownAfter.includes(m) && !ownBefore.includes(m));
|
|
1033
|
+
found += pointedAt.length;
|
|
1034
|
+
}
|
|
1035
|
+
const after = await withPerson(reader ? await x.snapshot(targetOrg) : {});
|
|
1036
|
+
if (sameBefore !== undefined) {
|
|
1037
|
+
const sameAfter = await readSame();
|
|
1038
|
+
if (sameAfter !== undefined) after[sameGet] = sameAfter;
|
|
1039
|
+
}
|
|
938
1040
|
const changes = x.compare(before, after);
|
|
939
1041
|
const changed = Object.keys(before).length ? changes.length > 0 : null;
|
|
940
1042
|
|
|
@@ -944,6 +1046,7 @@ async function tryOnce(x) {
|
|
|
944
1046
|
target: { organization: orgName(targetOrg), record: target.value },
|
|
945
1047
|
changes: changes.slice(0, 6), protectedPiecesSeen: found,
|
|
946
1048
|
});
|
|
1049
|
+
if (pointedAt.length) att.pointedAt = { key: p.bodyKey || Object.keys(body).find((k) => body[k] === target.value) || null, words: pointedAt.slice(0, 3) };
|
|
947
1050
|
// An answer to a try that was aimed across organizations is judged for that. For any other try, another
|
|
948
1051
|
// organization's records in the answer are a second finding, kept apart from what the role may do.
|
|
949
1052
|
att.verdictInfo = judge({ expected: p.expected, isGet: isGet, status: res.status, reply: reply, found: found, foreign: p.kind === 'tenant' ? foreign : [], markersKnown: markersKnown || ownMarked > 0, changed: changed, kind: p.kind });
|
|
@@ -973,7 +1076,7 @@ async function tryOnce(x) {
|
|
|
973
1076
|
const writers = (x.orgs.get(targetOrg) ? x.orgs.get(targetOrg).sessions : x.sessions).filter((s) => holds(policy, s.role, a.permission)).concat([actor]);
|
|
974
1077
|
for (const who of writers) {
|
|
975
1078
|
await who.send(a.method, pathNow, a.encoding === 'form' ? { form: back } : { json: back });
|
|
976
|
-
const again = await x.snapshot(targetOrg);
|
|
1079
|
+
const again = await withPerson(await x.snapshot(targetOrg));
|
|
977
1080
|
if (x.compare(before, again).length === 0) {
|
|
978
1081
|
att.restored = true;
|
|
979
1082
|
break;
|
|
@@ -997,6 +1100,26 @@ async function tryOnce(x) {
|
|
|
997
1100
|
return att;
|
|
998
1101
|
}
|
|
999
1102
|
|
|
1103
|
+
// Fields whose values are one of a few words every organization uses: "submitted", "warehouse", "INR".
|
|
1104
|
+
const SHARED_WORD_KEY = /(^|_)(status|state|stage|type|kind|role|level|priority|currency|unit|method|category|visibility)$/i;
|
|
1105
|
+
|
|
1106
|
+
/**
|
|
1107
|
+
* The values of a record that are a status or kind - words any organization's
|
|
1108
|
+
* records carry - and so prove nothing about whose record came back. Round 25:
|
|
1109
|
+
* "Only submitted purchase orders can be approved." held the other
|
|
1110
|
+
* organization's status "submitted", and a refusal was called a leak.
|
|
1111
|
+
*/
|
|
1112
|
+
function wordsOfAnyRecord(value) {
|
|
1113
|
+
const out = new Set();
|
|
1114
|
+
(function walk(v, key) {
|
|
1115
|
+
if (typeof v === 'string') {
|
|
1116
|
+
if ((key && SHARED_WORD_KEY.test(key)) || /^[a-z]+(_[a-z]+)*$/.test(v)) out.add(v);
|
|
1117
|
+
} else if (Array.isArray(v)) v.forEach((x) => walk(x, key));
|
|
1118
|
+
else if (v && typeof v === 'object') Object.keys(v).forEach((k) => walk(v[k], k));
|
|
1119
|
+
})(value, null);
|
|
1120
|
+
return out;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1000
1123
|
// A record's own mark of the organization it belongs to.
|
|
1001
1124
|
const ORG_KEY = /^(org|organi[sz]ation|tenant|workspace|company)[_-]?id$/i;
|
|
1002
1125
|
|
|
@@ -1093,7 +1216,8 @@ function proofOf(att) {
|
|
|
1093
1216
|
if (att.changes && att.changes.length) {
|
|
1094
1217
|
lines.push(' state: changed after the request (read before and after):');
|
|
1095
1218
|
for (const c of att.changes.slice(0, 3)) lines.push(' ' + c);
|
|
1096
|
-
} else if (att.
|
|
1219
|
+
} else if (att.pointedAt) lines.push(' state: saved, and this account\'s own lists now name the other organization\'s record' + (att.pointedAt.key ? ' (' + att.pointedAt.key + ')' : '') + ': ' + att.pointedAt.words.map((w) => JSON.stringify(w)).join(', '));
|
|
1220
|
+
else if (att.protectedPiecesSeen) lines.push(' state: the answer itself held ' + att.protectedPiecesSeen + ' piece(s) of records this account may not see');
|
|
1097
1221
|
else lines.push(' state: unchanged');
|
|
1098
1222
|
lines.push(' repeat: sign in as ' + att.actor.email + ', send ' + att.request.method + ' ' + att.request.path + (att.request.body && Object.keys(att.request.body).length ? ' with that body' : '') + ', then read the same lists as an allowed account');
|
|
1099
1223
|
return lines;
|