@aria-framework/tenancy 0.0.0-stage → 0.1.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 +73 -0
- package/README.md +911 -2
- package/index.js +19 -0
- package/lib/hosts/hostTenant.js +379 -0
- package/lib/hosts/hostname.js +321 -0
- package/lib/hosts/index.js +8 -0
- package/lib/hosts/tenantChrome.js +184 -0
- package/lib/partners/acting.js +216 -0
- package/lib/partners/index.js +8 -0
- package/lib/partners/provisioner.js +247 -0
- package/lib/partners/store.js +460 -0
- package/lib/scope/index.js +8 -0
- package/lib/scope/tenancy.js +776 -0
- package/lib/scope/writeGate.js +417 -0
- package/package.json +36 -4
- package/views/acting-banner.ejs +33 -0
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hostname handling for partner vanity hostnames — the two directions, kept apart.
|
|
3
|
+
*
|
|
4
|
+
* `normaliseHost` is for WRITES: an operator typing a hostname into the partner form. It is strict
|
|
5
|
+
* and it explains, because the cost of accepting something wrong is a partner whose visitors never
|
|
6
|
+
* reach them, with nothing in any log to say why.
|
|
7
|
+
*
|
|
8
|
+
* `hostFromHeader` is for READS: the `Host` header of an arriving request. It is forgiving of the
|
|
9
|
+
* things headers legitimately carry (a port, a trailing dot, mixed case) and forgiving of nothing
|
|
10
|
+
* else — it returns null rather than guessing, and a null host resolves to the installation's own
|
|
11
|
+
* front door, which answers as the House.
|
|
12
|
+
*
|
|
13
|
+
* THE TWO MUST AGREE. A stored host is compared against a header-derived one, so any normalisation
|
|
14
|
+
* one does and the other does not is a partner that can never be resolved — which looks exactly
|
|
15
|
+
* like a DNS problem and is not one. That is why both live here rather than at their call sites.
|
|
16
|
+
*
|
|
17
|
+
* NO DEPENDENCIES ON PURPOSE: models run in the database worker thread and the middleware runs on
|
|
18
|
+
* the main thread, and both need this. A pure module is also the only kind a guard can drive
|
|
19
|
+
* exhaustively without a database.
|
|
20
|
+
*
|
|
21
|
+
* MOVED from the apps' lib/hostname.js (the copy four apps share byte for byte), with the hub's
|
|
22
|
+
* reserved-label check (its list is now the caller's `reservedLabels`), `isHostLabel` and the
|
|
23
|
+
* `partner_base_domain` key name. The hub's own label helpers (what it sends each service) stay in
|
|
24
|
+
* the hub.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
'use strict';
|
|
28
|
+
|
|
29
|
+
/** RFC 1123 label: alphanumeric, may contain hyphens inside, 1–63 characters. */
|
|
30
|
+
const LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?';
|
|
31
|
+
const HOSTNAME_RE = new RegExp(`^${LABEL}(?:\\.${LABEL})+$`);
|
|
32
|
+
|
|
33
|
+
const MAX_HOSTNAME = 253;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Validate and canonicalise a hostname an operator typed.
|
|
37
|
+
*
|
|
38
|
+
* @param {string|null|undefined} raw
|
|
39
|
+
* @returns {string|null} the lower-cased hostname, or null for "no vanity host"
|
|
40
|
+
* @throws {Error} with a message written for the operator, naming what to do
|
|
41
|
+
*/
|
|
42
|
+
function normaliseHost(raw) {
|
|
43
|
+
// Empty CLEARS the field rather than failing. An operator removing a vanity host is an ordinary
|
|
44
|
+
// action, and it must not require a different control from setting one.
|
|
45
|
+
const trimmed = String(raw == null ? '' : raw).trim();
|
|
46
|
+
if (!trimmed) return null;
|
|
47
|
+
|
|
48
|
+
const lower = trimmed.toLowerCase().replace(/\.$/, ''); // a trailing dot is the DNS root
|
|
49
|
+
|
|
50
|
+
// REFUSE rather than repair, for each of these. Extracting the host from a pasted URL would be
|
|
51
|
+
// friendlier right up to the first time it guesses wrong about what the operator meant — and a
|
|
52
|
+
// wrong vanity host is silent, so the guess would not be corrected by anything.
|
|
53
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//.test(lower)) {
|
|
54
|
+
throw new Error('Enter a hostname only — no "https://". For example: support.acme.com');
|
|
55
|
+
}
|
|
56
|
+
if (lower.includes('/')) {
|
|
57
|
+
throw new Error('Enter a hostname only — no path. For example: support.acme.com');
|
|
58
|
+
}
|
|
59
|
+
if (lower.includes(':')) {
|
|
60
|
+
throw new Error('Enter a hostname only — no port. The port comes from how the site is served.');
|
|
61
|
+
}
|
|
62
|
+
if (lower.includes('*')) {
|
|
63
|
+
throw new Error('A wildcard cannot be a vanity host: each partner needs its own exact hostname.');
|
|
64
|
+
}
|
|
65
|
+
if (lower.includes('_')) {
|
|
66
|
+
throw new Error('Underscores are not valid in a hostname. Use hyphens: support-acme.example.com');
|
|
67
|
+
}
|
|
68
|
+
if (lower.length > MAX_HOSTNAME) {
|
|
69
|
+
throw new Error(`That hostname is ${lower.length} characters; the maximum is ${MAX_HOSTNAME}.`);
|
|
70
|
+
}
|
|
71
|
+
// At least two labels required. A single label ("acme") is not reachable as a public hostname and
|
|
72
|
+
// would collide with intranet search domains, so accepting one only defers the confusion.
|
|
73
|
+
if (!HOSTNAME_RE.test(lower)) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
'That is not a valid hostname. Use letters, digits and hyphens, with at least one dot — '
|
|
76
|
+
+ 'for example support.acme.com or acme.yourdomain.com.');
|
|
77
|
+
}
|
|
78
|
+
return lower;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The hostname a request arrived on, or null.
|
|
83
|
+
*
|
|
84
|
+
* Takes the header VALUE rather than the request, so a guard can drive it without building one.
|
|
85
|
+
* Port is stripped: `Host` carries it whenever the port is non-default, and a vanity host is
|
|
86
|
+
* stored without one.
|
|
87
|
+
*
|
|
88
|
+
* IPv6 literals return null. They arrive bracketed (`[::1]:3200`) and cannot be a vanity host, so
|
|
89
|
+
* the honest answer is "no partner host here" — which resolves to the installation's own address.
|
|
90
|
+
*
|
|
91
|
+
* @param {string|null|undefined} value the raw Host (or X-Forwarded-Host) value
|
|
92
|
+
* @returns {string|null}
|
|
93
|
+
*/
|
|
94
|
+
function hostFromHeader(value) {
|
|
95
|
+
const raw = String(value == null ? '' : value).trim();
|
|
96
|
+
if (!raw) return null;
|
|
97
|
+
if (raw.startsWith('[')) return null; // IPv6 literal
|
|
98
|
+
|
|
99
|
+
// A comma-separated list appears when more than one proxy has appended to X-Forwarded-Host, and
|
|
100
|
+
// only then: a plain `Host` header carrying a comma is malformed, and taking its first element is
|
|
101
|
+
// as good an answer as any for something that will not match a saved hostname regardless.
|
|
102
|
+
//
|
|
103
|
+
// THE FIRST ENTRY, because later ones are hops and letting an intermediary choose the tenant is
|
|
104
|
+
// the failure this is shaped against. Note the reasoning is borrowed from X-Forwarded-FOR, where
|
|
105
|
+
// a trusted proxy appends — see hostTenant.js beside this file for why that analogy does not by itself
|
|
106
|
+
// make the header trustworthy, and why honouring it at all is now opt-in.
|
|
107
|
+
const first = raw.split(',')[0].trim();
|
|
108
|
+
const withoutPort = first.replace(/:\d+$/, '');
|
|
109
|
+
const lower = withoutPort.toLowerCase().replace(/\.$/, '');
|
|
110
|
+
if (!lower || lower.length > MAX_HOSTNAME) return null;
|
|
111
|
+
// Deliberately the SAME pattern normaliseHost enforces, so a header can only ever match a host
|
|
112
|
+
// that the write path would have accepted. Anything else is not a vanity host by construction.
|
|
113
|
+
return HOSTNAME_RE.test(lower) ? lower : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ── DERIVING A PARTNER'S LABEL ─────────────────────────────────────────────────────────────────
|
|
117
|
+
//
|
|
118
|
+
// A partner's hostname is DERIVED, never typed. An operator (and later a self-service signup)
|
|
119
|
+
// supplies the partner's company domain, and the label is that domain flattened.
|
|
120
|
+
//
|
|
121
|
+
// WHY THE WHOLE DOMAIN AND NOT JUST THE NAME. `acme.com` becomes `acme-com`, not `acme`. That is
|
|
122
|
+
// less pretty and it is the part that does the work:
|
|
123
|
+
//
|
|
124
|
+
// * DOMAINS ARE ALREADY GLOBALLY UNIQUE, so a flattened domain is unique for free. There is no
|
|
125
|
+
// collision to arbitrate, no first-come advantage, and no tie-break to keep deterministic.
|
|
126
|
+
// * IT IS SELF-DOCUMENTING, which is the anti-impersonation property. `acme-co-za` is visibly
|
|
127
|
+
// not `acme-com`. A bare `acme` label is exactly what two unrelated companies called Acme
|
|
128
|
+
// would fight over, and whoever signed up first would hold it.
|
|
129
|
+
// * DETERMINISTIC. The same domain always yields the same label, so nothing depends on the order
|
|
130
|
+
// partners were created in.
|
|
131
|
+
//
|
|
132
|
+
// AND WHAT IT DOES NOT DO: it does not VERIFY the domain. Supplying a famous company's domain would
|
|
133
|
+
// yield its label. Derivation moves the claim from the label to the domain and checks neither. The
|
|
134
|
+
// gate is operator approval today — `partners.manage` is platform-only and there is no signup
|
|
135
|
+
// route — and must become a DNS TXT challenge on the day self-service onboarding ships.
|
|
136
|
+
|
|
137
|
+
const MAX_LABEL = 63;
|
|
138
|
+
|
|
139
|
+
/** Crockford base32, lower-cased: no i, l, o or u, so a label cannot be misread aloud. */
|
|
140
|
+
const RANDOM_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz';
|
|
141
|
+
const RANDOM_LENGTH = 10;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* A short, stable digest — used only to keep an over-long label unique, never as a secret.
|
|
145
|
+
*/
|
|
146
|
+
function shortHash(s) {
|
|
147
|
+
return require('crypto').createHash('sha256').update(s).digest('hex').slice(0, 6);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The CANONICAL form of a company domain — what gets stored.
|
|
152
|
+
*
|
|
153
|
+
* STORED CANONICAL, NOT AS TYPED, and a drive found out why. `www.Acme.CO.ZA` and `acme.co.za`
|
|
154
|
+
* derive the SAME hostname but are different strings, so with the raw input stored:
|
|
155
|
+
*
|
|
156
|
+
* * migration 048's `UNIQUE (lower(domain))` did not catch the second partner — the values
|
|
157
|
+
* genuinely differ — and only the portal_host index refused it, with a message about a
|
|
158
|
+
* hostname the operator never typed rather than about the domain they did;
|
|
159
|
+
* * the stored domain stopped being reliable evidence for the hostname beside it, which is one
|
|
160
|
+
* of the two reasons the column exists;
|
|
161
|
+
* * a future DNS TXT challenge would have had to re-apply this normalisation to know what to
|
|
162
|
+
* challenge, i.e. this function would have been needed anyway, one layer later.
|
|
163
|
+
*
|
|
164
|
+
* @param {string} domain e.g. 'acme.co.za', 'www.Acme.COM', 'bücher.example'
|
|
165
|
+
* @returns {string} the canonical ASCII domain, e.g. 'acme.co.za', 'xn--bcher-kva.example'
|
|
166
|
+
* @throws {Error} if the domain is not usable, with a message for the operator
|
|
167
|
+
*/
|
|
168
|
+
function normaliseDomain(domain) {
|
|
169
|
+
const trimmed = String(domain == null ? '' : domain).trim();
|
|
170
|
+
if (!trimmed) throw new Error('Enter the partner\'s company domain, for example acme.com.');
|
|
171
|
+
|
|
172
|
+
let lower = trimmed.toLowerCase().replace(/\.$/, '');
|
|
173
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//.test(lower)) {
|
|
174
|
+
throw new Error('Enter the domain only — no "https://". For example: acme.com');
|
|
175
|
+
}
|
|
176
|
+
if (lower.includes('/')) throw new Error('Enter the domain only — no path. For example: acme.com');
|
|
177
|
+
if (lower.includes('@')) {
|
|
178
|
+
throw new Error('Enter the domain, not an email address — the part after the @, e.g. acme.com');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// `www.` is how people write a domain, not part of it, and leaving it in would make
|
|
182
|
+
// `www-acme-com` and `acme-com` two different partners for one company.
|
|
183
|
+
lower = lower.replace(/^www\./, '');
|
|
184
|
+
|
|
185
|
+
// IDN → punycode via the platform's own UTS-46 implementation, so `bücher.example` becomes
|
|
186
|
+
// `xn--bcher-kva.example` and the label is ASCII. Hand-rolling this would be a second, wrong answer.
|
|
187
|
+
const ascii = require('url').domainToASCII(lower) || lower;
|
|
188
|
+
if (!HOSTNAME_RE.test(ascii)) {
|
|
189
|
+
throw new Error(
|
|
190
|
+
`"${trimmed}" is not a usable domain. Use the company's own domain with at least one dot, `
|
|
191
|
+
+ 'for example acme.com or acme.co.za.');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return ascii;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* The label for a partner whose company domain is `domain`.
|
|
199
|
+
*
|
|
200
|
+
* Built ON normaliseDomain rather than beside it, so the stored domain and the derived label can
|
|
201
|
+
* never disagree about what `www.Acme.CO.ZA` means.
|
|
202
|
+
*
|
|
203
|
+
* @returns {string} a single DNS label, e.g. 'acme-co-za'
|
|
204
|
+
*/
|
|
205
|
+
function labelFromDomain(domain) {
|
|
206
|
+
const ascii = normaliseDomain(domain);
|
|
207
|
+
const flat = ascii.replace(/\./g, '-');
|
|
208
|
+
if (flat.length <= MAX_LABEL) return flat;
|
|
209
|
+
|
|
210
|
+
// A DNS label caps at 63 characters, and a long domain can exceed it once flattened. Truncating
|
|
211
|
+
// alone would map two different domains to one label — the one thing this function must never do
|
|
212
|
+
// — so the digest of the FULL domain keeps it injective.
|
|
213
|
+
return `${flat.slice(0, MAX_LABEL - 7)}-${shortHash(ascii)}`;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* A label for a partner that supplied no domain.
|
|
218
|
+
*
|
|
219
|
+
* Opaque on purpose: a partner with nothing to derive from gets something that cannot be mistaken
|
|
220
|
+
* for a claim on anybody's name. It is a public hostname, not a secret, so the randomness is about
|
|
221
|
+
* collision avoidance rather than unguessability — the unique index is what actually enforces it.
|
|
222
|
+
*/
|
|
223
|
+
function randomLabel() {
|
|
224
|
+
const bytes = require('crypto').randomBytes(RANDOM_LENGTH);
|
|
225
|
+
let out = '';
|
|
226
|
+
for (let i = 0; i < RANDOM_LENGTH; i++) out += RANDOM_ALPHABET[bytes[i] % RANDOM_ALPHABET.length];
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ── LABELS NO PARTNER MAY HAVE ─────────────────────────────────────────────────────────────────
|
|
231
|
+
//
|
|
232
|
+
// An installation may run its own components under the partner base domain (the hub serves an
|
|
233
|
+
// image registry, a node surface and a package mirror as `<name>.<base>`, each a named proxy site
|
|
234
|
+
// that wins over the portal wildcard). A partner given one of those labels would either be
|
|
235
|
+
// unreachable or shadow the component. Neither generator can produce such a label today (a
|
|
236
|
+
// domain-derived label always holds a hyphen, an opaque one is 10 characters), so this is the rule
|
|
237
|
+
// written down before some later way of choosing a label exists.
|
|
238
|
+
//
|
|
239
|
+
// THE LIST IS THE CALLER'S AND IT IS REQUIRED. Apps differ (the hub reserves three names, the others
|
|
240
|
+
// none), so a caller that forgets the option gets an error here rather than another app's answer.
|
|
241
|
+
|
|
242
|
+
const LABEL_RE = new RegExp(`^${LABEL}$`);
|
|
243
|
+
|
|
244
|
+
/** Is `v` a single host label: a–z, 0–9, inner hyphens, 1–63 characters, lower case? */
|
|
245
|
+
const isHostLabel = (v) => typeof v === 'string' && v.length <= MAX_LABEL && LABEL_RE.test(v);
|
|
246
|
+
|
|
247
|
+
/** The installation setting the partner base domain is stored under. */
|
|
248
|
+
const PARTNER_BASE_DOMAIN_KEY = 'partner_base_domain';
|
|
249
|
+
|
|
250
|
+
function reservedFrom(options, fn) {
|
|
251
|
+
const list = options && options.reservedLabels;
|
|
252
|
+
if (!Array.isArray(list) || !list.every((l) => typeof l === 'string')) {
|
|
253
|
+
throw new TypeError(`${fn}: options.reservedLabels is required (an array of labels; [] when the installation reserves none)`);
|
|
254
|
+
}
|
|
255
|
+
return list.map((l) => l.toLowerCase());
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The one refusal for a reserved label: hostFor (create) and the partner edit route both go
|
|
260
|
+
* through it. Case-insensitive.
|
|
261
|
+
*
|
|
262
|
+
* @param {string} label
|
|
263
|
+
* @param {{reservedLabels: string[]}} options
|
|
264
|
+
*/
|
|
265
|
+
function assertLabelNotReserved(label, options) {
|
|
266
|
+
const reserved = reservedFrom(options, 'assertLabelNotReserved');
|
|
267
|
+
if (reserved.includes(String(label).toLowerCase())) {
|
|
268
|
+
throw new Error(`"${label}" is reserved for this installation's own components (${reserved.join(', ')}) and cannot be a partner's portal name.`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The edit route's free-text host: refused when it is `<reserved>.<base>`. A no-op without a base
|
|
274
|
+
* domain, for a host off the base, and for more than one label left of the base.
|
|
275
|
+
*
|
|
276
|
+
* @param {string} host
|
|
277
|
+
* @param {string} baseDomain
|
|
278
|
+
* @param {{reservedLabels: string[]}} options
|
|
279
|
+
*/
|
|
280
|
+
function refuseReservedHost(host, baseDomain, options) {
|
|
281
|
+
reservedFrom(options, 'refuseReservedHost');
|
|
282
|
+
const base = String(baseDomain == null ? '' : baseDomain).trim().toLowerCase().replace(/^\.|\.$/g, '');
|
|
283
|
+
const h = String(host == null ? '' : host).trim().toLowerCase();
|
|
284
|
+
if (!base || !h.endsWith(`.${base}`)) return;
|
|
285
|
+
const label = h.slice(0, -(base.length + 1));
|
|
286
|
+
if (!label.includes('.')) assertLabelNotReserved(label, options);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Compose a label and the installation's base domain into a hostname.
|
|
291
|
+
*
|
|
292
|
+
* Validated through normaliseHost, so a bad base domain fails HERE — at partner creation, where an
|
|
293
|
+
* operator can read why — rather than producing a hostname that quietly resolves for nobody.
|
|
294
|
+
*
|
|
295
|
+
* The label must be ONE label (compared in lower case, as normaliseHost folds it) and not a
|
|
296
|
+
* reserved one. Both generators (labelFromDomain, randomLabel) only ever produce one.
|
|
297
|
+
*
|
|
298
|
+
* @param {string} label
|
|
299
|
+
* @param {string} baseDomain
|
|
300
|
+
* @param {{reservedLabels: string[]}} options
|
|
301
|
+
*/
|
|
302
|
+
function hostFor(label, baseDomain, options) {
|
|
303
|
+
reservedFrom(options, 'hostFor');
|
|
304
|
+
const base = String(baseDomain == null ? '' : baseDomain).trim().toLowerCase().replace(/^\.|\.$/g, '');
|
|
305
|
+
if (!base) {
|
|
306
|
+
throw new Error(
|
|
307
|
+
'No partner base domain is set, so a hostname cannot be derived. Set it on the Partners '
|
|
308
|
+
+ 'screen before creating a partner.');
|
|
309
|
+
}
|
|
310
|
+
assertLabelNotReserved(label, options);
|
|
311
|
+
if (!isHostLabel(String(label == null ? '' : label).toLowerCase())) {
|
|
312
|
+
throw new Error(`"${label}" is not a single host label (letters, digits and inner hyphens, at most ${MAX_LABEL} characters).`);
|
|
313
|
+
}
|
|
314
|
+
return normaliseHost(`${label}.${base}`);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
module.exports = {
|
|
318
|
+
normaliseHost, hostFromHeader, normaliseDomain, labelFromDomain, randomLabel, hostFor,
|
|
319
|
+
assertLabelNotReserved, refuseReservedHost, isHostLabel, PARTNER_BASE_DOMAIN_KEY,
|
|
320
|
+
MAX_HOSTNAME, MAX_LABEL
|
|
321
|
+
};
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tenant-dependent view settings, resolved PER TENANT and cached.
|
|
3
|
+
*
|
|
4
|
+
* MOVED from the apps' lib/tenantChrome.js (the copy five apps share byte for byte), generalised to
|
|
5
|
+
* a list of fields (the desk app also resolves its brand and date style), with the desk app's
|
|
6
|
+
* synchronous cache-only read (`brandNow`, here `cached(field, fallback)`):
|
|
7
|
+
*
|
|
8
|
+
* createTenantChrome({ tenancy, db, fields })
|
|
9
|
+
* → { chromeFor(partnerId), forget([partnerId]), cachedSessionTimeoutMs(partnerId), cached(field, fallback) }
|
|
10
|
+
*
|
|
11
|
+
* ── THE DEFECT THIS EXISTS FOR ────────────────────────────────────────────────────────────────
|
|
12
|
+
*
|
|
13
|
+
* `settings` is tenant-scoped, so `display_timezone` and `session_timeout_minutes` are a partner's
|
|
14
|
+
* own. Both were read from a PROCESS-WIDE cache on the app's db client, set once at boot from
|
|
15
|
+
* whichever tenant was current then — the House:
|
|
16
|
+
*
|
|
17
|
+
* the layout `getDisplayTimezone()` — so every partner's console rendered timestamps in the
|
|
18
|
+
* House's zone, and a partner who set their own watched it be ignored.
|
|
19
|
+
* the idle gate `getSessionTimeoutMs()` is called with no arguments and must answer
|
|
20
|
+
* synchronously, so it could only ever hold ONE tenant's number. A partner setting
|
|
21
|
+
* five minutes would log out the House's operators and every other partner's staff
|
|
22
|
+
* after five minutes.
|
|
23
|
+
*
|
|
24
|
+
* Neither is a query that looks wrong. The value had LEFT the settings layer at boot, so a guard
|
|
25
|
+
* watching that layer is blind to it — which is why this module exists rather than a second call
|
|
26
|
+
* to `Settings`.
|
|
27
|
+
*
|
|
28
|
+
* ── WHY IT IS CACHED, AND WHAT INVALIDATES IT ──────────────────────────────────────────────────
|
|
29
|
+
*
|
|
30
|
+
* This is on the path of EVERY rendered request, which is exactly why the process-wide cache
|
|
31
|
+
* existed in the first place — the instinct was right and only the granularity was wrong. So: the
|
|
32
|
+
* same trade, per tenant. One read per partner per process, dropped when that partner saves its
|
|
33
|
+
* settings and when a partner is created or re-provisioned.
|
|
34
|
+
*
|
|
35
|
+
* Bounded by the number of PARTNERS rather than by anything a caller controls — the same reasoning
|
|
36
|
+
* the host map gives for caching the whole map instead of each host.
|
|
37
|
+
*
|
|
38
|
+
* ── THE KEY ────────────────────────────────────────────────────────────────────────────────────
|
|
39
|
+
*
|
|
40
|
+
* db-worker's tenantCacheKey, for the PARTNER scope of the id: every entry is read inside
|
|
41
|
+
* asPartner(id), so what is stored is always that one partner's own values, and 'p:<id>' is the
|
|
42
|
+
* honest key whatever scope the caller is in (a platform-scope request for the house asks for the
|
|
43
|
+
* house's chrome, as the apps do today). There is no platform entry: chromeFor(null) is never
|
|
44
|
+
* cached and answers the fallbacks.
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
'use strict';
|
|
48
|
+
|
|
49
|
+
const { tenantCacheKey } = require('@aria-framework/db-worker');
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The starter's two fields: what five apps resolve today, and what they pass as `fields`. `read`
|
|
53
|
+
* turns the Settings getter's answer into the cached value; `fallback` is the answer with no tenant.
|
|
54
|
+
*/
|
|
55
|
+
const STARTER_FIELDS = Object.freeze({
|
|
56
|
+
displayTimezone: Object.freeze({ method: 'getDisplayTimezone', fallback: 'UTC', read: (v) => v || 'UTC' }),
|
|
57
|
+
sessionTimeoutMs: Object.freeze({
|
|
58
|
+
method: 'getSessionTimeoutMinutes', fallback: 480 * 60 * 1000, read: (v) => (v || 480) * 60 * 1000
|
|
59
|
+
})
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @param {object} o
|
|
64
|
+
* @param {{asPartner: Function, currentTenant: Function}} o.tenancy
|
|
65
|
+
* @param {{invoke: Function}} o.db the app's DbClient (reads `Settings.<method>`)
|
|
66
|
+
* @param {Object<string, {method: string, fallback: *, read?: (raw: *) => *}>} o.fields
|
|
67
|
+
* REQUIRED, and must include `sessionTimeoutMs`: five apps pass STARTER_FIELDS, the desk its
|
|
68
|
+
* four. A field without `read` caches the getter's answer as it comes back.
|
|
69
|
+
*/
|
|
70
|
+
function createTenantChrome(o = {}) {
|
|
71
|
+
const { tenancy, db } = o;
|
|
72
|
+
if (!tenancy || typeof tenancy.asPartner !== 'function' || typeof tenancy.currentTenant !== 'function') {
|
|
73
|
+
throw new TypeError('createTenantChrome: tenancy must be the app\'s createTenancy() result (asPartner, currentTenant)');
|
|
74
|
+
}
|
|
75
|
+
if (!db || typeof db.invoke !== 'function') throw new TypeError('createTenantChrome: db must be the app\'s DbClient (invoke)');
|
|
76
|
+
// REQUIRED, NO DEFAULT: apps differ (the desk also resolves its brand and date style), and a default
|
|
77
|
+
// would serve such an app's neutral brand to every partner, silently.
|
|
78
|
+
const { fields } = o;
|
|
79
|
+
if (!fields || typeof fields !== 'object') {
|
|
80
|
+
throw new TypeError('createTenantChrome: fields is required (createTenantChrome.STARTER_FIELDS, or the app\'s own list)');
|
|
81
|
+
}
|
|
82
|
+
const names = Object.keys(fields);
|
|
83
|
+
// sessionTimeoutMs is read by every app's idle gate and live-update check through
|
|
84
|
+
// cachedSessionTimeoutMs, so a list without it is refused rather than answering undefined.
|
|
85
|
+
if (!names.includes('sessionTimeoutMs')) {
|
|
86
|
+
throw new TypeError('createTenantChrome: fields must include sessionTimeoutMs (the idle gate and the live-update check read it)');
|
|
87
|
+
}
|
|
88
|
+
for (const n of names) {
|
|
89
|
+
const f = fields[n];
|
|
90
|
+
if (!f || typeof f.method !== 'string' || !f.method) throw new TypeError(`createTenantChrome: fields.${n}.method must name a Settings getter`);
|
|
91
|
+
if (f.read !== undefined && typeof f.read !== 'function') throw new TypeError(`createTenantChrome: fields.${n}.read must be a function`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** tenantCacheKey({scope: 'partner', partnerId}) → { <field>: value } */
|
|
95
|
+
const _cache = new Map();
|
|
96
|
+
const keyOf = (id) => tenantCacheKey({ scope: 'partner', partnerId: id });
|
|
97
|
+
|
|
98
|
+
const fallbacks = () => {
|
|
99
|
+
const out = {};
|
|
100
|
+
for (const n of names) out[n] = fields[n].fallback;
|
|
101
|
+
return out;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Drop one partner's chrome, or everything.
|
|
106
|
+
*
|
|
107
|
+
* Missing this call does not break a page — it serves a stale value until the next restart, which
|
|
108
|
+
* reads as "I changed the setting and nothing happened" and sends an operator looking in the wrong
|
|
109
|
+
* place entirely.
|
|
110
|
+
*/
|
|
111
|
+
function forget(partnerId = null) {
|
|
112
|
+
if (partnerId == null) _cache.clear();
|
|
113
|
+
else _cache.delete(keyOf(Number(partnerId)));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* @param {number|null} partnerId
|
|
118
|
+
* @returns {Promise<object>} one value per field
|
|
119
|
+
*/
|
|
120
|
+
async function chromeFor(partnerId) {
|
|
121
|
+
const id = partnerId == null ? null : Number(partnerId);
|
|
122
|
+
if (id == null) {
|
|
123
|
+
// No tenant at all. Only reachable before the request-scope middleware has run, or on a path
|
|
124
|
+
// that never gets one; the fallbacks are the honest answer and cost nothing.
|
|
125
|
+
return fallbacks();
|
|
126
|
+
}
|
|
127
|
+
const key = keyOf(id);
|
|
128
|
+
if (_cache.has(key)) return _cache.get(key);
|
|
129
|
+
|
|
130
|
+
// IN THE PARTNER'S OWN SCOPE. `settings` is tenant-scoped, so reading it in whatever scope the
|
|
131
|
+
// request happens to carry is the whole bug this replaces: at platform scope the natural-key read
|
|
132
|
+
// crosses tenants, and at house scope a partner finds the House's row.
|
|
133
|
+
const chrome = await tenancy.asPartner(id, async () => {
|
|
134
|
+
const out = {};
|
|
135
|
+
for (const n of names) {
|
|
136
|
+
const raw = await db.invoke('Settings', fields[n].method);
|
|
137
|
+
out[n] = fields[n].read ? fields[n].read(raw) : raw;
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
});
|
|
141
|
+
_cache.set(key, chrome);
|
|
142
|
+
return chrome;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The cached idle timeout for a tenant, SYNCHRONOUSLY, or null if not yet loaded.
|
|
147
|
+
*
|
|
148
|
+
* The auth package calls `getSessionTimeoutMs()` with no arguments and expects a synchronous
|
|
149
|
+
* number, so the app's auth middleware cannot read res.locals or await anything. It reads the
|
|
150
|
+
* current tenant from the AsyncLocalStorage context instead and looks the answer up here — which
|
|
151
|
+
* is warm in practice, because the app resolves this tenant's chrome before any router runs.
|
|
152
|
+
*
|
|
153
|
+
* Returns null rather than a default so the CALLER decides: a miss must fall back to the
|
|
154
|
+
* installation default, never to some other tenant's number.
|
|
155
|
+
*/
|
|
156
|
+
function cachedSessionTimeoutMs(partnerId) {
|
|
157
|
+
if (partnerId == null) return null;
|
|
158
|
+
const hit = _cache.get(keyOf(Number(partnerId)));
|
|
159
|
+
return hit && hit.sessionTimeoutMs != null ? hit.sessionTimeoutMs : null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The CURRENT tenant's cached `field`, SYNCHRONOUSLY and best-effort, for callers that cannot
|
|
164
|
+
* await (push titles, report headers, a template's brand inside a background job).
|
|
165
|
+
*
|
|
166
|
+
* Falls back to `fallback` — which should be NEUTRAL, never another tenant's value: a missing
|
|
167
|
+
* cache entry must not be an excuse to brand one tenant as another.
|
|
168
|
+
*/
|
|
169
|
+
function cached(field, fallback) {
|
|
170
|
+
try {
|
|
171
|
+
const t = tenancy.currentTenant();
|
|
172
|
+
const hit = t && t.partnerId != null ? _cache.get(keyOf(Number(t.partnerId))) : null;
|
|
173
|
+
return (hit && hit[field]) || fallback;
|
|
174
|
+
} catch (_) {
|
|
175
|
+
return fallback;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return { chromeFor, forget, cachedSessionTimeoutMs, cached };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
createTenantChrome.STARTER_FIELDS = STARTER_FIELDS;
|
|
183
|
+
|
|
184
|
+
module.exports = { createTenantChrome };
|