@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.
- package/CHANGELOG.md +172 -0
- package/README.md +450 -2
- package/assets/visit.js +86 -0
- package/index.js +19 -0
- package/lib/access/audit.js +58 -0
- package/lib/access/index.js +30 -0
- package/lib/access/kinds.js +61 -0
- package/lib/access/rules.js +176 -0
- package/lib/access/store.js +601 -0
- package/lib/access/tables.js +176 -0
- package/lib/visits/index.js +28 -0
- package/lib/visits/options.js +183 -0
- package/lib/visits/record.js +76 -0
- package/lib/visits/rules.js +290 -0
- package/lib/visits/visits.js +1022 -0
- package/package.json +37 -4
- package/views/customer-visit-banner.ejs +20 -0
- package/views/customer-visit-ended.ejs +11 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE TABLES OF SUPPORT ACCESS, AS DATA (db-worker 0.31.0 `defineTables`). The app's own generator writes them into the
|
|
3
|
+
* app's own migration pair (`aria-tenancy new --definitions customer_access`), which the app commits and never edits;
|
|
4
|
+
* the app spreads `accessTenancy()` into its `defineTenancy`; and `checkAccessSchema` / `assertAccessSchema` compare the
|
|
5
|
+
* database with this set (at boot, or in the app's live test).
|
|
6
|
+
*
|
|
7
|
+
* VERSION 2 NAMES. None of the first app's five table names (support_access, support_defaults, support_grants,
|
|
8
|
+
* support_requests, support_managed) is used, so an app holding those can create these and drop those in one migration.
|
|
9
|
+
*
|
|
10
|
+
* customer_access_settings CUSTOMER one row per (customer, partner, kind) the customer has SET; no row = the
|
|
11
|
+
* starting value. Unique (customer_id, partner_id, kind).
|
|
12
|
+
* customer_access_defaults PARTNER a partner's starting value per kind for its new customers; append-only, one
|
|
13
|
+
* row per save. No customer column and no key into customers (a partner table
|
|
14
|
+
* keys only into partner tables: db-worker refuses the other).
|
|
15
|
+
* customer_access_grants CUSTOMER "Let them in now": one live grant per customer (partial unique index); no kind.
|
|
16
|
+
* customer_access_requests CUSTOMER a helper asking to come in: one waiting request per helper per customer; no kind.
|
|
17
|
+
* customer_access_managed CUSTOMER the partner's "we manage this customer" mark, one per customer; no kind.
|
|
18
|
+
*
|
|
19
|
+
* Every CUSTOMER table is keyed (customer_id, partner_id) → customers (id, partner_id) ON DELETE CASCADE ON UPDATE
|
|
20
|
+
* CASCADE by the generator. A user is a plain column with no key (user_id, set_by_user): a key into the principal table is
|
|
21
|
+
* attribution, and the format refuses it.
|
|
22
|
+
*
|
|
23
|
+
* WHAT THE SET NEEDS OF THE APP'S OWN TABLES (the anchors; the schema check verifies each):
|
|
24
|
+
* customers id TEXT, partner_id, name TEXT, status TEXT ('active' is active), created_at TEXT (UTC
|
|
25
|
+
* 'YYYY-MM-DD HH:MM:SS', stamped by the database: the received-time rule compares it, as text, with
|
|
26
|
+
* customer_access_defaults.created_at, stamped by the same clock); unique (id, partner_id)
|
|
27
|
+
* customer_contacts id TEXT, customer_id TEXT, partner_id, name TEXT; unique (id, partner_id)
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
'use strict';
|
|
31
|
+
|
|
32
|
+
const { defineTables, tenancyFragment, checkDefinedSchema, assertDefinedSchema } = require('@aria-framework/db-worker');
|
|
33
|
+
|
|
34
|
+
const LEVEL = "level IN ('look', 'change')";
|
|
35
|
+
const LEVEL_RULE = "(mode = 'open' AND level IS NOT NULL) OR (mode <> 'open' AND level IS NULL)";
|
|
36
|
+
const name200 = (c) => `length(${c}) BETWEEN 1 AND 200`;
|
|
37
|
+
const KIND = { name: 'kind', type: 'TEXT', notNull: true, check: 'length(kind) BETWEEN 1 AND 40' };
|
|
38
|
+
const USER = { postgres: 'BIGINT', sqlite: 'INTEGER' };
|
|
39
|
+
|
|
40
|
+
const RAW = () => ({
|
|
41
|
+
name: 'customer_access',
|
|
42
|
+
version: '1.0.0',
|
|
43
|
+
comment: [
|
|
44
|
+
'SUPPORT ACCESS, version 2 of the model (@aria-framework/customer, part access): who of the customer\'s partner may',
|
|
45
|
+
'come in to help, per kind of data, as the customer set it. No helper tier: the partner is the one helper.',
|
|
46
|
+
'customer_access_settings the customer\'s setting per kind; no row = the starting value (held in code)',
|
|
47
|
+
'customer_access_defaults a partner\'s starting value per kind for its NEW customers, append-only',
|
|
48
|
+
'customer_access_grants let them in now: one live grant per customer, for every kind not set to Never',
|
|
49
|
+
'customer_access_requests a helper asking to come in: one waiting request per helper per customer',
|
|
50
|
+
'customer_access_managed the partner\'s "we manage this customer" mark',
|
|
51
|
+
'Times are UTC \'YYYY-MM-DD HH:MM:SS\'.'
|
|
52
|
+
],
|
|
53
|
+
anchors: {
|
|
54
|
+
customers: {
|
|
55
|
+
tenancy: { customer: 'id' },
|
|
56
|
+
columns: [
|
|
57
|
+
{ name: 'id', type: 'TEXT', notNull: true },
|
|
58
|
+
{ name: 'partner_id', type: 'PARTNER_ID', notNull: true },
|
|
59
|
+
{ name: 'name', type: 'TEXT', notNull: true },
|
|
60
|
+
{ name: 'status', type: 'TEXT', notNull: true },
|
|
61
|
+
{ name: 'created_at', type: 'TEXT', notNull: true }
|
|
62
|
+
],
|
|
63
|
+
unique: [['id', 'partner_id']]
|
|
64
|
+
},
|
|
65
|
+
customer_contacts: {
|
|
66
|
+
tenancy: { customer: 'customer_id' },
|
|
67
|
+
columns: [
|
|
68
|
+
{ name: 'id', type: 'TEXT', notNull: true },
|
|
69
|
+
{ name: 'customer_id', type: 'TEXT', notNull: true },
|
|
70
|
+
{ name: 'partner_id', type: 'PARTNER_ID', notNull: true },
|
|
71
|
+
{ name: 'name', type: 'TEXT', notNull: true }
|
|
72
|
+
],
|
|
73
|
+
unique: [['id', 'partner_id']]
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
tables: [
|
|
77
|
+
{
|
|
78
|
+
name: 'customer_access_settings',
|
|
79
|
+
description: "a customer's own choice, per kind of data, of whether its partner may come in to help",
|
|
80
|
+
tenancy: { customer: 'customer_id' },
|
|
81
|
+
columns: [
|
|
82
|
+
KIND,
|
|
83
|
+
{ name: 'mode', type: 'TEXT', notNull: true, check: "mode IN ('open', 'ask', 'never')" },
|
|
84
|
+
{ name: 'level', type: 'TEXT', check: LEVEL },
|
|
85
|
+
{ name: 'set_by_name', type: 'TEXT', notNull: true, check: name200('set_by_name') },
|
|
86
|
+
{ name: 'set_by_contact', type: 'TEXT' },
|
|
87
|
+
{ name: 'updated_at', type: 'TEXT', notNull: true, default: { utcNow: true } }
|
|
88
|
+
],
|
|
89
|
+
constraints: [{ name: 'ck_customer_access_settings_level', check: LEVEL_RULE }]
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
name: 'customer_access_defaults',
|
|
93
|
+
description: "a partner's starting support access per kind of data for its new customers, one row per save",
|
|
94
|
+
tenancy: 'PARTNER',
|
|
95
|
+
columns: [
|
|
96
|
+
KIND,
|
|
97
|
+
{ name: 'mode', type: 'TEXT', notNull: true, check: "mode IN ('open', 'ask')" },
|
|
98
|
+
{ name: 'level', type: 'TEXT', check: LEVEL },
|
|
99
|
+
{ name: 'set_by_name', type: 'TEXT', notNull: true, check: name200('set_by_name') },
|
|
100
|
+
{ name: 'set_by_user', type: USER }
|
|
101
|
+
],
|
|
102
|
+
constraints: [{ name: 'ck_customer_access_defaults_level', check: LEVEL_RULE }]
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
name: 'customer_access_grants',
|
|
106
|
+
description: 'a customer letting its partner in for a while, into every kind not set to Never, and how it ended',
|
|
107
|
+
tenancy: { customer: 'customer_id' },
|
|
108
|
+
columns: [
|
|
109
|
+
{ name: 'level', type: 'TEXT', notNull: true, check: LEVEL },
|
|
110
|
+
{ name: 'ends_at', type: 'TEXT' },
|
|
111
|
+
{ name: 'given_by_name', type: 'TEXT', notNull: true, check: name200('given_by_name') },
|
|
112
|
+
{ name: 'given_by_contact', type: 'TEXT' },
|
|
113
|
+
{ name: 'request_id', type: 'BIGINT' },
|
|
114
|
+
{ name: 'ended_at', type: 'TEXT' },
|
|
115
|
+
{ name: 'ended_how', type: 'TEXT', check: "ended_how IN ('ended', 'lapsed', 'replaced')" },
|
|
116
|
+
{ name: 'ended_by_name', type: 'TEXT', check: 'length(ended_by_name) <= 200' }
|
|
117
|
+
],
|
|
118
|
+
constraints: [{ name: 'ck_customer_access_grants_ended', check: '(ended_at IS NULL AND ended_how IS NULL) OR (ended_at IS NOT NULL AND ended_how IS NOT NULL)' }]
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
name: 'customer_access_requests',
|
|
122
|
+
description: "a helper asking a customer to be let in, and the customer's answer (the first answer settles it)",
|
|
123
|
+
tenancy: { customer: 'customer_id' },
|
|
124
|
+
columns: [
|
|
125
|
+
{ name: 'user_id', type: 'BIGINT', notNull: true },
|
|
126
|
+
{ name: 'user_partner_id', type: 'BIGINT', notNull: true },
|
|
127
|
+
{ name: 'user_name', type: 'TEXT', notNull: true, check: name200('user_name') },
|
|
128
|
+
{ name: 'company', type: 'TEXT', notNull: true, check: name200('company') },
|
|
129
|
+
{ name: 'reason', type: 'TEXT', notNull: true, check: 'length(reason) BETWEEN 1 AND 300' },
|
|
130
|
+
{ name: 'duration', type: 'TEXT', notNull: true, check: "duration IN ('1h', '24h', '7d')" },
|
|
131
|
+
{ name: 'level', type: 'TEXT', notNull: true, check: LEVEL },
|
|
132
|
+
{ name: 'state', type: 'TEXT', notNull: true, default: { text: 'waiting' }, check: "state IN ('waiting', 'allowed', 'declined', 'lapsed', 'cancelled')" },
|
|
133
|
+
{ name: 'expires_at', type: 'TEXT', notNull: true },
|
|
134
|
+
{ name: 'answered_at', type: 'TEXT' },
|
|
135
|
+
{ name: 'answered_by_name', type: 'TEXT', check: 'length(answered_by_name) <= 200' },
|
|
136
|
+
{ name: 'answered_by_contact', type: 'TEXT' },
|
|
137
|
+
{ name: 'granted_level', type: 'TEXT', check: "granted_level IN ('look', 'change')" },
|
|
138
|
+
{ name: 'grant_id', type: 'BIGINT' }
|
|
139
|
+
]
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
name: 'customer_access_managed',
|
|
143
|
+
description: "a partner's standing 'we manage this customer' mark (its staff come in without a reason while the customer lets them)",
|
|
144
|
+
tenancy: { customer: 'customer_id' },
|
|
145
|
+
columns: [
|
|
146
|
+
{ name: 'set_by_name', type: 'TEXT', notNull: true, check: name200('set_by_name') },
|
|
147
|
+
{ name: 'set_by_user', type: USER }
|
|
148
|
+
]
|
|
149
|
+
}
|
|
150
|
+
],
|
|
151
|
+
indexes: [
|
|
152
|
+
{ name: 'uq_customer_access_settings_kind', table: 'customer_access_settings', unique: true, columns: ['customer_id', 'partner_id', 'kind'] },
|
|
153
|
+
{ name: 'idx_customer_access_defaults_kind', table: 'customer_access_defaults', columns: ['partner_id', 'kind', 'created_at'] },
|
|
154
|
+
{ name: 'uq_customer_access_grants_live', table: 'customer_access_grants', unique: true, columns: ['customer_id', 'partner_id'], where: 'ended_at IS NULL' },
|
|
155
|
+
{ name: 'idx_customer_access_grants_open', table: 'customer_access_grants', columns: ['ended_at', 'ends_at'] },
|
|
156
|
+
{ name: 'uq_customer_access_requests_waiting', table: 'customer_access_requests', unique: true, columns: ['customer_id', 'partner_id', 'user_id'], where: "state = 'waiting'" },
|
|
157
|
+
{ name: 'idx_customer_access_requests_state', table: 'customer_access_requests', columns: ['state', 'expires_at'] },
|
|
158
|
+
{ name: 'uq_customer_access_managed_customer', table: 'customer_access_managed', unique: true, columns: ['customer_id', 'partner_id'] }
|
|
159
|
+
]
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
/** The set, defined and frozen. */
|
|
163
|
+
const accessTables = defineTables(RAW());
|
|
164
|
+
|
|
165
|
+
/** What the app spreads into its defineTenancy: `defineTenancy({ ..., ...accessTenancy() })`. */
|
|
166
|
+
const accessTenancy = () => tenancyFragment(accessTables);
|
|
167
|
+
|
|
168
|
+
/** Compare the database with the set: `{ problems, compared }` (db-worker checkDefinedSchema). */
|
|
169
|
+
const checkAccessSchema = (driver, { partnerIdType } = {}) => checkDefinedSchema(driver, [accessTables], { partnerIdType });
|
|
170
|
+
/** The same, throwing TABLE_DEFINITIONS_MISMATCH naming every problem: what the app calls when it starts. */
|
|
171
|
+
const assertAccessSchema = (driver, { partnerIdType } = {}) => assertDefinedSchema(driver, [accessTables], { partnerIdType });
|
|
172
|
+
|
|
173
|
+
/** The table names, for an app's own lists. */
|
|
174
|
+
const ACCESS_TABLES = Object.freeze(accessTables.tables.map((t) => t.name));
|
|
175
|
+
|
|
176
|
+
module.exports = { accessTables, accessTenancy, checkAccessSchema, assertAccessSchema, ACCESS_TABLES, RAW_ACCESS_TABLES: RAW };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Part "visits" (0.2): working in one customer: the way in, the level per kind, the reason, four hours, the re-check on
|
|
3
|
+
* every request and live event, the gate in front of the app's content, the two audit rows, the banner and the ended
|
|
4
|
+
* notice, the typed-work notice.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const rules = require('./rules');
|
|
11
|
+
const { createVisits } = require('./visits');
|
|
12
|
+
const { VISIT_ACTIONS, VISIT_ACTION_LABELS } = require('./record');
|
|
13
|
+
|
|
14
|
+
module.exports = {
|
|
15
|
+
createVisits,
|
|
16
|
+
visitRules: rules,
|
|
17
|
+
VISIT_HOURS: rules.VISIT_HOURS,
|
|
18
|
+
VISIT_MS: rules.VISIT_MS,
|
|
19
|
+
VISIT_WORDS: rules.VISIT_WORDS,
|
|
20
|
+
VISIT_ENDINGS: rules.VISIT_ENDINGS,
|
|
21
|
+
VISIT_MARKER: rules.VISIT_MARKER,
|
|
22
|
+
VISIT_ACTIONS,
|
|
23
|
+
VISIT_ACTION_LABELS,
|
|
24
|
+
/** The partials: customer-visit-banner.ejs and customer-visit-ended.ejs (add to the app's views). */
|
|
25
|
+
viewsDir: path.join(__dirname, '..', '..', 'views'),
|
|
26
|
+
/** The browser script: visit.js (the app serves it and loads it with a script tag). */
|
|
27
|
+
assetsDir: path.join(__dirname, '..', '..', 'assets')
|
|
28
|
+
};
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createVisits' OPTIONS, checked once at construction: every required one is refused BY NAME when missing or out of
|
|
3
|
+
* shape, an unknown one is refused, and the app's lists are checked against each other (a permission in one kind and one
|
|
4
|
+
* level only; every kind has its permissions; every gated mount names a kind; every outside entry lies under a mount).
|
|
5
|
+
* Nothing here has a default that "looks right": the paths, the permission names and the lists are the app's.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
'use strict';
|
|
9
|
+
|
|
10
|
+
const { isKinds } = require('../access/kinds');
|
|
11
|
+
const R = require('./rules');
|
|
12
|
+
|
|
13
|
+
function fail(message) { throw new Error(`createVisits: ${message}`); }
|
|
14
|
+
|
|
15
|
+
const isFn = (f) => typeof f === 'function';
|
|
16
|
+
const READ = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
17
|
+
const SEG = /^[A-Za-z0-9_~-][A-Za-z0-9._~-]*$/;
|
|
18
|
+
const PARAM = /^:[A-Za-z_][A-Za-z0-9_]*$/;
|
|
19
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
20
|
+
const PERM = /^[^\s]{1,120}$/;
|
|
21
|
+
|
|
22
|
+
/** A full mount path: "/" then literal segments (letters, digits, . _ ~ -), no trailing "/", no dot segment. */
|
|
23
|
+
function isMountPath(p) {
|
|
24
|
+
return typeof p === 'string' && p.length <= 1024 && /^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+$/.test(p)
|
|
25
|
+
&& !p.split('/').some((s) => s === '.' || s === '..');
|
|
26
|
+
}
|
|
27
|
+
/** A local path this app may send the browser to (fleet view's rule): "/x" or "/x?y", never "//host", "/\host", a scheme, a space. */
|
|
28
|
+
function isLocalPath(p) {
|
|
29
|
+
return typeof p === 'string' && p.length <= 2048 && /^\/(?![/\\])/.test(p) && !/[\\\x00-\x20\x7f]/.test(p);
|
|
30
|
+
}
|
|
31
|
+
/** Is `p` the mount `m` or under it? */
|
|
32
|
+
const under = (p, m) => p === m || p.startsWith(`${m}/`);
|
|
33
|
+
|
|
34
|
+
/** One `outside` entry: "METHOD /literal/or/:name/segments" (fleet view's grammar; a read method is allowed here). */
|
|
35
|
+
function parseOutside(entry) {
|
|
36
|
+
const m = typeof entry === 'string' && entry.match(/^([A-Z]+) (\/[^ ]*)$/);
|
|
37
|
+
if (!m) fail(`outside: ${JSON.stringify(entry)} is not "METHOD /path"`);
|
|
38
|
+
const [, method, p] = m;
|
|
39
|
+
const segs = p.split('/');
|
|
40
|
+
const ok = p !== '/' && segs.slice(1).every((s) => (SEG.test(s) && s !== '.' && s !== '..') || PARAM.test(s));
|
|
41
|
+
if (!ok) fail(`outside: ${JSON.stringify(entry)}: the path must be literal segments (letters, digits, . _ ~ -) and :name segments, no query, wildcard, empty, dot or encoded segment`);
|
|
42
|
+
return Object.freeze({ entry, method, path: p, segs });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const MESSAGE_KEYS = ['outside', 'lookOnly', 'closed', 'permission', 'unlisted', 'leaveFirst', 'busy', 'signedOut', 'placeChanged', 'left',
|
|
46
|
+
'started', 'lowered', 'byGrant', 'refusal', 'invalid'];
|
|
47
|
+
const KNOWN = ['tenancy', 'db', 'accessModel', 'kinds', 'levels', 'notCapped', 'permission', 'roleCan', 'requirePermission', 'partnerById',
|
|
48
|
+
'audit', 'fleetView', 'sessionEnding', 'tellPartner', 'fitMemoMs', 'mountPath', 'mounts', 'outside', 'customerParams', 'paths',
|
|
49
|
+
'notPages', 'logger', 'now', 'flash', 'wantsJson', 'refusalView', 'messages', 'caseSensitive', 'platformOnly'];
|
|
50
|
+
// The words of the start route's refusals and invalid input (the `refusal` and `invalid` messages are objects of these).
|
|
51
|
+
const REFUSAL_KEYS = ['fleet-view', 'permission', 'not-found', 'inactive', 'closed', 'role', 'waiting', 'not-allowed'];
|
|
52
|
+
const INVALID_KEYS = ['reason', 'reason-long', 'level'];
|
|
53
|
+
const isText = (v) => (typeof v === 'string' && v.length > 0) || isFn(v);
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Check every option; → the configuration createVisits runs on (frozen lists, the permission index, parsed entries).
|
|
57
|
+
*/
|
|
58
|
+
function checkOptions(options) {
|
|
59
|
+
const o = options;
|
|
60
|
+
if (!o || typeof o !== 'object' || Array.isArray(o)) fail('pass the options object (see the README, "Visits")');
|
|
61
|
+
for (const k of Object.keys(o)) if (!KNOWN.includes(k)) fail(`unknown option "${k}"`);
|
|
62
|
+
|
|
63
|
+
const t = o.tenancy;
|
|
64
|
+
if (!t || !['asCustomer', 'asPartner', 'contextFor', 'runWithTenant'].every((f) => isFn(t[f]))) {
|
|
65
|
+
fail('tenancy is required: what @aria-framework/tenancy createTenancy returned (asCustomer, asPartner, contextFor, runWithTenant)');
|
|
66
|
+
}
|
|
67
|
+
if (!o.db || !isFn(o.db.invoke)) fail('db is required: the app\'s db client, built with { customerPin: true }');
|
|
68
|
+
if (typeof o.accessModel !== 'string' || !NAME.test(o.accessModel)) fail('accessModel is required: the model name the app registered createAccessStore under');
|
|
69
|
+
if (!isKinds(o.kinds)) fail('kinds is required: what defineKinds() returned');
|
|
70
|
+
const kinds = o.kinds.keys;
|
|
71
|
+
|
|
72
|
+
const lv = o.levels;
|
|
73
|
+
if (!lv || typeof lv !== 'object' || Array.isArray(lv)) fail('levels is required: { [kind]: { look: [permission], change: [permission] } }');
|
|
74
|
+
for (const k of Object.keys(lv)) if (!kinds.includes(k)) fail(`levels names "${k}", which is not one of the kinds (${kinds.join(', ')})`);
|
|
75
|
+
const levels = {};
|
|
76
|
+
for (const k of kinds) {
|
|
77
|
+
const e = lv[k];
|
|
78
|
+
if (!e || typeof e !== 'object' || Array.isArray(e) || Object.keys(e).some((x) => x !== 'look' && x !== 'change')) {
|
|
79
|
+
fail(`levels.${k} is required: { look: [permission, ...], change: [permission, ...] }`);
|
|
80
|
+
}
|
|
81
|
+
if (!Array.isArray(e.look) || e.look.length === 0) fail(`levels.${k}.look must list at least one permission (what lets a role look at ${k})`);
|
|
82
|
+
if (!Array.isArray(e.change)) fail(`levels.${k}.change must be a list of permissions (it may be empty)`);
|
|
83
|
+
for (const p of [...e.look, ...e.change]) if (typeof p !== 'string' || !PERM.test(p)) fail(`levels.${k}: ${JSON.stringify(p)} is not a permission name`);
|
|
84
|
+
levels[k] = Object.freeze({ look: Object.freeze([...e.look]), change: Object.freeze([...e.change]) });
|
|
85
|
+
}
|
|
86
|
+
const index = R.permissionIndex(levels); // throws on a permission named twice
|
|
87
|
+
if (!Array.isArray(o.notCapped)) fail('notCapped is required: the permissions a visit leaves to the role alone ([] for none)');
|
|
88
|
+
for (const p of o.notCapped) {
|
|
89
|
+
if (typeof p !== 'string' || !PERM.test(p)) fail(`notCapped: ${JSON.stringify(p)} is not a permission name`);
|
|
90
|
+
if (index.has(p)) fail(`notCapped: "${p}" is in levels (a permission is either a kind's or not capped)`);
|
|
91
|
+
}
|
|
92
|
+
if (typeof o.permission !== 'string' || !PERM.test(o.permission)) fail('permission is required: the name of the app\'s work-in permission');
|
|
93
|
+
if (index.has(o.permission)) fail(`permission "${o.permission}" is in levels: the work-in permission is not a kind's`);
|
|
94
|
+
|
|
95
|
+
for (const k of ['roleCan', 'requirePermission', 'partnerById', 'audit', 'sessionEnding', 'tellPartner']) {
|
|
96
|
+
if (!isFn(o[k])) fail(`${k} is required (a function; see the README, "Visits")`);
|
|
97
|
+
}
|
|
98
|
+
if (o.fleetView !== null && (!o.fleetView || typeof o.fleetView !== 'object' || !isLocalPath(o.fleetView.startPath) || !isFn(o.fleetView.isOn)
|
|
99
|
+
|| !isFn(o.fleetView.addStartCheck) || !isFn(o.fleetView.inRow) || !isFn(o.fleetView.classify))) {
|
|
100
|
+
fail('fleetView is required: what createFleetView of @aria-framework/tenancy 0.5.0 or later returned (with addStartCheck and inRow), or null for an app without fleet view');
|
|
101
|
+
}
|
|
102
|
+
if (!(Number.isInteger(o.fitMemoMs) && o.fitMemoMs >= 0 && o.fitMemoMs <= 5000)) fail('fitMemoMs is required: a whole number of milliseconds, 0 to 5000 (CD-22 allows five seconds)');
|
|
103
|
+
if (!isMountPath(o.mountPath)) fail('mountPath is required: the full path of the Customers pages the visit routes sit under ("/x"), literal segments, no trailing slash');
|
|
104
|
+
// CD-21 (review round 3): Leave needs only a session; fleet view's read-only guard runs before every router, so its
|
|
105
|
+
// readOnlyExcept must let Leave through (read through fleet view's own classify, the guard's question)
|
|
106
|
+
if (o.fleetView && o.fleetView.classify('POST', `${o.mountPath}/leave`) === 'refused') {
|
|
107
|
+
fail(`fleetView: its readOnlyExcept must list "POST ${o.mountPath}/leave" (CD-21: Leave is never refused, not even by fleet view's read-only guard)`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (!Array.isArray(o.mounts) || o.mounts.length === 0) fail('mounts is required: [{ path, kind }], every gated mount with its kind (full paths)');
|
|
111
|
+
const mounts = o.mounts.map((m, i) => {
|
|
112
|
+
if (!m || typeof m !== 'object' || !isMountPath(m.path)) fail(`mounts[${i}]: path must be a full mount path ("/x")`);
|
|
113
|
+
if (!kinds.includes(m.kind)) fail(`mounts[${i}] (${m.path}): kind ${JSON.stringify(m.kind)} is not one of the kinds (${kinds.join(', ')})`);
|
|
114
|
+
if (Object.keys(m).some((k) => k !== 'path' && k !== 'kind')) fail(`mounts[${i}]: only { path, kind }`);
|
|
115
|
+
return Object.freeze({ path: m.path, kind: m.kind });
|
|
116
|
+
});
|
|
117
|
+
for (const a of mounts) {
|
|
118
|
+
for (const b of mounts) if (a !== b && under(b.path, a.path)) fail(`mounts: ${b.path} is ${a.path === b.path ? 'listed twice' : `under ${a.path}`} (one mount, one kind)`);
|
|
119
|
+
if (under(o.mountPath, a.path) || under(a.path, o.mountPath)) fail(`mounts: ${a.path} and mountPath ${o.mountPath} overlap (the visit routes are never gated)`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (!Array.isArray(o.outside)) fail('outside is required: the "METHOD /path" requests a gated mount serves outside a visit ([] for none)');
|
|
123
|
+
const outside = o.outside.map(parseOutside);
|
|
124
|
+
for (const e of outside) {
|
|
125
|
+
if (!mounts.some((m) => under(e.path, m.path))) fail(`outside: ${e.entry} is under no gated mount`);
|
|
126
|
+
if (READ.has(e.method) && e.method !== 'GET') fail(`outside: ${e.entry}: list GET (it also lets HEAD through)`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const cp = o.customerParams;
|
|
130
|
+
if (!cp || typeof cp !== 'object' || !Array.isArray(cp.query) || !Array.isArray(cp.body) || Object.keys(cp).some((k) => k !== 'query' && k !== 'body')) {
|
|
131
|
+
fail('customerParams is required: { query: [name], body: [name] }, the parameters naming a customer that a visit rewrites to its own (CD-25)');
|
|
132
|
+
}
|
|
133
|
+
for (const n of [...cp.query, ...cp.body]) if (typeof n !== 'string' || !NAME.test(n)) fail(`customerParams: ${JSON.stringify(n)} is not a parameter name`);
|
|
134
|
+
|
|
135
|
+
const p = o.paths;
|
|
136
|
+
if (!p || typeof p !== 'object' || !isLocalPath(p.customers) || !isFn(p.customer) || !isFn(p.landing)) {
|
|
137
|
+
fail('paths is required: { customers: "/x", customer(id) => path, landing(visit) => path }, local paths');
|
|
138
|
+
}
|
|
139
|
+
if (!Array.isArray(o.notPages) || !o.notPages.every((r) => r instanceof RegExp)) fail('notPages is required: RegExps of the full paths under a mount that are not pages (files, fragments) ([] for none)');
|
|
140
|
+
if (!o.logger || !isFn(o.logger.warn) || !isFn(o.logger.error)) fail('logger is required (warn and error)');
|
|
141
|
+
|
|
142
|
+
if (o.now != null && !isFn(o.now)) fail('now must be a function () => milliseconds');
|
|
143
|
+
if (o.flash != null && !isFn(o.flash)) fail('flash must be a function (req, res, kind, text), which may return a promise');
|
|
144
|
+
if (o.wantsJson != null && !isFn(o.wantsJson)) fail('wantsJson must be a function (req) => boolean');
|
|
145
|
+
if (o.refusalView != null && (typeof o.refusalView !== 'string' || !o.refusalView)) fail('refusalView must be a view name');
|
|
146
|
+
if (o.messages != null) {
|
|
147
|
+
if (typeof o.messages !== 'object' || Array.isArray(o.messages)) fail('messages must be an object');
|
|
148
|
+
for (const [k, v] of Object.entries(o.messages)) {
|
|
149
|
+
if (!MESSAGE_KEYS.includes(k)) fail(`messages: unknown message "${k}" (known: ${MESSAGE_KEYS.join(', ')})`);
|
|
150
|
+
if (k === 'refusal' || k === 'invalid') {
|
|
151
|
+
const known = k === 'refusal' ? REFUSAL_KEYS : INVALID_KEYS;
|
|
152
|
+
if (!v || typeof v !== 'object' || Array.isArray(v)) fail(`messages.${k} must be an object of { ${known.join(', ')} }`);
|
|
153
|
+
for (const [kk, vv] of Object.entries(v)) {
|
|
154
|
+
if (!known.includes(kk)) fail(`messages.${k}: unknown "${kk}" (known: ${known.join(', ')})`);
|
|
155
|
+
if (!isText(vv)) fail(`messages.${k}.${kk} must be a sentence (a non-empty string) or a function returning one`);
|
|
156
|
+
}
|
|
157
|
+
} else if (!isText(v)) fail(`messages.${k} must be a sentence (a non-empty string) or a function returning one`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (o.caseSensitive != null && typeof o.caseSensitive !== 'boolean') fail('caseSensitive must be true or false (Express\'s "case sensitive routing"; default false, as Express\'s)');
|
|
161
|
+
if (o.platformOnly != null) {
|
|
162
|
+
if (!Array.isArray(o.platformOnly) || !o.platformOnly.every((x) => typeof x === 'string')) fail('platformOnly must be a list of permission names (the app\'s platform-only permissions)');
|
|
163
|
+
// a person's role is judged at partner scope (at their home partner): a platform-only permission is never held there
|
|
164
|
+
const named = [o.permission, ...index.keys(), ...o.notCapped].filter((x) => o.platformOnly.includes(x));
|
|
165
|
+
if (named.length) fail(`platformOnly: ${named.join(', ')} ${named.length === 1 ? 'is' : 'are'} named in permission, levels or notCapped; a role is judged at partner scope, where a platform-only permission is never held`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return Object.freeze({
|
|
169
|
+
...o,
|
|
170
|
+
caseSensitive: o.caseSensitive === true,
|
|
171
|
+
kindKeys: Object.freeze([...kinds]),
|
|
172
|
+
levels: Object.freeze(levels),
|
|
173
|
+
index,
|
|
174
|
+
notCapped: new Set(o.notCapped),
|
|
175
|
+
mounts: Object.freeze(mounts),
|
|
176
|
+
outside: Object.freeze(outside),
|
|
177
|
+
customerParams: Object.freeze({ query: Object.freeze([...cp.query]), body: Object.freeze([...cp.body]) }),
|
|
178
|
+
notPages: Object.freeze([...o.notPages]),
|
|
179
|
+
now: o.now || Date.now
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
module.exports = { checkOptions, isLocalPath, isMountPath, under, MESSAGE_KEYS };
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A VISIT IS TWO ROWS OF THE APP'S OWN AUDIT TRAIL (CD-44, CD-45): a start and a stop, under the person's own name, in
|
|
3
|
+
* the trail of the partner the visit was made under (the house person who came in as a partner: that partner's trail).
|
|
4
|
+
* There is no separate log. The names are the first customer-driven app's, so its rows read the same after it moves
|
|
5
|
+
* onto this package. Both rows carry the visit's id, which pairs them; every other row written during the visit is
|
|
6
|
+
* stamped by the app's audit helper with `stampOf(req)` (`working_in`, `visit`).
|
|
7
|
+
*
|
|
8
|
+
* start customer, visit, reason (or managed: true), levels (per kind), level (the highest), until, company (the
|
|
9
|
+
* person's home partner), let_in per kind (setting | grant), grant and let_in_by when a kind is let in by the
|
|
10
|
+
* customer's grant, asked when some kind's level is lower than what was asked
|
|
11
|
+
* stop customer, visit, levels, level, ended (left | expired | signed_out | refused), because (refused only),
|
|
12
|
+
* minutes, started_at
|
|
13
|
+
*
|
|
14
|
+
* Version 2 of the model has no helper tier (Platform D-0013): neither row carries one. Both rows carry
|
|
15
|
+
* `acting_as_partner: <partner>` when the visit was MADE working in that partner (the record's `acting`), whatever the
|
|
16
|
+
* session says when the row is written (review round 1); the app's helper, given the request as the visit was made
|
|
17
|
+
* (visits.js asTheVisit), stamps the same.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
'use strict';
|
|
21
|
+
|
|
22
|
+
const R = require('./rules');
|
|
23
|
+
const A = require('../access/rules');
|
|
24
|
+
|
|
25
|
+
const VISIT_ACTIONS = Object.freeze({ start: 'customer.work_in_start', stop: 'customer.work_in_stop' });
|
|
26
|
+
const VISIT_ACTION_LABELS = Object.freeze({
|
|
27
|
+
[VISIT_ACTIONS.start]: 'Started working in a customer',
|
|
28
|
+
[VISIT_ACTIONS.stop]: 'Stopped working in a customer'
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
|
|
32
|
+
|
|
33
|
+
/** The start row's detail. `letIn` and `grant` from rules.entryLevels; `company` the home partner's name. */
|
|
34
|
+
function startDetail(rec, { letIn, grant, company }) {
|
|
35
|
+
const d = { customer: rec.customerId, visit: rec.id };
|
|
36
|
+
if (rec.managed) d.managed = true; else d.reason = rec.reason;
|
|
37
|
+
d.levels = { ...rec.levels };
|
|
38
|
+
d.level = R.levelOf(rec.levels);
|
|
39
|
+
d.until = iso(rec.until);
|
|
40
|
+
d.company = company == null ? null : String(company).slice(0, 200);
|
|
41
|
+
d.let_in = { ...letIn };
|
|
42
|
+
if (Object.values(letIn).includes('grant') && grant) {
|
|
43
|
+
d.grant = Number(grant.id);
|
|
44
|
+
d.let_in_by = grant.given_by_name || null;
|
|
45
|
+
}
|
|
46
|
+
if (Object.values(rec.levels).some((l) => R.LEVELS.includes(l) && A.rank(l) < A.rank(rec.asked))) d.asked = rec.asked;
|
|
47
|
+
if (rec.acting === true) d.acting_as_partner = rec.partnerId;
|
|
48
|
+
return d;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The stop row's detail. `rec` may be a record out of shape (ended `refused` because `record`): every value is taken
|
|
53
|
+
* only when it has its shape, else null.
|
|
54
|
+
*/
|
|
55
|
+
function stopDetail(rec, ended, because, nowMs) {
|
|
56
|
+
const r = rec && typeof rec === 'object' ? rec : {};
|
|
57
|
+
const levels = r.levels && typeof r.levels === 'object' && !Array.isArray(r.levels)
|
|
58
|
+
? Object.fromEntries(Object.entries(r.levels).filter(([, l]) => l === null || R.LEVELS.includes(l))) : null;
|
|
59
|
+
const d = {
|
|
60
|
+
customer: typeof r.customerId === 'string' && R.CUSTOMER_ID.test(r.customerId) ? r.customerId : null,
|
|
61
|
+
visit: typeof r.id === 'string' && R.VISIT_ID.test(r.id) ? r.id : null,
|
|
62
|
+
levels,
|
|
63
|
+
level: levels ? R.levelOf(levels) : null,
|
|
64
|
+
ended,
|
|
65
|
+
minutes: Number.isFinite(r.startedAt) ? R.minutesOf(r, nowMs) : null,
|
|
66
|
+
started_at: iso(r.startedAt)
|
|
67
|
+
};
|
|
68
|
+
if (ended === 'refused') d.because = because || null;
|
|
69
|
+
if (r.acting === true && Number.isSafeInteger(r.partnerId) && r.partnerId > 0) d.acting_as_partner = r.partnerId;
|
|
70
|
+
return d;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** What the app's audit helper adds to a row written inside a visit (CD-45). */
|
|
74
|
+
const stampFor = (facts) => (facts ? { working_in: facts.customerId, visit: facts.id } : null);
|
|
75
|
+
|
|
76
|
+
module.exports = { VISIT_ACTIONS, VISIT_ACTION_LABELS, startDetail, stopDetail, stampFor };
|