@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,460 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createPartnerStore — the partner list itself, as the nine methods every multi-tenant app carried.
|
|
3
|
+
*
|
|
4
|
+
* const store = createPartnerStore({ driver: () => database.driver(), sql, mintRef, refShape, refPolicy,
|
|
5
|
+
* counts, nameMaxLength, houseName, extraColumns, onChange, onDeactivate });
|
|
6
|
+
* module.exports = { ...store, ...theAppsOwnHubMethods }; // models/Partner.js
|
|
7
|
+
*
|
|
8
|
+
* NOT TENANT-SCOPED, and it cannot be: this table IS the tenancy. A partner nobody could see could not be joined to,
|
|
9
|
+
* and the row-level-security predicate on every other table reads a partner id that has to resolve here. The manifest
|
|
10
|
+
* classifies it PLATFORM for exactly that reason.
|
|
11
|
+
*
|
|
12
|
+
* THE HOUSE PARTNER IS SEEDED FROM CODE, NOT FROM THE SCHEMA, the same rule the built-in roles and the settings
|
|
13
|
+
* defaults follow: a row shipped in a migration is a row every future app inherits without choosing it.
|
|
14
|
+
*
|
|
15
|
+
* Moved from the starter's model (its nine methods), with: the platform-scope refusal on listWithCounts (the soc
|
|
16
|
+
* app); the house's reference minted at seed, the reference checked on create, `update` in one transaction with the
|
|
17
|
+
* host normalised, `setActive` in one transaction and a no-op when unchanged (the hub); paging and search on the list
|
|
18
|
+
* and an editable domain with its duplicate check (the desk). Whatever differs between apps is a setting; see
|
|
19
|
+
* the README's "Partners".
|
|
20
|
+
*
|
|
21
|
+
* THE DRIVER IS A GETTER, read at every call: a handle captured at require time binds to the first driver in the
|
|
22
|
+
* process, and a test bridge that opens a second one would be written through the old handle.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
'use strict';
|
|
26
|
+
|
|
27
|
+
const { assertPlatformScope } = require('@aria-framework/db-worker');
|
|
28
|
+
|
|
29
|
+
const IDENT = /^[a-z_][a-z0-9_]*$/;
|
|
30
|
+
const REF_POLICIES = ['editable', 'permanent'];
|
|
31
|
+
|
|
32
|
+
function fail(message) { throw new Error(`createPartnerStore: ${message}`); }
|
|
33
|
+
function typed(code, message) { return Object.assign(new Error(message), { code }); }
|
|
34
|
+
const has = (o, k) => !!o && Object.prototype.hasOwnProperty.call(o, k);
|
|
35
|
+
const escapeLike = (s) => String(s).replace(/[\\%_]/g, (c) => `\\${c}`);
|
|
36
|
+
|
|
37
|
+
// The sentences an operator reads. An app with its own wording passes `messages` (the desk's portal and Postgres lines).
|
|
38
|
+
const STORE_MESSAGES = {
|
|
39
|
+
hostRequired: 'A partner needs a portal hostname, derived from its company domain (or an opaque one if it '
|
|
40
|
+
+ 'has no domain). Without it its people would have to sign in at the installation\'s own '
|
|
41
|
+
+ 'address, where a username that exists in two tenants cannot be resolved to one.',
|
|
42
|
+
postgresOnly: 'Partners can only be created on PostgreSQL. On SQLite every partner_id column defaults to '
|
|
43
|
+
+ 'the house partner and there is no row-level security, so a second tenant would have its '
|
|
44
|
+
+ 'rows written silently into the first one.',
|
|
45
|
+
hostCleared: 'A partner needs a portal hostname. Clearing it would leave its staff unable to sign in '
|
|
46
|
+
+ 'anywhere, because the hostname is what decides which tenant a login belongs to.',
|
|
47
|
+
houseDeactivate: 'The house partner cannot be deactivated — it is the installation itself, and its staff are '
|
|
48
|
+
+ 'the only people who could turn it back on.'
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
function checkOptions(o) {
|
|
52
|
+
if (!o || typeof o !== 'object') fail('pass an options object');
|
|
53
|
+
if (typeof o.driver !== 'function') fail('driver must be a getter, () => database.driver(), read at call time');
|
|
54
|
+
if (!o.sql || typeof o.sql.returningId !== 'function' || typeof o.sql.now !== 'function') {
|
|
55
|
+
fail("sql is required: @aria-framework/db-worker's sql (the app's lib/sql.js re-export)");
|
|
56
|
+
}
|
|
57
|
+
// NO DEFAULT FOR THE REFERENCE MINT: an attached app must never mint the hub's own prefix for a partner, and a
|
|
58
|
+
// default would be one app's prefix handed to every other.
|
|
59
|
+
if (typeof o.mintRef !== 'function') fail("mintRef is required, with no default: () => a new reference in this app's OWN prefix");
|
|
60
|
+
if (o.refShape !== null && typeof o.refShape !== 'function') {
|
|
61
|
+
fail('refShape is required: (ref) => true when a GIVEN reference has this app\'s shape, or null to accept any');
|
|
62
|
+
}
|
|
63
|
+
if (!(REF_POLICIES.includes(o.refPolicy) || typeof o.refPolicy === 'function')) {
|
|
64
|
+
fail("refPolicy is required, with no default: 'editable', 'permanent', or (current, newRef, ctx) => true when the reference is locked");
|
|
65
|
+
}
|
|
66
|
+
if (!o.counts || typeof o.counts !== 'object' || Array.isArray(o.counts)) {
|
|
67
|
+
fail('counts is required: { alias: { table, where? } } for the list screen ({} for none)');
|
|
68
|
+
}
|
|
69
|
+
for (const [alias, c] of Object.entries(o.counts)) {
|
|
70
|
+
if (!IDENT.test(alias)) fail(`counts: "${alias}" is not a plain column alias`);
|
|
71
|
+
if (!c || !IDENT.test(String(c.table || ''))) fail(`counts.${alias}: table must be a plain table name`);
|
|
72
|
+
if (c.where != null && typeof c.where !== 'string') fail(`counts.${alias}: where is SQL text about the alias "c"`);
|
|
73
|
+
}
|
|
74
|
+
if (o.nameMaxLength !== null && !(Number.isInteger(o.nameMaxLength) && o.nameMaxLength > 0)) {
|
|
75
|
+
fail('nameMaxLength is required: a positive whole number, or null for no limit');
|
|
76
|
+
}
|
|
77
|
+
if (!(typeof o.houseName === 'string' || typeof o.houseName === 'function')) {
|
|
78
|
+
fail("houseName is required: the house partner's name at seed (the app's brand), a string or () => string");
|
|
79
|
+
}
|
|
80
|
+
// NO DEFAULT: the hub mints the house's reference at seed; the apps attached to it seed the house with NULL on
|
|
81
|
+
// purpose, because their hub-receive code binds the hub's house id to it once (`... WHERE is_house = 1 AND
|
|
82
|
+
// external_ref IS NULL`) and refuses a house document when the house already holds another reference.
|
|
83
|
+
if (typeof o.mintHouseRef !== 'boolean') fail('mintHouseRef is required (true or false): is the house given a minted reference at seed?');
|
|
84
|
+
// NO DEFAULT: `partners` has no row-level security, so nothing below this store stops a write at a partner's scope.
|
|
85
|
+
if (typeof o.writesRequirePlatform !== 'boolean') fail('writesRequirePlatform is required (true or false): must create, update, setActive and seedHouse run at platform scope?');
|
|
86
|
+
if (!['house-first', 'id'].includes(o.allOrder)) fail("allOrder is required: 'house-first' (the house, then by name) or 'id'");
|
|
87
|
+
if (o.messages != null && typeof o.messages !== 'object') fail('messages must be an object');
|
|
88
|
+
for (const k of Object.keys(o.messages || {})) {
|
|
89
|
+
if (!(k in STORE_MESSAGES)) fail(`messages: unknown key "${k}" (known: ${Object.keys(STORE_MESSAGES).join(', ')})`);
|
|
90
|
+
}
|
|
91
|
+
if (o.normaliseHost != null && typeof o.normaliseHost !== 'function') fail('normaliseHost must be a function (host) => host');
|
|
92
|
+
if (o.paginate != null && typeof o.paginate !== 'function') fail('paginate must be a function ({page, pageSize, total}) => pager');
|
|
93
|
+
for (const k of ['onChange', 'onDeactivate']) {
|
|
94
|
+
if (o[k] != null && typeof o[k] !== 'function') fail(`${k} must be a function (tx, event)`);
|
|
95
|
+
}
|
|
96
|
+
const extra = o.extraColumns == null ? [] : o.extraColumns;
|
|
97
|
+
if (!Array.isArray(extra)) fail('extraColumns must be a list of { name, create?, update?, list?, param?, read? }');
|
|
98
|
+
const CORE = new Set(['id', 'name', 'external_ref', 'is_house', 'is_active', 'domain', 'portal_host', 'created_at']);
|
|
99
|
+
for (const c of extra) {
|
|
100
|
+
if (!c || !IDENT.test(String(c.name || ''))) fail('extraColumns: each needs a plain column name');
|
|
101
|
+
if (CORE.has(c.name)) fail(`extraColumns: "${c.name}" is one of the store's own columns`);
|
|
102
|
+
if (c.update != null && ![true, false, 'now'].includes(c.update)) fail(`extraColumns.${c.name}: update is true, false or 'now'`);
|
|
103
|
+
}
|
|
104
|
+
return extra;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function createPartnerStore(options) {
|
|
108
|
+
const extra = checkOptions(options);
|
|
109
|
+
const {
|
|
110
|
+
driver, sql, mintRef, refShape, refPolicy, counts, nameMaxLength, houseName,
|
|
111
|
+
normaliseHost, paginate, onChange, onDeactivate, mintHouseRef, writesRequirePlatform, allOrder
|
|
112
|
+
} = options;
|
|
113
|
+
const msg = { ...STORE_MESSAGES, ...(options.messages || {}) };
|
|
114
|
+
// A WRITE AT A PARTNER'S SCOPE, REFUSED BEFORE ANYTHING IS WRITTEN (when the app says so): the table has no policy,
|
|
115
|
+
// so such a write lands on any partner, and a deactivation's sign-out of that partner's users would be filtered away
|
|
116
|
+
// by the policy on `users`, leaving it deactivated with its people still signed in. Postgres only, as the source.
|
|
117
|
+
const platformWrite = (h, label) => (writesRequirePlatform
|
|
118
|
+
? assertPlatformScope(h, `Partner.${label} writes the partner table and`) : null);
|
|
119
|
+
|
|
120
|
+
const d = () => {
|
|
121
|
+
const handle = driver();
|
|
122
|
+
if (!handle) throw new Error('createPartnerStore: the driver getter returned nothing (called before the database opened?)');
|
|
123
|
+
return handle;
|
|
124
|
+
};
|
|
125
|
+
const listExtra = extra.filter((c) => c.list).map((c) => `, p.${c.name}`).join('');
|
|
126
|
+
const createExtra = extra.filter((c) => c.create);
|
|
127
|
+
const updateExtra = extra.filter((c) => c.update);
|
|
128
|
+
const param = (c, v) => (c.param ? c.param(v) : v);
|
|
129
|
+
|
|
130
|
+
function cleanName(name) {
|
|
131
|
+
const clean = String(name == null ? '' : name).trim();
|
|
132
|
+
if (!clean) throw new Error('A partner name is required.');
|
|
133
|
+
if (nameMaxLength !== null && clean.length > nameMaxLength) {
|
|
134
|
+
throw new Error(`A partner name may be at most ${nameMaxLength} characters.`);
|
|
135
|
+
}
|
|
136
|
+
return clean;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function countsSql() {
|
|
140
|
+
return Object.entries(counts).map(([alias, c]) => `,
|
|
141
|
+
(SELECT COUNT(*) FROM ${c.table} c WHERE c.partner_id = p.id${c.where ? ` AND (${c.where})` : ''}) AS ${alias}`)
|
|
142
|
+
.join('');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
/**
|
|
147
|
+
* Create the house partner if it is not there. Idempotent: safe on every boot.
|
|
148
|
+
*
|
|
149
|
+
* `is_house = 1` is the DEFINING property, not the id: at most one row is the house (a partial unique index),
|
|
150
|
+
* and everything that needs it asks for the flag, because a restored or merged database is exactly where the id
|
|
151
|
+
* and the flag stop agreeing.
|
|
152
|
+
*
|
|
153
|
+
* WITH `mintHouseRef` ITS REFERENCE IS MINTED HERE, AT CREATION, like every other partner's: an app whose
|
|
154
|
+
* reference is permanent and NOT NULL has no "insert now, backfill at the next boot" shape. WITHOUT it the house's
|
|
155
|
+
* reference is NULL, which an attached app needs: the hub's house id is bound to it later, once.
|
|
156
|
+
*/
|
|
157
|
+
async seedHouse() {
|
|
158
|
+
const h = d();
|
|
159
|
+
await platformWrite(h, 'seedHouse');
|
|
160
|
+
const existing = await h.get('SELECT id FROM partners WHERE is_house = 1');
|
|
161
|
+
if (existing) return { seeded: false, id: Number(existing.id) };
|
|
162
|
+
const name = (typeof houseName === 'function' ? houseName() : houseName) || 'House';
|
|
163
|
+
const r = mintHouseRef
|
|
164
|
+
? await h.run(`INSERT INTO partners (name, is_house, external_ref) VALUES (?, 1, ?)${sql.returningId()}`, [name, mintRef()])
|
|
165
|
+
: await h.run(`INSERT INTO partners (name, is_house) VALUES (?, 1)${sql.returningId()}`, [name]);
|
|
166
|
+
return { seeded: true, id: Number(r.lastId) };
|
|
167
|
+
},
|
|
168
|
+
|
|
169
|
+
/** The house partner, or null before the first boot has seeded it. */
|
|
170
|
+
async house() {
|
|
171
|
+
return d().get('SELECT * FROM partners WHERE is_house = 1');
|
|
172
|
+
},
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Every partner, INCLUDING DEACTIVATED ONES, deliberately. A per-partner job visiting a dormant tenant does a
|
|
176
|
+
* little work for nothing; SKIPPING a tenant that turned out to be live would miss its work entirely. A caller
|
|
177
|
+
* wanting only live tenants says so.
|
|
178
|
+
*
|
|
179
|
+
* `portal_host`, `domain` and `is_active` ARE SELECTED, and that is not padding: host resolution builds its
|
|
180
|
+
* host-to-partner map from this one read, and with them absent every row looked hostless and every vanity host
|
|
181
|
+
* fell through to the house.
|
|
182
|
+
*/
|
|
183
|
+
async all() {
|
|
184
|
+
return d().all(
|
|
185
|
+
`SELECT id, name, external_ref, is_house, is_active, portal_host, domain, created_at${extra.filter((c) => c.list).map((c) => `, ${c.name}`).join('')} `
|
|
186
|
+
+ `FROM partners ORDER BY ${allOrder === 'id' ? 'id' : 'is_house DESC, name'}`);
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
async byId(id) {
|
|
190
|
+
return d().get('SELECT * FROM partners WHERE id = ?', [Number(id)]);
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The ACTIVE partner that owns a hostname, or undefined. Compared with lower(), matching the unique index (so it
|
|
195
|
+
* is used, on a read made once per unauthenticated request). `is_active = 1` is part of the lookup: a
|
|
196
|
+
* deactivated partner's host resolves to nothing, so it falls back to the installation's own front door. Callers
|
|
197
|
+
* pass a host already normalised; this does not re-normalise (two places is how the directions drift apart).
|
|
198
|
+
*/
|
|
199
|
+
async byPortalHost(host) {
|
|
200
|
+
const h = String(host == null ? '' : host).trim().toLowerCase();
|
|
201
|
+
if (!h) return undefined;
|
|
202
|
+
return d().get(
|
|
203
|
+
'SELECT id, name, portal_host FROM partners '
|
|
204
|
+
+ 'WHERE portal_host IS NOT NULL AND lower(portal_host) = ? AND is_active = 1', [h]);
|
|
205
|
+
},
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The list the admin screen renders, with the app's counts.
|
|
209
|
+
*
|
|
210
|
+
* REFUSED BELOW PLATFORM SCOPE, before it reads: asked from a partner context the policy would return that
|
|
211
|
+
* partner's rows for every line and each count would silently be its own. Postgres only (SQLite holds one
|
|
212
|
+
* tenant). The permission in front of it is not the only guard.
|
|
213
|
+
*
|
|
214
|
+
* With no argument: every partner, as an array. With `{ q, page, pageSize }`: one page, `q` searching names
|
|
215
|
+
* case-blind and escaped, COUNT first, the id as the tie-break, returning `{ rows, total, pager }` (needs the
|
|
216
|
+
* store's `paginate`).
|
|
217
|
+
*/
|
|
218
|
+
async listWithCounts(paging) {
|
|
219
|
+
const h = d();
|
|
220
|
+
await assertPlatformScope(h, 'Partner.listWithCounts counts across partners and');
|
|
221
|
+
const cols = `p.id, p.name, p.external_ref, p.is_house, p.is_active, p.created_at,
|
|
222
|
+
p.portal_host, p.domain${listExtra}${countsSql()}`;
|
|
223
|
+
if (paging === undefined) {
|
|
224
|
+
return h.all(`
|
|
225
|
+
SELECT ${cols}
|
|
226
|
+
FROM partners p
|
|
227
|
+
ORDER BY p.is_house DESC, p.name`);
|
|
228
|
+
}
|
|
229
|
+
if (!paginate) throw new Error('Partner.listWithCounts: paging needs the store\'s paginate option');
|
|
230
|
+
const { q, page, pageSize } = paging || {};
|
|
231
|
+
const where = q ? "WHERE LOWER(p.name) LIKE ? ESCAPE '\\'" : '';
|
|
232
|
+
const params = q ? [`%${escapeLike(String(q).toLowerCase())}%`] : [];
|
|
233
|
+
const total = Number(((await h.get(`SELECT COUNT(*) AS c FROM partners p ${where}`, params)) || {}).c) || 0;
|
|
234
|
+
const pager = paginate({ page, pageSize, total });
|
|
235
|
+
const rows = total
|
|
236
|
+
? await h.all(`
|
|
237
|
+
SELECT ${cols}
|
|
238
|
+
FROM partners p
|
|
239
|
+
${where}
|
|
240
|
+
ORDER BY p.is_house DESC, p.name, p.id LIMIT ? OFFSET ?`, [...params, pager.limit, pager.offset])
|
|
241
|
+
: [];
|
|
242
|
+
return { rows, total, pager };
|
|
243
|
+
},
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Create a partner ROW. The row only: its roles and other seeds are written inside the new partner's scope, on
|
|
247
|
+
* the main thread, by createProvisioner.
|
|
248
|
+
*
|
|
249
|
+
* THE ONE CHANCE TO CHOOSE THE REFERENCE: given, it must have this app's shape (`refShape`) and belong to nobody;
|
|
250
|
+
* omitted, one is minted with the app's own `mintRef`.
|
|
251
|
+
*/
|
|
252
|
+
async create(fields) {
|
|
253
|
+
const f = fields || {};
|
|
254
|
+
const h = d();
|
|
255
|
+
await platformWrite(h, 'create');
|
|
256
|
+
const clean = cleanName(f.name);
|
|
257
|
+
const givenRef = f.external_ref == null ? '' : String(f.external_ref).trim();
|
|
258
|
+
if (givenRef && refShape && !refShape(givenRef)) {
|
|
259
|
+
throw typed('PARTNER_REF_SHAPE', `The external reference "${givenRef}" is not in this installation's reference `
|
|
260
|
+
+ 'format. Leave it empty and one is generated.');
|
|
261
|
+
}
|
|
262
|
+
const domain = f.domain || null;
|
|
263
|
+
const portalHost = f.portal_host || null;
|
|
264
|
+
|
|
265
|
+
// EVERY NON-HOUSE PARTNER IS REACHABLE BY ITS OWN HOSTNAME, AND THE MODEL ENFORCES IT. Without one its people
|
|
266
|
+
// would sign in at the installation's own address, where an anonymous lookup runs at platform scope and matches
|
|
267
|
+
// one row PER TENANT: the same username in two tenants resolves to whichever the database returns first. In
|
|
268
|
+
// the model, not only on the form, because the form is one caller.
|
|
269
|
+
if (!portalHost) throw new Error(msg.hostRequired);
|
|
270
|
+
|
|
271
|
+
// AND IT IS A POSTGRES FEATURE. On SQLite every partner_id column defaults to the house and there is no
|
|
272
|
+
// row-level security: a second partner's rows would land in the house, silently. Refusing is the honest answer.
|
|
273
|
+
if (h.dialect.kind !== 'postgres') throw new Error(msg.postgresOnly);
|
|
274
|
+
|
|
275
|
+
const existing = await h.get('SELECT id FROM partners WHERE lower(name) = lower(?)', [clean]);
|
|
276
|
+
if (existing) throw new Error(`A partner called "${clean}" already exists.`);
|
|
277
|
+
|
|
278
|
+
// BOTH CLASHES NAMED BEFORE THE INSERT: the unique indexes would refuse either, with a message naming the index,
|
|
279
|
+
// which tells an operator nothing about WHICH partner holds it. The domain first, because it is what was typed.
|
|
280
|
+
if (domain) {
|
|
281
|
+
const dupeDomain = await h.get(
|
|
282
|
+
'SELECT id, name FROM partners WHERE domain IS NOT NULL AND lower(domain) = lower(?)', [domain]);
|
|
283
|
+
if (dupeDomain) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
`The domain "${domain}" already belongs to "${dupeDomain.name}". Two partners cannot `
|
|
286
|
+
+ 'share a domain, because their portal hostnames would be derived the same.');
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
const dupeHost = await h.get(
|
|
290
|
+
'SELECT id, name FROM partners WHERE portal_host IS NOT NULL AND lower(portal_host) = lower(?)', [portalHost]);
|
|
291
|
+
if (dupeHost) {
|
|
292
|
+
throw new Error(
|
|
293
|
+
`The hostname "${portalHost}" is already the portal for "${dupeHost.name}". Visitors would `
|
|
294
|
+
+ 'reach whichever partner the database returned first.');
|
|
295
|
+
}
|
|
296
|
+
if (givenRef) {
|
|
297
|
+
const dupeRef = await h.get('SELECT id, name FROM partners WHERE external_ref = ?', [givenRef]);
|
|
298
|
+
if (dupeRef) throw new Error(`The external reference "${givenRef}" already belongs to "${dupeRef.name}".`);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const ref = givenRef || mintRef();
|
|
302
|
+
// Omitted or undefined is ACTIVE (the sources' `is_active = true` default); only a given falsy value is not.
|
|
303
|
+
const active = f.is_active === undefined ? 1 : (f.is_active ? 1 : 0);
|
|
304
|
+
const cols = ['name', 'external_ref', 'is_house', 'is_active', 'domain', 'portal_host'];
|
|
305
|
+
const vals = [clean, ref, 0, active, domain, portalHost];
|
|
306
|
+
const out = { name: clean, external_ref: ref, domain, portal_host: portalHost, is_active: active };
|
|
307
|
+
for (const c of createExtra) {
|
|
308
|
+
if (!has(f, c.name)) continue;
|
|
309
|
+
cols.push(c.name); vals.push(param(c, f[c.name])); out[c.name] = f[c.name];
|
|
310
|
+
}
|
|
311
|
+
const r = await h.run(
|
|
312
|
+
`INSERT INTO partners (${cols.join(', ')}) VALUES (${cols.map(() => '?').join(', ')})${sql.returningId()}`, vals);
|
|
313
|
+
return { id: Number(r.lastId), ...out };
|
|
314
|
+
},
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Rename a partner, change its hostname (and its domain with it), its reference as `refPolicy` allows, and the
|
|
318
|
+
* app's own `extraColumns`.
|
|
319
|
+
*
|
|
320
|
+
* ONE TRANSACTION: every read is on the handle, and `onChange(tx, event)` runs inside it, so an app that bumps a
|
|
321
|
+
* version on a change commits the edit and the version together or not at all.
|
|
322
|
+
*
|
|
323
|
+
* `portal_host` IS ONLY WRITTEN WHEN THE KEY IS PRESENT: a hostname is optional, so an absent key is otherwise
|
|
324
|
+
* indistinguishable from "clear it", and a caller updating only the name would silently delete it. The same
|
|
325
|
+
* presence rule holds `domain` (which travels with the host: it is the evidence for why the host is what it is)
|
|
326
|
+
* and each `extraColumns` entry (an omitted one is preserved, never blanked).
|
|
327
|
+
*
|
|
328
|
+
* `opts` is the caller's, passed to `refPolicy` and to `onChange` untouched (an app's "from the hub" flag).
|
|
329
|
+
*/
|
|
330
|
+
async update(id, fields, opts) {
|
|
331
|
+
const f = fields || {};
|
|
332
|
+
const pid = Number(id);
|
|
333
|
+
const clean = cleanName(f.name);
|
|
334
|
+
const newHost = has(f, 'portal_host')
|
|
335
|
+
? (normaliseHost && f.portal_host ? normaliseHost(f.portal_host) : (f.portal_host || null))
|
|
336
|
+
: undefined;
|
|
337
|
+
|
|
338
|
+
const h = d();
|
|
339
|
+
await platformWrite(h, 'update');
|
|
340
|
+
return h.transaction(async (tx) => {
|
|
341
|
+
const clash = await tx.get('SELECT id FROM partners WHERE lower(name) = lower(?) AND id <> ?', [clean, pid]);
|
|
342
|
+
if (clash) throw new Error(`A partner called "${clean}" already exists.`);
|
|
343
|
+
const current = await tx.get('SELECT * FROM partners WHERE id = ?', [pid]);
|
|
344
|
+
|
|
345
|
+
const sets = ['name = ?'];
|
|
346
|
+
const vals = [clean];
|
|
347
|
+
|
|
348
|
+
// ── THE REFERENCE ─────────────────────────────────────────────────────────────────────────────────────────
|
|
349
|
+
if (refPolicy === 'permanent') {
|
|
350
|
+
// The partner's identity at every service: named with anything but its stored value, the whole edit is
|
|
351
|
+
// refused, and the column is never written. Omitting the key is the ordinary case.
|
|
352
|
+
if (current && has(f, 'external_ref')) {
|
|
353
|
+
const asked = f.external_ref == null ? '' : String(f.external_ref).trim();
|
|
354
|
+
if (asked !== String(current.external_ref == null ? '' : current.external_ref)) {
|
|
355
|
+
throw typed('PARTNER_REF_PERMANENT', `The external reference cannot be ${asked ? 'changed' : 'cleared'}: `
|
|
356
|
+
+ `"${current.external_ref}" is this partner's identity at every service, and a different one would `
|
|
357
|
+
+ 'orphan its tenants there. Nothing was saved.');
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
} else {
|
|
361
|
+
// 'editable' or a lock predicate: written as given, an absent or empty one stored as NULL (the starter's
|
|
362
|
+
// contract). A predicate is asked only when the value would change, and may throw its own typed refusal.
|
|
363
|
+
const ref = f.external_ref ? String(f.external_ref).trim() : null;
|
|
364
|
+
// The predicate answers true (locked, this package's code), { code, message } (locked, with the app's own code
|
|
365
|
+
// and sentence, so its API answers do not change), or throws its own typed refusal.
|
|
366
|
+
if (typeof refPolicy === 'function' && current && (current.external_ref || null) !== ref) {
|
|
367
|
+
const locked = await refPolicy(current, ref, { tx, opts });
|
|
368
|
+
const LOCKED = "This partner's external reference is locked and cannot be changed.";
|
|
369
|
+
if (locked && typeof locked === 'object') throw typed(String(locked.code || 'PARTNER_REF_LOCKED'), String(locked.message || LOCKED));
|
|
370
|
+
if (locked) throw typed('PARTNER_REF_LOCKED', LOCKED);
|
|
371
|
+
}
|
|
372
|
+
sets.push('external_ref = ?'); vals.push(ref);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ── THE HOSTNAME, AND THE DOMAIN WITH IT ─────────────────────────────────────────────────────────────────
|
|
376
|
+
if (newHost !== undefined) {
|
|
377
|
+
// THE INVARIANT create() ENFORCES HAS TO SURVIVE AN EDIT: clearing the box would put a partner back into
|
|
378
|
+
// the unresolvable state. The HOUSE may have none: it answers for any unrecognised host.
|
|
379
|
+
if (!newHost && current && !Number(current.is_house)) throw new Error(msg.hostCleared);
|
|
380
|
+
if (newHost) {
|
|
381
|
+
const taken = await tx.get(
|
|
382
|
+
'SELECT id, name FROM partners WHERE portal_host IS NOT NULL '
|
|
383
|
+
+ 'AND lower(portal_host) = lower(?) AND id <> ?', [newHost, pid]);
|
|
384
|
+
if (taken) {
|
|
385
|
+
throw new Error(
|
|
386
|
+
`The hostname "${newHost}" is already the portal for "${taken.name}". Two partners cannot `
|
|
387
|
+
+ 'share one hostname — visitors would reach whichever the database returned first.');
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
sets.push('portal_host = ?'); vals.push(newHost);
|
|
391
|
+
if (has(f, 'domain')) {
|
|
392
|
+
const domain = f.domain || null;
|
|
393
|
+
if (domain) {
|
|
394
|
+
const dupe = await tx.get(
|
|
395
|
+
'SELECT id, name FROM partners WHERE domain IS NOT NULL AND lower(domain) = lower(?) AND id <> ?',
|
|
396
|
+
[domain, pid]);
|
|
397
|
+
if (dupe) throw new Error(`The domain "${domain}" already belongs to "${dupe.name}".`);
|
|
398
|
+
}
|
|
399
|
+
sets.push('domain = ?'); vals.push(domain);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// ── THE APP'S OWN COLUMNS: preserved, never blanked, when omitted ────────────────────────────────────────
|
|
404
|
+
for (const c of updateExtra) {
|
|
405
|
+
if (c.update === 'now') { sets.push(`${c.name} = ${sql.now()}`); continue; }
|
|
406
|
+
const v = has(f, c.name) ? f[c.name] : (current ? (c.read ? c.read(current[c.name]) : current[c.name]) : null);
|
|
407
|
+
sets.push(`${c.name} = ?`); vals.push(param(c, v));
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const r = await tx.run(`UPDATE partners SET ${sets.join(', ')} WHERE id = ?`, [...vals, pid]);
|
|
411
|
+
if (onChange && Number(r.changes) > 0) {
|
|
412
|
+
const after = await tx.get('SELECT * FROM partners WHERE id = ?', [pid]);
|
|
413
|
+
await onChange(tx, { id: pid, op: 'update', before: current, after, opts });
|
|
414
|
+
}
|
|
415
|
+
return r;
|
|
416
|
+
});
|
|
417
|
+
},
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Activate or deactivate a partner, in ONE TRANSACTION.
|
|
421
|
+
*
|
|
422
|
+
* THE HOUSE CANNOT BE DEACTIVATED: its staff are the platform operators, the only people who could turn it back
|
|
423
|
+
* on. Refused here, not only on the form.
|
|
424
|
+
*
|
|
425
|
+
* "DID IT CHANGE" IS THE UPDATE'S OWN ANSWER (`AND is_active <> ?`), not a read before it: a plain SELECT is not
|
|
426
|
+
* locked, so two opposite toggles at once would both read the old value. Postgres re-evaluates the condition
|
|
427
|
+
* after the row lock is granted, so whichever runs second sees the first's value, and `changes` counts what
|
|
428
|
+
* moved. A repeat is a no-op with `changes = 0`, and `onChange` is not called.
|
|
429
|
+
*
|
|
430
|
+
* ON DEACTIVATE, WHOEVER IS ALREADY IN IS SIGNED OUT (`users.session_version` bumped: the auth layer drops any
|
|
431
|
+
* session whose copy disagrees, the API's refresh tokens included), then `onDeactivate(tx, event)` ends whatever
|
|
432
|
+
* else the app keeps (portal sessions, codes, trusted browsers). Both run on every deactivate call, as in the app
|
|
433
|
+
* this came from; both are idempotent. Reactivating signs nobody out.
|
|
434
|
+
*
|
|
435
|
+
* THE HOOKS RUN INSIDE THE TRANSACTION, `onChange` last: a hook that throws rolls the flag and the sign-outs back.
|
|
436
|
+
*/
|
|
437
|
+
async setActive(id, active, opts) {
|
|
438
|
+
const pid = Number(id);
|
|
439
|
+
const want = active ? 1 : 0;
|
|
440
|
+
const h = d();
|
|
441
|
+
await platformWrite(h, 'setActive');
|
|
442
|
+
return h.transaction(async (tx) => {
|
|
443
|
+
const row = await tx.get('SELECT is_house FROM partners WHERE id = ?', [pid]);
|
|
444
|
+
if (!row) throw new Error('No such partner.');
|
|
445
|
+
if (Number(row.is_house) === 1 && !want) throw new Error(msg.houseDeactivate);
|
|
446
|
+
const r = await tx.run('UPDATE partners SET is_active = ? WHERE id = ? AND is_active <> ?', [want, pid, want]);
|
|
447
|
+
if (!want) {
|
|
448
|
+
await tx.run('UPDATE users SET session_version = session_version + 1 WHERE partner_id = ?', [pid]);
|
|
449
|
+
if (onDeactivate) await onDeactivate(tx, { id: pid, changes: Number(r.changes), opts });
|
|
450
|
+
}
|
|
451
|
+
if (onChange && Number(r.changes) === 1) {
|
|
452
|
+
await onChange(tx, { id: pid, op: 'setActive', active: !!want, opts });
|
|
453
|
+
}
|
|
454
|
+
return r;
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
module.exports = { createPartnerStore };
|