@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,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Working inside a partner: the act-as and stop routes, the locals the banner reads, and where the banner lives.
|
|
3
|
+
*
|
|
4
|
+
* router.use(actingRoutes({ Router: express.Router, tenancy, db, audit, requirePermission,
|
|
5
|
+
* permission: 'partners.manage', landing: '/', refuseInactive: true })); // BEFORE any /:id route
|
|
6
|
+
* app.use(actingLocals({ tenancy, readOnly: false }));
|
|
7
|
+
* app.set('views', [..., viewsDir]); then <%- include('acting-banner') %>
|
|
8
|
+
*
|
|
9
|
+
* A platform operator can READ every tenant (the policy's platform arm is `true`) and cannot WRITE into one, because
|
|
10
|
+
* every scoped table defaults partner_id to the operator's own partner, the house. This is the switch that lets them
|
|
11
|
+
* work there, and it is deliberately EXPLICIT: they say which tenant, and everything they do lands there until they say
|
|
12
|
+
* otherwise. IT NARROWS, IT NEVER WIDENS: while acting the scope is 'partner', so every platform-only permission is
|
|
13
|
+
* refused. The scope code (`contextFor`) re-checks at the point of use that only a platform user can be acting.
|
|
14
|
+
*
|
|
15
|
+
* Moved from the starter's two handlers and its banner block. No permission name lives here (`permission` is the
|
|
16
|
+
* app's), and whether a deactivated partner may be entered is the app's `refuseInactive`.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
'use strict';
|
|
20
|
+
|
|
21
|
+
const path = require('path');
|
|
22
|
+
|
|
23
|
+
function fail(message) { throw new Error(`actingRoutes: ${message}`); }
|
|
24
|
+
|
|
25
|
+
/** A local path only ("/x", never "//host" or "/\\host" or "http:"), or the redirect is an open one. */
|
|
26
|
+
function isLocalPath(p) {
|
|
27
|
+
return typeof p === 'string' && /^\/(?![/\\])/.test(p) && !/[\r\n]/.test(p);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const DEFAULT_MESSAGES = {
|
|
31
|
+
house: 'The House is the platform view — you are already in it.',
|
|
32
|
+
inactive: (name) => `"${name}" is deactivated. Reactivate it before working in it.`,
|
|
33
|
+
started: (name) => `You are now working inside "${name}". Everything you create lands there, and `
|
|
34
|
+
+ 'platform-only settings are unavailable until you stop.',
|
|
35
|
+
notActing: 'You were not working inside a partner.',
|
|
36
|
+
stopped: 'Back to the platform view.',
|
|
37
|
+
// Absent: an unknown partner id answers the app's 404 page, as the starter does. A string: it is flashed instead.
|
|
38
|
+
unknown: null
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const text = (m, ...a) => (typeof m === 'function' ? m(...a) : m);
|
|
42
|
+
|
|
43
|
+
function actingRoutes(options) {
|
|
44
|
+
const o = options || {};
|
|
45
|
+
if (typeof o.Router !== 'function') fail('Router is required (express.Router): this package does not load express itself');
|
|
46
|
+
if (!o.tenancy || typeof o.tenancy.contextFor !== 'function') fail('tenancy is required');
|
|
47
|
+
if (!o.db || typeof o.db.invoke !== 'function') fail('db is required (the app\'s db client)');
|
|
48
|
+
if (typeof o.audit !== 'function') fail('audit is required: (req, action, opts), the app\'s staff audit helper');
|
|
49
|
+
if (typeof o.requirePermission !== 'function') fail('requirePermission is required (the app\'s gate)');
|
|
50
|
+
if (typeof o.permission !== 'string' || !o.permission) fail('permission is required: the name of the app\'s partner-management permission');
|
|
51
|
+
if (!isLocalPath(o.landing)) fail('landing is required: a local path ("/" or "/dashboard") where the browser goes after a switch');
|
|
52
|
+
// NO DEFAULT: the apps answer this differently today, and an app that forgot must not silently get another's rule.
|
|
53
|
+
if (typeof o.refuseInactive !== 'boolean') fail('refuseInactive is required (true or false): may a house operator act inside a deactivated partner?');
|
|
54
|
+
if (o.back != null && !isLocalPath(o.back)) fail('back must be a local path');
|
|
55
|
+
if (o.flash != null && typeof o.flash !== 'function') fail('flash must be a function (req, res, type, message), which may return a promise');
|
|
56
|
+
if (o.notFound != null && typeof o.notFound !== 'function') fail('notFound must be a function (req, res)');
|
|
57
|
+
const messages = { ...DEFAULT_MESSAGES, ...(o.messages || {}) };
|
|
58
|
+
// WHERE THE TWO ROWS LAND (the owner's decision of 29 Nov 2026: the stop entry goes into both logs). REQUIRED, no
|
|
59
|
+
// default, so every existing app stays as it is until its own adoption: each passes { start: 'house', stop: 'partner' },
|
|
60
|
+
// what all six do today (the start row is written before the switch, in the operator's own scope; the stop row after
|
|
61
|
+
// the switch back, but still in the REQUEST's context, which the scope middleware fixed at the acting partner).
|
|
62
|
+
// start: 'house' | 'both' stop: 'partner' | 'house' | 'both'
|
|
63
|
+
// 'house' is the operator's own scope (contextFor once the acting keys are absent), 'partner' the partner acted in,
|
|
64
|
+
// 'both' one row in each: the same action and detail, built by the app's audit from the same request.
|
|
65
|
+
const sc = o.auditScopes;
|
|
66
|
+
if (!sc || typeof sc !== 'object' || !['house', 'both'].includes(sc.start) || !['partner', 'house', 'both'].includes(sc.stop)) {
|
|
67
|
+
fail("auditScopes is required, with no default: { start: 'house' | 'both', stop: 'partner' | 'house' | 'both' } (every existing app: { start: 'house', stop: 'partner' })");
|
|
68
|
+
}
|
|
69
|
+
if ((sc.start === 'both' || sc.stop !== 'partner') && typeof o.tenancy.run !== 'function') fail('tenancy.run is required for these auditScopes (the rows written in an explicit scope)');
|
|
70
|
+
if ((sc.start === 'both' || sc.stop === 'both') && (!o.logger || typeof o.logger.error !== 'function')) {
|
|
71
|
+
fail("logger is required (error) when an auditScopes value is 'both': the ADDED row's failure is logged, never thrown");
|
|
72
|
+
}
|
|
73
|
+
const { db, audit, landing, refuseInactive } = o;
|
|
74
|
+
/**
|
|
75
|
+
* The ADDED row of a 'both': written in `ctx`, and isolated: a throw or a rejection is logged at error and changes
|
|
76
|
+
* nothing else (no switch undone, no request failed). The row today's code writes keeps today's behaviour.
|
|
77
|
+
*/
|
|
78
|
+
const addedRow = (ctx, req, action, opts) => {
|
|
79
|
+
const failed = (e) => { try { o.logger.error(`acting: the added "${action}" audit row (${ctx.scope} ${ctx.partnerId}) could not be written: ${(e && e.message) || e}`); } catch (_) { /* nothing more to do */ } };
|
|
80
|
+
try {
|
|
81
|
+
const r = o.tenancy.run(ctx, () => audit(req, action, opts));
|
|
82
|
+
if (r && typeof r.then === 'function') r.then(null, failed);
|
|
83
|
+
} catch (e) { failed(e); }
|
|
84
|
+
};
|
|
85
|
+
const partnerCtx = (id) => ({ scope: 'partner', partnerId: Number(id) });
|
|
86
|
+
const partnerModel = o.partnerModel || 'Partner';
|
|
87
|
+
// `back` when the app sets it; else the mount (`req.baseUrl`), CHECKED AT REQUEST TIME like every other redirect
|
|
88
|
+
// here (a mount the app did not mean, or none, is not trusted); else `landing`.
|
|
89
|
+
const backTo = (req) => o.back || (isLocalPath(req.baseUrl) ? req.baseUrl : landing);
|
|
90
|
+
// The 404 answer: by default the app's 'errors/404' view (which the app must have), or the app's own `notFound`.
|
|
91
|
+
const notFound = (req, res) => (o.notFound ? o.notFound(req, res) : res.status(404).render('errors/404', { title: 'Not found' }));
|
|
92
|
+
// A flash, then `then()`: by default the app's `res.flash(type, message, callback)` (connect-flash style WITH a
|
|
93
|
+
// callback; another shape answers a 500), or the app's own `flash(req, res, type, message)`, which may return a promise.
|
|
94
|
+
const flashThen = (req, res, next, type, message, then) => {
|
|
95
|
+
if (!o.flash) return res.flash(type, message, then);
|
|
96
|
+
let r;
|
|
97
|
+
try { r = o.flash(req, res, type, message); } catch (e) { return next(e); }
|
|
98
|
+
return Promise.resolve(r).then(() => then(), next);
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const router = o.Router();
|
|
102
|
+
// A non-digit id is not this route's (the starter's numericParam): it falls through to the app's own routes or its
|
|
103
|
+
// 404, BEFORE the permission gate runs, rather than reaching Number().
|
|
104
|
+
router.param('id', (req, res, next, value) => (/^[0-9]+$/.test(String(value)) ? next() : next('route')));
|
|
105
|
+
|
|
106
|
+
// ── DECLARED BEFORE EVERY '/:id' ROUTE, AND THAT IS LOAD-BEARING ───────────────────────────────────────────────────
|
|
107
|
+
// Express matches in declaration order, so the app mounts this router before its own `/:id` routes. A param guard's
|
|
108
|
+
// fall-through for a non-numeric id would happen to make it work anyway; depending on that is a coincidence, not a
|
|
109
|
+
// design (an endpoint once never reached its handler that way and Express answered 404 with no log and no audit).
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Stop working inside a partner.
|
|
113
|
+
*
|
|
114
|
+
* NOT BEHIND THE PERMISSION, deliberately: while acting the operator's scope is 'partner', and every platform-only
|
|
115
|
+
* permission, the partner-management one included, is refused. Gating the way OUT on a permission the act of acting
|
|
116
|
+
* removes would strand them. So the check is the fact acting does not change: is the signed-in user platform staff?
|
|
117
|
+
*/
|
|
118
|
+
router.post('/stop-acting', (req, res, next) => {
|
|
119
|
+
const u = req.session && req.session.user;
|
|
120
|
+
// A partner-scoped user has nothing to stop, and should not learn that the mechanism exists.
|
|
121
|
+
if (!u || u.scope_kind !== 'platform') return notFound(req, res);
|
|
122
|
+
const was = req.session.actingPartnerId;
|
|
123
|
+
if (was == null) return flashThen(req, res, next, 'error', text(messages.notActing), () => res.redirect(landing));
|
|
124
|
+
delete req.session.actingPartnerId;
|
|
125
|
+
delete req.session.actingPartnerName;
|
|
126
|
+
req.session.save((err) => {
|
|
127
|
+
// next(err), NOT throw: this callback runs after the handler returned, so a throw here is an uncaught
|
|
128
|
+
// exception, and a session-store blip would take the process down instead of rendering an error page.
|
|
129
|
+
if (err) return next(err);
|
|
130
|
+
// Audited AFTER the switch back, the mirror of act-as: this row belongs in the operator's own scope, next to the
|
|
131
|
+
// one that opened the session.
|
|
132
|
+
const stopOpts = { entity_type: 'partner', entity_id: Number(was) };
|
|
133
|
+
if (sc.stop === 'house') {
|
|
134
|
+
// The one row, in the operator's own scope (the keys are gone, so contextFor answers it), not the request's.
|
|
135
|
+
o.tenancy.run(o.tenancy.contextFor(req), () => audit(req, 'partner.act_as_stop', stopOpts));
|
|
136
|
+
} else {
|
|
137
|
+
audit(req, 'partner.act_as_stop', stopOpts); // today's row: in the request's context, the partner acted in
|
|
138
|
+
if (sc.stop === 'both') addedRow(o.tenancy.contextFor(req), req, 'partner.act_as_stop', stopOpts);
|
|
139
|
+
}
|
|
140
|
+
return flashThen(req, res, next, 'success', text(messages.stopped), () => res.redirect(backTo(req)));
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
/** Work inside a partner. */
|
|
145
|
+
router.post('/:id/act-as', o.requirePermission(o.permission), (req, res, next) => {
|
|
146
|
+
(async () => {
|
|
147
|
+
const id = Number(req.params.id);
|
|
148
|
+
const partner = await db.invoke(partnerModel, 'byId', id);
|
|
149
|
+
if (!partner) {
|
|
150
|
+
if (messages.unknown) return flashThen(req, res, next, 'error', text(messages.unknown), () => res.redirect(backTo(req)));
|
|
151
|
+
return notFound(req, res);
|
|
152
|
+
}
|
|
153
|
+
if (Number(partner.is_house) === 1) {
|
|
154
|
+
return flashThen(req, res, next, 'error', text(messages.house), () => res.redirect(backTo(req)));
|
|
155
|
+
}
|
|
156
|
+
if (refuseInactive && !Number(partner.is_active)) {
|
|
157
|
+
return flashThen(req, res, next, 'error', text(messages.inactive, partner.name), () => res.redirect(backTo(req)));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// AUDITED BEFORE THE SWITCH, so the row lands in the operator's OWN scope (the house) where a platform reader
|
|
161
|
+
// will find it. Written after the switch it would land in the acted-upon tenant, the one place somebody auditing
|
|
162
|
+
// the operator would not think to look.
|
|
163
|
+
const startOpts = { entity_type: 'partner', entity_id: id, detail: { name: partner.name } };
|
|
164
|
+
// Today's row, in the request's context: before the switch that IS the operator's own scope. A throw here stops the
|
|
165
|
+
// switch, as in the source.
|
|
166
|
+
audit(req, 'partner.act_as_start', startOpts);
|
|
167
|
+
if (sc.start === 'both') addedRow(partnerCtx(id), req, 'partner.act_as_start', startOpts);
|
|
168
|
+
|
|
169
|
+
req.session.actingPartnerId = id;
|
|
170
|
+
req.session.actingPartnerName = partner.name;
|
|
171
|
+
return req.session.save((err) => {
|
|
172
|
+
if (err) return next(err); // next(err), NOT throw: see stop-acting
|
|
173
|
+
return flashThen(req, res, next, 'success', text(messages.started, partner.name), () => res.redirect(landing));
|
|
174
|
+
});
|
|
175
|
+
})().catch(next);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
return router;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The locals the banner reads, on every page: `actingPartnerName` and `actingReadOnly`.
|
|
183
|
+
*
|
|
184
|
+
* THE BANNER DOES NOT TRUST THE SESSION'S STORED NAME ALONE. It is shown only when the request's scope has actually
|
|
185
|
+
* moved to that partner, asked of `tenancy.contextFor(req)`: a partner-scoped user with a stray acting flag (which the
|
|
186
|
+
* scope code ignores) would otherwise see "working inside P" while working in their own tenant. The name itself is the
|
|
187
|
+
* one the act-as route stored.
|
|
188
|
+
*
|
|
189
|
+
* `readOnly` is the app's write rule while acting (its write gate's `whileActing: 'readOnly'`), as a plain boolean:
|
|
190
|
+
* `actingReadOnly` is true only while the scope has moved. `note` replaces the banner's second sentence.
|
|
191
|
+
*/
|
|
192
|
+
function actingLocals(options) {
|
|
193
|
+
const o = options || {};
|
|
194
|
+
if (!o.tenancy || typeof o.tenancy.contextFor !== 'function') throw new Error('actingLocals: tenancy is required');
|
|
195
|
+
if (typeof o.readOnly !== 'boolean') throw new Error('actingLocals: readOnly is required (true or false): is acting read-only in this app?');
|
|
196
|
+
if (o.stopPath != null && !isLocalPath(o.stopPath)) throw new Error('actingLocals: stopPath must be a local path');
|
|
197
|
+
const stopPath = o.stopPath || '/admin/partners/stop-acting';
|
|
198
|
+
const note = o.note || null;
|
|
199
|
+
return function actingLocalsMw(req, res, next) {
|
|
200
|
+
const s = req.session;
|
|
201
|
+
const u = s && s.user;
|
|
202
|
+
let moved = false;
|
|
203
|
+
if (u && s.actingPartnerId != null) {
|
|
204
|
+
const ctx = o.tenancy.contextFor(req);
|
|
205
|
+
moved = !!ctx && ctx.scope === 'partner' && Number(ctx.partnerId) === Number(s.actingPartnerId)
|
|
206
|
+
&& Number(ctx.partnerId) !== Number(u.partner_id);
|
|
207
|
+
}
|
|
208
|
+
res.locals.actingPartnerName = moved ? (s.actingPartnerName || `partner ${Number(s.actingPartnerId)}`) : null;
|
|
209
|
+
res.locals.actingReadOnly = moved && o.readOnly;
|
|
210
|
+
res.locals.actingStopPath = stopPath;
|
|
211
|
+
res.locals.actingNote = note;
|
|
212
|
+
next();
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
module.exports = { actingRoutes, actingLocals, viewsDir: path.join(__dirname, '..', '..', 'views') };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The partners part: the partner store and provisioning (piece 10); the acting routes, locals and banner (piece 11).
|
|
4
|
+
const { createPartnerStore } = require('./store');
|
|
5
|
+
const { createProvisioner } = require('./provisioner');
|
|
6
|
+
const { actingRoutes, actingLocals, viewsDir } = require('./acting');
|
|
7
|
+
|
|
8
|
+
module.exports = { createPartnerStore, createProvisioner, actingRoutes, actingLocals, viewsDir };
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createProvisioner — creating a partner, and giving it the things it cannot work without.
|
|
3
|
+
*
|
|
4
|
+
* const { createPartner, provision } = createProvisioner({ tenancy, db, rbac, logger, seeds, deactivateWith,
|
|
5
|
+
* onPartnersChanged, writesRequirePlatform });
|
|
6
|
+
*
|
|
7
|
+
* ── WHY THIS IS NOT IN THE PARTNER STORE ────────────────────────────────────────────────────────────────────────────
|
|
8
|
+
*
|
|
9
|
+
* A partner row on its own is a tenant that cannot be used: its roles, templates and the rest are partner-scoped, and a
|
|
10
|
+
* partner with no RBAC cache grants nothing. Every one of them has to be written INSIDE the new partner's scope, and
|
|
11
|
+
* that is the seam: models run in the DB worker and receive their tenant IN THE MESSAGE, so a model cannot switch
|
|
12
|
+
* tenants mid-call. `asPartner()` lives on the main thread, so the orchestration lives here, next to it.
|
|
13
|
+
*
|
|
14
|
+
* ── IT IS NOT ATOMIC, AND IT SAYS SO ────────────────────────────────────────────────────────────────────────────────
|
|
15
|
+
*
|
|
16
|
+
* The row and its seeds are separate worker round-trips. If seeding fails, the partner is left DEACTIVATED and the
|
|
17
|
+
* error reported: a half-built tenant nobody can sign into is recoverable; one that ACCEPTS logins is a support call
|
|
18
|
+
* about pages that refuse for no visible reason. Each seed is idempotent, so `provision()` can be re-run (a
|
|
19
|
+
* Re-provision action), rather than inviting somebody to create a second partner and hope. A seed that checks "is my
|
|
20
|
+
* table empty for this partner" does nothing for a fully seeded partner that predates a seed added later: that is a
|
|
21
|
+
* separate backfill, not this.
|
|
22
|
+
*
|
|
23
|
+
* ── WHAT CHANGED IN THE MOVE ────────────────────────────────────────────────────────────────────────────────────────
|
|
24
|
+
*
|
|
25
|
+
* - The seeds are the app's list (`seeds: [{ name, run }]`), each run inside the partner's scope, each result
|
|
26
|
+
* checked: a seed that returns nothing is an error, never "none", and `ctx.rows()` refuses a read that is not an
|
|
27
|
+
* array (an empty array has to mean empty: a mistyped method read as "none" re-seeds on every run).
|
|
28
|
+
* - RBAC is refreshed after EVERY provision, the re-provision route's included: a role seeded into a partner the cache
|
|
29
|
+
* does not know about grants nothing until the next restart.
|
|
30
|
+
* - The thrown error carries `partnerId`.
|
|
31
|
+
* - A failed deactivation of a half-built partner is LOGGED AT ERROR, and the messages stop claiming the partner was
|
|
32
|
+
* deactivated. Every copy swallowed it (`.catch(() => {})`), so a partner could stay ACTIVE while the log said
|
|
33
|
+
* "left DEACTIVATED".
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
'use strict';
|
|
37
|
+
|
|
38
|
+
function fail(message) { throw new Error(`createProvisioner: ${message}`); }
|
|
39
|
+
|
|
40
|
+
function createProvisioner(options) {
|
|
41
|
+
const o = options || {};
|
|
42
|
+
if (!o.tenancy || typeof o.tenancy.asPartner !== 'function') fail('tenancy is required (the app\'s createTenancy result: asPartner is used)');
|
|
43
|
+
if (!o.db || typeof o.db.invoke !== 'function') fail('db is required (the app\'s db client: invoke is used)');
|
|
44
|
+
if (!o.rbac || typeof o.rbac.refresh !== 'function') fail('rbac is required (refresh(partnerId) is called after every provision)');
|
|
45
|
+
if (!o.logger || typeof o.logger.error !== 'function' || typeof o.logger.info !== 'function') fail('logger is required (info and error)');
|
|
46
|
+
// NO DEFAULT SEEDS: what a new tenant needs is the app's, and another app's list would seed the wrong things quietly.
|
|
47
|
+
if (!Array.isArray(o.seeds) || o.seeds.length === 0) fail('seeds is required: [{ name, run(ctx) }, …], run inside the partner\'s scope');
|
|
48
|
+
const names = new Set();
|
|
49
|
+
for (const s of o.seeds) {
|
|
50
|
+
if (!s || typeof s.name !== 'string' || !s.name || typeof s.run !== 'function') fail('each seed is { name, run(ctx) }');
|
|
51
|
+
if (names.has(s.name)) fail(`two seeds are named "${s.name}"`);
|
|
52
|
+
names.add(s.name);
|
|
53
|
+
}
|
|
54
|
+
// NO DEFAULT DEACTIVATION: an app whose hub-received partners refuse the local switch deactivates another way.
|
|
55
|
+
if (typeof o.deactivateWith !== 'function') fail("deactivateWith is required: (partnerId, opts) => the app's deactivation (setActive, or its hub path)");
|
|
56
|
+
// ONE CALLBACK AFTER EVERY WRITE TO THE PARTNER LIST HAS COMMITTED, on the main thread (an invoke that returned
|
|
57
|
+
// has committed; the store runs in the worker and cannot reach a main-thread cache). The app wires it to
|
|
58
|
+
// createTenancy's refreshActivePartners() and createHostTenant's forget(). No default: an app that forgot it would keep
|
|
59
|
+
// serving a deactivated partner's host, or honour acting into it, until its next restart.
|
|
60
|
+
//
|
|
61
|
+
// A FUNCTION OR A LIST OF FUNCTIONS, all STARTED AT ONCE (in array order) and each ISOLATED: with one function doing
|
|
62
|
+
// both, a host forget() that threw (an app's onForget) stopped the active-partner refresh after it, and acting into a
|
|
63
|
+
// deactivated partner went on for ever; awaited one after the other, the first one's slow work delayed the second's
|
|
64
|
+
// effect. An entry that throws or rejects is logged, naming its position, and stops none of the others.
|
|
65
|
+
const subscribers = Array.isArray(o.onPartnersChanged) ? o.onPartnersChanged.slice() : [o.onPartnersChanged];
|
|
66
|
+
if (subscribers.length === 0 || !subscribers.every((f) => typeof f === 'function')) {
|
|
67
|
+
fail("onPartnersChanged is required: (event) => …, or a list of them, the app's refresh of every partner-list cache (active partners, hosts)");
|
|
68
|
+
}
|
|
69
|
+
// REQUIRED, NO DEFAULT, the same value the app gives the partner store: `true` refuses createPartner, provision,
|
|
70
|
+
// updatePartner, setPartnerActive and write below platform scope, judged here on the main thread from the current
|
|
71
|
+
// tenant context, BEFORE anything is written or any seed runs. provision() writes into the partner it names through
|
|
72
|
+
// asPartner(id), so without this a caller at partner A's scope could seed partner B. Engine-independent: it reads
|
|
73
|
+
// the context, not the database, so it refuses on SQLite too (where the store's own check does nothing).
|
|
74
|
+
if (typeof o.writesRequirePlatform !== 'boolean') fail('writesRequirePlatform is required (true or false), the same value the partner store is given: must provisioning and partner writes run at platform scope?');
|
|
75
|
+
if (o.writesRequirePlatform && typeof o.tenancy.currentTenant !== 'function') fail('tenancy.currentTenant is required with writesRequirePlatform');
|
|
76
|
+
const partnerModel = o.partnerModel || 'Partner';
|
|
77
|
+
const { tenancy, db, rbac, logger, seeds, deactivateWith, writesRequirePlatform } = o;
|
|
78
|
+
|
|
79
|
+
/** Refuse below platform scope (writesRequirePlatform), before anything is written; the store's code and sentence shape. */
|
|
80
|
+
function platformOnly(label) {
|
|
81
|
+
if (!writesRequirePlatform) return;
|
|
82
|
+
const ctx = tenancy.currentTenant();
|
|
83
|
+
if (ctx && ctx.scope === 'platform') return;
|
|
84
|
+
throw Object.assign(new Error(`Partner provisioning: ${label} writes the partner list and must run at platform scope (asPlatform), not "${ctx ? ctx.scope : 'none'}"`),
|
|
85
|
+
{ code: 'tenant_scope_refused' });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A seed's read of "what is there already": anything but an array is an error, never "none found". */
|
|
89
|
+
async function rows(model, method, ...args) {
|
|
90
|
+
const r = await db.invoke(model, method, ...args);
|
|
91
|
+
if (!Array.isArray(r)) throw new Error(`partner provisioning: ${model}.${method} returned ${r === null ? 'null' : typeof r}, expected an array`);
|
|
92
|
+
return r;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Give a partner the rows it cannot work without, then refresh its RBAC cache. Safe to re-run.
|
|
97
|
+
*
|
|
98
|
+
* EVERY SEED INSIDE THE PARTNER'S OWN SCOPE: each scoped table defaults `partner_id` from the session, so the rows
|
|
99
|
+
* land in the right tenant without any model naming it, and outside a scope the NOT NULL refuses them rather than
|
|
100
|
+
* defaulting to somebody.
|
|
101
|
+
*
|
|
102
|
+
* @returns {Promise<object>} { <seed name>: what that seed returned }, in the order of `seeds`
|
|
103
|
+
*/
|
|
104
|
+
async function provision(partnerId, opts) {
|
|
105
|
+
platformOnly('provision');
|
|
106
|
+
const id = Number(partnerId);
|
|
107
|
+
const seeded = await tenancy.asPartner(id, async () => {
|
|
108
|
+
const out = {};
|
|
109
|
+
for (const s of seeds) {
|
|
110
|
+
const r = await s.run({ db, partnerId: id, rows, tenancy, opts });
|
|
111
|
+
if (r === undefined) throw new Error(`partner provisioning: the seed "${s.name}" returned nothing — a seed says what it did`);
|
|
112
|
+
out[s.name] = r;
|
|
113
|
+
}
|
|
114
|
+
return out;
|
|
115
|
+
});
|
|
116
|
+
// THE CACHE, AND THIS IS THE LINE PEOPLE FORGET: RBAC loads every partner's roles at boot, so a partner seeded
|
|
117
|
+
// afterwards has no cache until refresh(id) or a restart, and grants nothing, which reads as a permissions bug.
|
|
118
|
+
await rbac.refresh(id);
|
|
119
|
+
return seeded;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// THE FAILURE PATH CANNOT ITSELF FAIL: a logger that throws there would hand the caller the logger's error, with no
|
|
123
|
+
// partnerId, and a half-built partner whose deactivation failed would stay active and unreported.
|
|
124
|
+
function safeLog(level, line) {
|
|
125
|
+
try { logger[level](typeof line === 'function' ? line() : line); } catch (_) { /* the error the caller gets says the same */ }
|
|
126
|
+
}
|
|
127
|
+
const messageOf = (e) => (e && e.message) || String(e);
|
|
128
|
+
|
|
129
|
+
const describe = (seeded) => Object.entries(seeded)
|
|
130
|
+
.map(([k, v]) => `${k}=${v !== null && typeof v === 'object' ? JSON.stringify(v) : v}`).join(', ');
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Create a partner and make it usable; on a failure, leave it DEACTIVATED and throw with `partnerId`.
|
|
134
|
+
*
|
|
135
|
+
* `domain` and `portal_host` are DERIVED BY THE CALLER: deriving needs the installation's base domain, and the route
|
|
136
|
+
* is where a bad one has a form to be reported on. Every field is passed to the store's create as given (an app's
|
|
137
|
+
* own create fields included), and `opts` to both the create and the deactivation.
|
|
138
|
+
*/
|
|
139
|
+
async function createPartner(fields, opts) {
|
|
140
|
+
platformOnly('createPartner');
|
|
141
|
+
const partner = opts === undefined
|
|
142
|
+
? await db.invoke(partnerModel, 'create', fields)
|
|
143
|
+
: await db.invoke(partnerModel, 'create', fields, opts);
|
|
144
|
+
const id = Number(partner.id);
|
|
145
|
+
let seeded;
|
|
146
|
+
try {
|
|
147
|
+
seeded = await provision(id, opts);
|
|
148
|
+
} catch (e) {
|
|
149
|
+
// LEFT UNUSABLE ON PURPOSE, rather than deleted: deleting would discard whatever did get written and hide the
|
|
150
|
+
// evidence; deactivating makes it unreachable to its people while leaving an operator something to fix.
|
|
151
|
+
let deactivated = true;
|
|
152
|
+
try {
|
|
153
|
+
await deactivateWith(id, opts);
|
|
154
|
+
await changed({ op: 'deactivate', id, reason: 'provisioning failed' });
|
|
155
|
+
} catch (de) {
|
|
156
|
+
deactivated = false;
|
|
157
|
+
safeLog('error', `Partner ${id} "${partner.name}" could not be DEACTIVATED after its provisioning failed `
|
|
158
|
+
+ `(${messageOf(de)}) — it is still ACTIVE and half-built. Deactivate it by hand, then fix the cause and re-provision.`);
|
|
159
|
+
}
|
|
160
|
+
safeLog('error', `Partner ${id} "${partner.name}" was created but could not be provisioned (${messageOf(e)}) — `
|
|
161
|
+
+ (deactivated ? 'left DEACTIVATED. Fix the cause and re-provision; do not create a second.'
|
|
162
|
+
: 'and it could NOT be deactivated (logged above).'));
|
|
163
|
+
const err = new Error(deactivated
|
|
164
|
+
? `The partner was created but could not be set up (${messageOf(e)}). It has been deactivated so `
|
|
165
|
+
+ 'nobody can sign in to a half-built tenant. Re-provision it once the cause is fixed.'
|
|
166
|
+
: `The partner was created but could not be set up (${messageOf(e)}), and it could not be deactivated either: `
|
|
167
|
+
+ 'it is still active. Deactivate it, then re-provision it once the cause is fixed.');
|
|
168
|
+
err.partnerId = id;
|
|
169
|
+
err.deactivated = deactivated;
|
|
170
|
+
err.cause = e;
|
|
171
|
+
// The row exists whether or not it could be deactivated: the caches hear of it either way.
|
|
172
|
+
if (!deactivated) await changed({ op: 'create', id, reason: 'provisioning failed, still active' });
|
|
173
|
+
throw err;
|
|
174
|
+
}
|
|
175
|
+
// Logged OUTSIDE the try: a logger that throws must not turn a provisioned partner into a "failed" one and
|
|
176
|
+
// deactivate it.
|
|
177
|
+
await changed({ op: 'create', id });
|
|
178
|
+
safeLog('info', () => `Partner ${id} "${partner.name}" created and provisioned: ${describe(seeded)}`);
|
|
179
|
+
return { ...partner, seeded };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The callback, guarded: every subscriber is STARTED AT ONCE, in array order (each called synchronously, one after
|
|
184
|
+
* the other, before any is awaited), each isolated, and all are awaited to settle before the write answers. So no
|
|
185
|
+
* entry's slow work delays another's immediate effect (the active set's stale mark, the host map's drop), and order
|
|
186
|
+
* opens no window. One that throws or rejects is logged at error (with its position when there is more than one);
|
|
187
|
+
* nothing changes what the write answered. Every entry must settle: nothing here bounds one that never does.
|
|
188
|
+
*/
|
|
189
|
+
async function changed(event) {
|
|
190
|
+
const failed = (i, e) => {
|
|
191
|
+
const which = subscribers.length > 1 ? ` (onPartnersChanged entry ${i + 1} of ${subscribers.length})` : '';
|
|
192
|
+
safeLog('error', `Partner ${event.id}: the partner-list refresh${which} after "${event.op}" failed (${messageOf(e)}) — `
|
|
193
|
+
+ 'host and active-partner caches may be stale until the next change or restart.');
|
|
194
|
+
};
|
|
195
|
+
const runs = subscribers.map((f, i) => {
|
|
196
|
+
try { return Promise.resolve(f(event)).catch((e) => failed(i, e)); } catch (e) { failed(i, e); return null; }
|
|
197
|
+
});
|
|
198
|
+
await Promise.all(runs);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The other two writes to the partner list, through the same callback: the app's routes call these instead of
|
|
203
|
+
* invoking the store directly, so every write that commits refreshes the caches. The store's own answer is
|
|
204
|
+
* returned unchanged (`changes` 0 for a repeat). A write that throws refreshes nothing.
|
|
205
|
+
*/
|
|
206
|
+
async function updatePartner(id, fields, opts) {
|
|
207
|
+
platformOnly('updatePartner');
|
|
208
|
+
const r = opts === undefined ? await db.invoke(partnerModel, 'update', id, fields) : await db.invoke(partnerModel, 'update', id, fields, opts);
|
|
209
|
+
await changed({ op: 'update', id: Number(id), changes: Number(r && r.changes) || 0 });
|
|
210
|
+
return r;
|
|
211
|
+
}
|
|
212
|
+
async function setPartnerActive(id, active, opts) {
|
|
213
|
+
platformOnly('setPartnerActive');
|
|
214
|
+
const r = opts === undefined ? await db.invoke(partnerModel, 'setActive', id, active) : await db.invoke(partnerModel, 'setActive', id, active, opts);
|
|
215
|
+
await changed({ op: active ? 'activate' : 'deactivate', id: Number(id), changes: Number(r && r.changes) || 0 });
|
|
216
|
+
return r;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* The guarded notifier, for a main-thread write that does not go through this provisioner: call it right after the
|
|
221
|
+
* write has returned. Never throws; a failing callback is logged at error.
|
|
222
|
+
*/
|
|
223
|
+
async function partnersChanged(event) {
|
|
224
|
+
await changed({ op: 'change', id: null, ...(event || {}) });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* A DIRECT STORE WRITE ON THE MAIN THREAD, followed by the callback: `write('setActiveFromHub', id, 0)`,
|
|
229
|
+
* `write('bindHouseRef', ref)`, `write('update', id, fields)`. Invokes `<partnerModel>.<method>(...args)`, fires
|
|
230
|
+
* the notifier ONCE after it returned (committed), not when it throws, and returns its answer unchanged. The
|
|
231
|
+
* attached apps' hub-receive paths write through this, so a partner deactivated at the hub ends acting into it and
|
|
232
|
+
* clears its host as a local deactivation does.
|
|
233
|
+
*/
|
|
234
|
+
async function write(method, ...args) {
|
|
235
|
+
if (typeof method !== 'string' || !method) throw new Error('write(method, ...args): name the store method');
|
|
236
|
+
platformOnly(`write('${method}')`);
|
|
237
|
+
const r = await db.invoke(partnerModel, method, ...args);
|
|
238
|
+
const first = args[0];
|
|
239
|
+
const id = (typeof first === 'number' || (typeof first === 'string' && /^[0-9]+$/.test(first))) ? Number(first) : null;
|
|
240
|
+
await changed({ op: method, id, changes: Number(r && r.changes) || 0 });
|
|
241
|
+
return r;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return { createPartner, provision, updatePartner, setPartnerActive, partnersChanged, write };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
module.exports = { createProvisioner };
|