@aria-framework/customer 0.0.0-stage → 0.2.0

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,30 @@
1
+ /**
2
+ * Part "access": the customer's support-access setting per kind of data, its grants and requests, the partner's
3
+ * starting value and managed mark, the sweep, the audit action names, and the five tables as data.
4
+ */
5
+
6
+ 'use strict';
7
+
8
+ const rules = require('./rules');
9
+ const { defineKinds, isKinds } = require('./kinds');
10
+ const { accessTables, accessTenancy, checkAccessSchema, assertAccessSchema, ACCESS_TABLES } = require('./tables');
11
+ const { createAccessStore, ACCESS_CUSTOMER_SAFE, ACCESS_STAFF } = require('./store');
12
+ const { ACTIONS, ACTION_LABELS, ACTIONS_ABOUT_CUSTOMER, sweepAudit } = require('./audit');
13
+
14
+ module.exports = {
15
+ accessRules: rules,
16
+ defineKinds,
17
+ isKinds,
18
+ accessTables,
19
+ accessTenancy,
20
+ checkAccessSchema,
21
+ assertAccessSchema,
22
+ ACCESS_TABLES,
23
+ createAccessStore,
24
+ ACCESS_CUSTOMER_SAFE,
25
+ ACCESS_STAFF,
26
+ ACCESS_ACTIONS: ACTIONS,
27
+ ACCESS_ACTION_LABELS: ACTION_LABELS,
28
+ ACCESS_ACTIONS_ABOUT_CUSTOMER: ACTIONS_ABOUT_CUSTOMER,
29
+ sweepAudit
30
+ };
@@ -0,0 +1,61 @@
1
+ /**
2
+ * THE APP'S KINDS OF DATA (CD-06, CD-27): a part of a customer's content with its own support-access setting.
3
+ *
4
+ * defineKinds([{ key, label, start: { mode, level }, partnerMaySetStart }, ...])
5
+ *
6
+ * key a slug stored in the `kind` column of the settings and starting-value tables
7
+ * label the words a page shows for it
8
+ * start what the partner starts at for this kind when nothing is stored and the partner has set no value
9
+ * of its own: open with a level, ask, or never (an app may start a kind closed: CD-27's quotes)
10
+ * partnerMaySetStart true: a partner may set its own starting value for this kind (CD-39); false: only the customer
11
+ * opens it, and a partner's save for it is refused
12
+ *
13
+ * Every field is required, with no default: a starting value that "looks right" is exactly what gets shipped unread.
14
+ * An app with one kind passes a list of one.
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ const R = require('./rules');
20
+
21
+ const KEY = /^[a-z][a-z0-9_]{0,39}$/;
22
+ const FIELDS = ['key', 'label', 'start', 'partnerMaySetStart'];
23
+ const KINDS = Symbol('customer access kinds');
24
+
25
+ function fail(message) {
26
+ throw Object.assign(new Error(`customer access kinds: ${message}`), { code: 'ACCESS_KINDS_REFUSED' });
27
+ }
28
+
29
+ /** Validate the app's list and return a frozen copy: `{ list, keys, byKey(key) }`. */
30
+ function defineKinds(list) {
31
+ if (isKinds(list)) return list;
32
+ if (!Array.isArray(list) || list.length === 0) fail('pass the app\'s kinds of data: a non-empty list of { key, label, start, partnerMaySetStart }');
33
+ const out = [];
34
+ for (const [i, k] of list.entries()) {
35
+ const at = `kind ${i + 1}`;
36
+ if (!k || typeof k !== 'object' || Array.isArray(k)) fail(`${at} is not an object`);
37
+ for (const f of Object.keys(k)) if (!FIELDS.includes(f)) fail(`${at}: unknown field "${f}" (known: ${FIELDS.join(', ')})`);
38
+ for (const f of FIELDS) if (!R.has(k, f)) fail(`${at}: ${f} is required`);
39
+ if (typeof k.key !== 'string' || !KEY.test(k.key)) fail(`${at}: key ${JSON.stringify(k.key)} is not a slug (a lower-case letter, then letters, digits, _; at most 40)`);
40
+ if (out.some((x) => x.key === k.key)) fail(`${at}: key "${k.key}" is used twice`);
41
+ if (typeof k.label !== 'string' || !k.label.trim()) fail(`${k.key}: label is required`);
42
+ const s = k.start;
43
+ if (!s || typeof s !== 'object' || Object.keys(s).some((f) => f !== 'mode' && f !== 'level')) fail(`${k.key}: start is { mode, level }`);
44
+ const start = { mode: s.mode, level: s.mode === 'open' ? s.level : (s.level == null ? null : s.level) };
45
+ if (!R.validSetting(start)) fail(`${k.key}: start ${JSON.stringify(s)} is not a setting (open with look or change; ask or never with no level)`);
46
+ if (typeof k.partnerMaySetStart !== 'boolean') fail(`${k.key}: partnerMaySetStart is true or false`);
47
+ out.push(Object.freeze({ key: k.key, label: k.label, start: Object.freeze(start), partnerMaySetStart: k.partnerMaySetStart }));
48
+ }
49
+ const keys = Object.freeze(out.map((k) => k.key));
50
+ const kinds = {
51
+ list: Object.freeze(out),
52
+ keys,
53
+ byKey(key) { return out.find((k) => k.key === key) || null; },
54
+ [KINDS]: true
55
+ };
56
+ return Object.freeze(kinds);
57
+ }
58
+
59
+ const isKinds = (v) => !!v && v[KINDS] === true;
60
+
61
+ module.exports = { defineKinds, isKinds };
@@ -0,0 +1,176 @@
1
+ /**
2
+ * WHO MAY COME IN: THE RULES, VERSION 2 (pure: no database, no session, no clock of their own).
3
+ *
4
+ * Moved from the first customer-driven app's rules (its lib/supportAccess.js) and changed for version 2 of the model
5
+ * ("Customer-driven apps" version 3; Platform D-0013, D-0014):
6
+ *
7
+ * NO TIER. A customer has one helper, its partner. The house is the partner of the customers it sells to
8
+ * directly and gets exactly what any partner gets; it is never named on another partner's customer
9
+ * (CD-02, CD-29). The tier list, `tiersOf`, `tierFor` and the house arm of the starting value are gone.
10
+ * KINDS. The customer's setting is kept PER KIND OF DATA (CD-26, CD-27). The rules below are kind-free: the
11
+ * answer for one kind is a function of that kind's own setting, the partner's starting value for that
12
+ * kind, the kind's own starting value, and the customer's live grant (which is not per kind: a grant
13
+ * lets the partner into every kind not set to Never, D-0013 answer 2). Nothing else.
14
+ *
15
+ * A SETTING open ("May come in", with a level: look | change) / ask ("Only when we let them in") / never.
16
+ * No stored row is the STARTING VALUE: the partner's own value for that kind, in force when the
17
+ * customer was received, where the app lets the partner set that kind (partnerMaySetStart); else the
18
+ * kind's own starting value from the app's list (CD-37, CD-39).
19
+ * A GRANT "Let them in now": a level and an end (or none: until switched off). Never means closed: under
20
+ * Never a grant gives nothing, whatever it says (CD-35).
21
+ * ALLOWANCE what the partner may do in one kind NOW: nothing under Never; else the higher of the setting's level
22
+ * (open only) and a live grant's level, or nothing.
23
+ * MANAGED the partner's "we manage this customer" mark waives the reason only. It is in force only while every
24
+ * kind not set to Never is May come in (D-0014 answer 9, CD-40) and at least one kind is (a customer
25
+ * closed in every kind lets nobody in, so there is nothing to waive). It lets nobody in.
26
+ *
27
+ * What a visit does with these (the lowest of asked, allowed and the helper's role; four hours; re-checked on every
28
+ * request) is the visits part of this package, not here.
29
+ */
30
+
31
+ 'use strict';
32
+
33
+ const MODES = Object.freeze(['open', 'ask', 'never']);
34
+ const LEVELS = Object.freeze(['look', 'change']);
35
+ const MODE_WORDS = Object.freeze({ open: 'May come in', ask: 'Only when we let them in', never: 'Never' });
36
+ const LEVEL_WORDS = Object.freeze({ look: 'look only', change: 'make changes' });
37
+ /** "Let them in now" and a request's wanted time: key → milliseconds (null: until switched off, grants only). */
38
+ const GRANT_FOR = Object.freeze({ '1h': 3600000, '24h': 86400000, '7d': 7 * 86400000, off: null });
39
+ const GRANT_WORDS = Object.freeze({ '1h': '1 hour', '24h': '24 hours', '7d': '7 days', off: 'until switched off' });
40
+ const REQUEST_FOR = Object.freeze(['1h', '24h', '7d']);
41
+ /** A request nobody answers ends after this long (CD-32). */
42
+ const REQUEST_LIVES_MS = 24 * 3600000;
43
+ const REASON_MAX = 300;
44
+ /** The customer's answers to a request: allow what was asked, allow look only, decline (CD-32). */
45
+ const ANSWERS = Object.freeze(['allow', 'allow_look', 'decline']);
46
+
47
+ const has = (o, k) => o != null && Object.prototype.hasOwnProperty.call(o, k);
48
+ const rank = (level) => LEVELS.indexOf(level); // -1 for none
49
+ const lower = (a, b) => (rank(a) < 0 || rank(b) < 0 ? null : (rank(a) <= rank(b) ? a : b));
50
+ const higher = (a, b) => (rank(a) < 0 ? (rank(b) < 0 ? null : b) : rank(b) < 0 ? a : (rank(a) >= rank(b) ? a : b));
51
+
52
+ /** Is `s` a setting a customer may store for a kind: open with a level, or ask / never with none? */
53
+ function validSetting(s) {
54
+ if (!s || typeof s !== 'object' || !MODES.includes(s.mode)) return false;
55
+ return s.mode === 'open' ? LEVELS.includes(s.level) : s.level == null;
56
+ }
57
+
58
+ /** Is `s` a starting value a partner may set for its new customers: open with a level, or ask (never Never, CD-39)? */
59
+ function validStart(s) {
60
+ if (!s || typeof s !== 'object') return false;
61
+ return s.mode === 'open' ? LEVELS.includes(s.level) : s.mode === 'ask' && s.level == null;
62
+ }
63
+
64
+ /** `{ mode, level }` with level null unless open. */
65
+ const plain = (s) => ({ mode: s.mode, level: s.mode === 'open' ? s.level : null });
66
+
67
+ /**
68
+ * THE STARTING VALUE of one kind for one customer: the partner's own value for this kind (`partnerStart`, the one in
69
+ * force when the customer was received; the store reads it) when the app lets the partner set this kind, else the
70
+ * kind's own. → `{ mode, level, byPartner }`. A partner value that is not a valid starting value throws: a stored row
71
+ * the rules cannot read is an error, never a default.
72
+ */
73
+ function startOf(kind, partnerStart = null) {
74
+ if (partnerStart != null && kind.partnerMaySetStart === true) {
75
+ if (!validStart({ mode: partnerStart.mode, level: partnerStart.level == null ? null : partnerStart.level })) {
76
+ throw new Error(`customer access: ${JSON.stringify(partnerStart)} is not a starting value a partner may set`);
77
+ }
78
+ return { ...plain(partnerStart), byPartner: true };
79
+ }
80
+ return { ...plain(kind.start), byPartner: false };
81
+ }
82
+
83
+ /** The setting in force for one kind: the stored row when there is one, else its starting value (CD-37). */
84
+ function settingOf(kind, stored, partnerStart = null) {
85
+ if (stored) {
86
+ if (!validSetting({ mode: stored.mode, level: stored.level == null ? null : stored.level })) {
87
+ throw new Error(`customer access: a stored setting ${JSON.stringify({ mode: stored.mode, level: stored.level })} for ${kind.key} is not a setting`);
88
+ }
89
+ return { ...plain({ mode: stored.mode, level: stored.level }), stored: true, byPartner: false };
90
+ }
91
+ return { ...startOf(kind, partnerStart), stored: false };
92
+ }
93
+
94
+ /** UTC 'YYYY-MM-DD HH:MM:SS' (the columns' form) ↔ ms. */
95
+ const stamp = (ms) => new Date(ms).toISOString().slice(0, 19).replace('T', ' ');
96
+ const msOf = (text) => (text ? Date.parse(String(text).replace(' ', 'T') + 'Z') : NaN);
97
+
98
+ /** Is a stored grant row live at `nowMs`: not ended, and its end (if any) still ahead? */
99
+ const grantLive = (g, nowMs) => !!g && !g.ended_at && (g.ends_at == null || msOf(g.ends_at) > nowMs);
100
+ /** Is a stored request still waiting at `nowMs`: not answered, and its 24 hours not up? */
101
+ const requestWaiting = (r, nowMs) => !!r && r.state === 'waiting' && msOf(r.expires_at) > nowMs;
102
+
103
+ /**
104
+ * WHAT THE PARTNER MAY DO NOW IN ONE KIND: `{ level, basis, grant, until }`: level 'look' | 'change' | null; basis
105
+ * 'setting' | 'grant' (the grant when it gives more: its end then bounds a visit); until = the grant's end in ms (null:
106
+ * none). `setting` {mode, level}; `grant` the customer's stored grant row, or null.
107
+ */
108
+ function allowance(setting, grant, nowMs) {
109
+ if (!Number.isFinite(nowMs)) throw new Error('customer access: allowance needs the time (ms)');
110
+ const none = { level: null, basis: null, grant: null, until: null };
111
+ if (!setting || setting.mode === 'never') return none;
112
+ const bySetting = setting.mode === 'open' && LEVELS.includes(setting.level) ? setting.level : null;
113
+ const g = grantLive(grant, nowMs) && LEVELS.includes(grant.level) ? grant : null;
114
+ const level = higher(bySetting, g ? g.level : null);
115
+ if (!level) return none;
116
+ // the setting first when it gives as much: a visit under "May come in" is not bounded by a grant that ends sooner
117
+ if (bySetting && rank(bySetting) >= rank(level)) return { level, basis: 'setting', grant: null, until: null };
118
+ return { level, basis: 'grant', grant: g, until: g.ends_at == null ? null : msOf(g.ends_at) };
119
+ }
120
+
121
+ /**
122
+ * THE ANSWER FOR ONE KIND: `{ kind, setting, allowance }` from that kind's own rows only: its stored setting (or null),
123
+ * the partner's starting value for it in force when the customer was received (or null), and the customer's grant.
124
+ */
125
+ function answerFor(kind, { stored = null, partnerStart = null, grant = null } = {}, nowMs) {
126
+ const setting = settingOf(kind, stored, partnerStart);
127
+ return { kind: kind.key, setting, allowance: allowance(setting, grant, nowMs) };
128
+ }
129
+
130
+ /** Every kind set to Never: the customer is closed to its partner (CD-35, CD-36): no grant, no request, no visit. */
131
+ const allClosed = (settings) => settings.length > 0 && settings.every((s) => s.mode === 'never');
132
+
133
+ /**
134
+ * IS THE "WE MANAGE THIS CUSTOMER" MARK IN FORCE: a mark stored, every kind not set to Never is May come in (D-0014
135
+ * answer 9), and at least one kind is. `settings` the settings in force, one per kind.
136
+ */
137
+ function managedInForce(settings, managed) {
138
+ if (!managed || !Array.isArray(settings) || settings.length === 0) return false;
139
+ const open = settings.filter((s) => s.mode !== 'never');
140
+ return open.length > 0 && open.every((s) => s.mode === 'open' && LEVELS.includes(s.level));
141
+ }
142
+
143
+ /**
144
+ * MAY A HELPER ASK TO COME IN AT `level`: 'closed' when every kind is Never (no request under Never, CD-35);
145
+ * 'already' when every kind not set to Never already allows that level; else null (the request may be made).
146
+ * `answers` the kinds' answers (answerFor).
147
+ */
148
+ function askRefusal(answers, level) {
149
+ if (allClosed(answers.map((a) => a.setting))) return 'closed';
150
+ const open = answers.filter((a) => a.setting.mode !== 'never');
151
+ if (open.every((a) => a.allowance.level && rank(a.allowance.level) >= rank(level))) return 'already';
152
+ return null;
153
+ }
154
+
155
+ /**
156
+ * WHAT THE ACCESS COLUMN SAYS FOR ONE KIND: `{ state, may, level, until, askedAt, requestId }`:
157
+ * may the setting lets the partner in (`level`)
158
+ * let_in a grant lets it in, until `until` (null: until switched off)
159
+ * waiting the viewer's request is out
160
+ * ask Only when we let them in
161
+ * closed Never
162
+ * How several kinds' states make one cell is decided with the first app that has several (D-0014 answer 11).
163
+ */
164
+ function columnState(answer, request, nowMs) {
165
+ const a = answer.allowance;
166
+ if (a.level) return { state: a.basis === 'grant' ? 'let_in' : 'may', may: true, level: a.level, until: a.until == null ? null : stamp(a.until) };
167
+ if (answer.setting.mode === 'never') return { state: 'closed', may: false };
168
+ if (requestWaiting(request, nowMs)) return { state: 'waiting', may: false, askedAt: request.created_at, requestId: Number(request.id) };
169
+ return { state: 'ask', may: false };
170
+ }
171
+
172
+ module.exports = {
173
+ MODES, LEVELS, MODE_WORDS, LEVEL_WORDS, GRANT_FOR, GRANT_WORDS, REQUEST_FOR, REQUEST_LIVES_MS, REASON_MAX, ANSWERS,
174
+ has, rank, lower, higher, validSetting, validStart, startOf, settingOf, stamp, msOf, grantLive, requestWaiting,
175
+ allowance, answerFor, allClosed, managedInForce, askRefusal, columnState
176
+ };