shutro 0.1.0 → 0.2.1
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/README.md +12 -2
- package/dist/audit/index.d.ts +3 -1
- package/dist/audit/index.js +2 -0
- package/dist/cli/cli.js +17 -2
- package/dist/cli/config.js +2 -0
- package/dist/cli/generate/generate.js +2 -0
- package/dist/cli/generate/render.js +57 -8
- package/dist/cli/init.js +4 -4
- package/dist/cli/resolve.d.ts +2 -0
- package/dist/cli/resolve.js +28 -0
- package/dist/core/data/data.d.ts +59 -0
- package/dist/core/data/data.js +119 -0
- package/dist/core/data/load.d.ts +37 -0
- package/dist/core/data/load.js +236 -0
- package/dist/core/env/env.d.ts +175 -2
- package/dist/core/env/env.js +304 -19
- package/dist/core/env/identity.d.ts +10 -0
- package/dist/core/env/identity.js +16 -0
- package/dist/core/errors.d.ts +15 -1
- package/dist/core/errors.js +21 -0
- package/dist/core/events/events.d.ts +44 -0
- package/dist/core/events/events.js +58 -0
- package/dist/core/events/workers.d.ts +56 -0
- package/dist/core/events/workers.js +155 -0
- package/dist/core/index.d.ts +17 -9
- package/dist/core/index.js +11 -3
- package/dist/core/model/field.d.ts +33 -0
- package/dist/core/model/field.js +64 -1
- package/dist/core/model/generated.d.ts +4 -2
- package/dist/core/model/model.d.ts +40 -0
- package/dist/core/model/model.js +28 -0
- package/dist/core/model/related.d.ts +17 -0
- package/dist/core/model/related.js +60 -0
- package/dist/core/model/typed.d.ts +107 -0
- package/dist/core/model/typed.js +46 -0
- package/dist/core/money/fx.d.ts +10 -2
- package/dist/core/money/fx.js +17 -2
- package/dist/core/recordset/aggregate.d.ts +22 -0
- package/dist/core/recordset/aggregate.js +258 -0
- package/dist/core/recordset/audit.d.ts +9 -1
- package/dist/core/recordset/audit.js +59 -2
- package/dist/core/recordset/compute.d.ts +2 -0
- package/dist/core/recordset/compute.js +11 -2
- package/dist/core/recordset/domain.d.ts +4 -0
- package/dist/core/recordset/domain.js +74 -2
- package/dist/core/recordset/onchange.js +70 -37
- package/dist/core/recordset/recordset.d.ts +10 -1
- package/dist/core/recordset/recordset.js +80 -14
- package/dist/core/recordset/security.d.ts +15 -1
- package/dist/core/recordset/security.js +95 -10
- package/dist/core/recordset/source.d.ts +9 -0
- package/dist/core/recordset/source.js +19 -0
- package/dist/core/recordset/transitions.js +4 -1
- package/dist/core/recordset/types.d.ts +131 -12
- package/dist/core/recordset/values.d.ts +6 -0
- package/dist/core/recordset/values.js +34 -4
- package/dist/core/recordset/writes.d.ts +6 -1
- package/dist/core/recordset/writes.js +217 -12
- package/dist/core/registry/ddl.d.ts +9 -0
- package/dist/core/registry/ddl.js +49 -2
- package/dist/core/registry/module.d.ts +10 -1
- package/dist/core/registry/module.js +2 -0
- package/dist/core/registry/registry.d.ts +29 -4
- package/dist/core/registry/registry.js +100 -5
- package/dist/core/security/runtime.d.ts +102 -0
- package/dist/core/security/runtime.js +232 -0
- package/dist/driver-pg/driver.d.ts +2 -0
- package/dist/driver-pg/driver.js +1 -0
- package/dist/migrate/apply.d.ts +5 -1
- package/dist/migrate/apply.js +20 -2
- package/dist/migrate/schema.js +40 -2
- package/dist/security/index.d.ts +24 -0
- package/dist/security/index.js +16 -0
- package/dist/sql/tag.d.ts +5 -0
- package/dist/sql/tag.js +29 -1
- package/package.json +1 -1
package/dist/core/env/env.js
CHANGED
|
@@ -2,15 +2,20 @@ var _a;
|
|
|
2
2
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { isRetryable, } from '../../driver-pg/index.js';
|
|
5
|
+
import { InvalidSequenceError } from '../../sequence/index.js';
|
|
5
6
|
import { compile, sql as sqlTag } from '../../sql/index.js';
|
|
6
|
-
import {
|
|
7
|
+
import { refId } from '../data/load.js';
|
|
8
|
+
import { AccessError, CompanyNotAllowedError, ConcurrentUpdateError, FlagNotAllowedError, InvalidIdentityError, NoEnvironmentError, NoRegistryError, TransactionScopeError, } from '../errors.js';
|
|
9
|
+
import { emitEvent, enqueueJob, ensureEventTables } from '../events/events.js';
|
|
10
|
+
import { subscribe, work, } from '../events/workers.js';
|
|
7
11
|
import { createFx } from '../money/fx.js';
|
|
8
|
-
import { trackSuperuser } from '../recordset/audit.js';
|
|
12
|
+
import { trackElevation, trackSecurityChange, trackSuperuser } from '../recordset/audit.js';
|
|
9
13
|
import { invalidateCached } from '../recordset/compute.js';
|
|
10
14
|
import { companyCurrencyId, createRecordCache, currencyById, flushAll, modelRef, } from '../recordset/recordset.js';
|
|
11
|
-
import { assertAccess, canAccess, canField } from '../recordset/security.js';
|
|
15
|
+
import { assertAccess, assertPermission, assertRecords, canAccess, canField, hasPermission, } from '../recordset/security.js';
|
|
12
16
|
import { mapConstraintError } from '../recordset/sqlErrors.js';
|
|
13
|
-
import {
|
|
17
|
+
import { administratorCodes, changeStatement, closureWith, isAdministratorWith, loadRuntimeSecurity, SECURITY_CHANNEL, validateChange, } from '../security/runtime.js';
|
|
18
|
+
import { assertGrants, assertLang, assertReason, resolveIdentity, SYSTEM_UID, } from './identity.js';
|
|
14
19
|
import { assertTimeZone, calendarDateIn } from './time.js';
|
|
15
20
|
const DEFAULT_FLAGS = Object.freeze({
|
|
16
21
|
activeTest: true,
|
|
@@ -48,15 +53,30 @@ export class Env {
|
|
|
48
53
|
/** Allowed company ids (record-rule scope). */
|
|
49
54
|
companyIds;
|
|
50
55
|
lang;
|
|
56
|
+
/** {@link uid} as a `res.users` id, for many2one defaults: `default: (env) => env.userId`. */
|
|
57
|
+
get userId() {
|
|
58
|
+
return this.uid;
|
|
59
|
+
}
|
|
60
|
+
/** {@link companyId} as a `res.company` id. */
|
|
61
|
+
get companyRef() {
|
|
62
|
+
return this.companyId;
|
|
63
|
+
}
|
|
51
64
|
/** The language translatable fields fall back to when `lang` has no text (RFC 0011). */
|
|
52
65
|
sourceLang;
|
|
53
66
|
tz;
|
|
54
67
|
/** Superuser mode: only inside {@link asSuperuser}. */
|
|
55
68
|
su;
|
|
69
|
+
/**
|
|
70
|
+
* The user is in an administrator group (`defineGroup({ administrator: true })`): every ACL, record rule, field
|
|
71
|
+
* group and permission passes, without grants (RFC 0014 §7.9). Company scoping still applies.
|
|
72
|
+
*/
|
|
73
|
+
administrator;
|
|
56
74
|
/** Reason for a job or superuser scope, when given. */
|
|
57
75
|
reason;
|
|
58
76
|
/** The user's security groups, closed over `implies` (RFC 0014 §7.1). */
|
|
59
77
|
groups;
|
|
78
|
+
/** Special permissions of this user on top of the roles (`'account.backdate'`, `'account.move:unlink'`). */
|
|
79
|
+
grants;
|
|
60
80
|
/** @internal Encryption keys. */
|
|
61
81
|
keys;
|
|
62
82
|
flags;
|
|
@@ -75,7 +95,11 @@ export class Env {
|
|
|
75
95
|
this.groups =
|
|
76
96
|
runtime.registry === undefined
|
|
77
97
|
? new Set(identity.groups)
|
|
78
|
-
: runtime.registry.security.
|
|
98
|
+
: closureWith(runtime.registry, runtime.security.current, identity.groups);
|
|
99
|
+
this.administrator =
|
|
100
|
+
runtime.registry !== undefined &&
|
|
101
|
+
isAdministratorWith(runtime.registry, runtime.security.current, this.groups);
|
|
102
|
+
this.grants = new Set(identity.grants);
|
|
79
103
|
this.keys = runtime.keys;
|
|
80
104
|
this.tz = identity.tz;
|
|
81
105
|
this.su = identity.su;
|
|
@@ -90,7 +114,7 @@ export class Env {
|
|
|
90
114
|
const registry = runtime.registry;
|
|
91
115
|
if (registry === undefined)
|
|
92
116
|
throw new NoRegistryError();
|
|
93
|
-
return scopeInternals(this, scope, registry, (q) => this.#query(q), runtime.driver);
|
|
117
|
+
return scopeInternals(this, scope, registry, (q) => this.#query(q), runtime.driver, runtime.security.current);
|
|
94
118
|
});
|
|
95
119
|
Object.freeze(this);
|
|
96
120
|
}
|
|
@@ -108,9 +132,98 @@ export class Env {
|
|
|
108
132
|
return {
|
|
109
133
|
can: (model, perm) => canAccess(scope, scope.registry.get(model).model, perm),
|
|
110
134
|
check: (model, perm) => assertAccess(scope, scope.registry.get(model).model, perm),
|
|
135
|
+
checkRecords: async (model, ids, perm) => {
|
|
136
|
+
const target = scope.registry.get(model).model;
|
|
137
|
+
assertAccess(scope, target, perm);
|
|
138
|
+
await assertRecords(scope, target, ids, perm);
|
|
139
|
+
},
|
|
111
140
|
canField: (model, field, kind) => canField(scope, scope.registry.get(model).model, field, kind),
|
|
141
|
+
has: (code) => hasPermission(scope, code),
|
|
142
|
+
require: (code) => {
|
|
143
|
+
assertPermission(scope, code);
|
|
144
|
+
},
|
|
145
|
+
administratorGroups: () => administratorCodes(scope.registry, scope.overlay),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The record with external id `id` (`'base.main_company'`, RFC 0017), nothing loaded.
|
|
150
|
+
* @throws {UnknownExternalIdError} for an unknown id or a record of another model.
|
|
151
|
+
*/
|
|
152
|
+
async ref(model, id) {
|
|
153
|
+
const resId = await refId(this, model, id);
|
|
154
|
+
return this.model(model).browse([resId]);
|
|
155
|
+
}
|
|
156
|
+
/** The id of the record with external id `id`. @throws {UnknownExternalIdError} */
|
|
157
|
+
async refId(model, id) {
|
|
158
|
+
return refId(this, model, id);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Runtime security administration (RFC 0014 §7.10): roles, model access, record rules and permission grants, on top
|
|
162
|
+
* of the code's declarations. Administrators (or superuser scopes) only; each change is validated against the
|
|
163
|
+
* registry, audited, and reloaded by every process once committed. Needs `createShutro({ runtimeSecurity: true })`.
|
|
164
|
+
*/
|
|
165
|
+
get securityAdmin() {
|
|
166
|
+
const apply = async (change) => {
|
|
167
|
+
const scope = internalsOf(this);
|
|
168
|
+
if (!this.#runtime.security.enabled)
|
|
169
|
+
throw new InvalidIdentityError('Runtime security is not enabled.', 'Pass runtimeSecurity: true to createShutro.');
|
|
170
|
+
if (!this.su && !this.administrator)
|
|
171
|
+
throw new AccessError('security', 'manage', {
|
|
172
|
+
problem: 'only administrators can change roles, access and rules.',
|
|
173
|
+
hint: 'Use an administrator account (defineGroup({ administrator: true })).',
|
|
174
|
+
});
|
|
175
|
+
// Read through this transaction: roles saved earlier in it count.
|
|
176
|
+
const overlay = await loadRuntimeSecurity({
|
|
177
|
+
query: (q) => scope.query(q),
|
|
178
|
+
});
|
|
179
|
+
validateChange(scope.registry, overlay, change);
|
|
180
|
+
await scope.query(changeStatement(change));
|
|
181
|
+
await scope.query(compile(sqlTag `SELECT pg_notify(${SECURITY_CHANNEL}, '')`));
|
|
182
|
+
trackSecurityChange(scope, change);
|
|
183
|
+
this.afterCommit(async () => {
|
|
184
|
+
this.#runtime.security.current = await loadRuntimeSecurity(this.#runtime.driver);
|
|
185
|
+
});
|
|
186
|
+
};
|
|
187
|
+
return {
|
|
188
|
+
saveRole: (role) => apply({ kind: 'role', ...role }),
|
|
189
|
+
deleteRole: (code) => apply({ kind: 'deleteRole', code }),
|
|
190
|
+
setAccess: (role, model, perms) => apply({ kind: 'access', role, model, perms }),
|
|
191
|
+
saveRule: (rule) => apply({ kind: 'rule', ...rule }),
|
|
192
|
+
deleteRule: (name) => apply({ kind: 'deleteRule', name }),
|
|
193
|
+
grantPermission: (role, permission) => apply({ kind: 'permission', role, permission }),
|
|
194
|
+
revokePermission: (role, permission) => apply({ kind: 'revokePermission', role, permission }),
|
|
195
|
+
setFieldGroups: (model, field, groups) => apply({
|
|
196
|
+
kind: 'fields',
|
|
197
|
+
model,
|
|
198
|
+
field,
|
|
199
|
+
read: [...(groups.read ?? [])],
|
|
200
|
+
write: [...(groups.write ?? [])],
|
|
201
|
+
}),
|
|
112
202
|
};
|
|
113
203
|
}
|
|
204
|
+
/**
|
|
205
|
+
* Emits a domain event in this transaction (RFC 0018 §7.2): it exists if and only if the transaction commits, and
|
|
206
|
+
* subscribers (`shutro.subscribe`) receive it at least once. Returns the event id.
|
|
207
|
+
*/
|
|
208
|
+
async emit(topic, payload) {
|
|
209
|
+
const scope = internalsOf(this);
|
|
210
|
+
const query = (q) => scope.query(q);
|
|
211
|
+
await ensureEventTables(this.#runtime.driver, query);
|
|
212
|
+
return emitEvent(query, this.#actor(), topic, payload);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Enqueues a background job in this transaction (RFC 0018 §7.3), run by `shutro.work` as this user, with
|
|
216
|
+
* retries. With `key`, a job already pending or running under that key makes this a no-op (returns `null`).
|
|
217
|
+
*/
|
|
218
|
+
async enqueue(name, payload, options) {
|
|
219
|
+
const scope = internalsOf(this);
|
|
220
|
+
const query = (q) => scope.query(q);
|
|
221
|
+
await ensureEventTables(this.#runtime.driver, query);
|
|
222
|
+
return enqueueJob(query, this.#actor(), name, payload, options);
|
|
223
|
+
}
|
|
224
|
+
#actor() {
|
|
225
|
+
return { uid: this.uid, companyId: this.companyId, groups: [...this.groups] };
|
|
226
|
+
}
|
|
114
227
|
/** Dated, per-company currency conversion (RFC 0006 §7.6). Needs a `res.currency.rate` model. */
|
|
115
228
|
get fx() {
|
|
116
229
|
const scope = internalsOf(this);
|
|
@@ -227,6 +340,30 @@ export class Env {
|
|
|
227
340
|
: Object.freeze([...this.companyIds, company]);
|
|
228
341
|
return this.#derive({ companyId: company, companyIds });
|
|
229
342
|
}
|
|
343
|
+
/**
|
|
344
|
+
* Drops clean records from this scope's cache (all models, or one): for long reads in one transaction, such as
|
|
345
|
+
* streaming an export of millions of rows page by page, so memory stays bounded. Records with unsaved changes or
|
|
346
|
+
* pending computes and checks are kept; dropped records are simply loaded again when read.
|
|
347
|
+
*/
|
|
348
|
+
releaseCache(model) {
|
|
349
|
+
const scope = internalsOf(this);
|
|
350
|
+
const root = this.#scope.root;
|
|
351
|
+
for (const name of model === undefined ? [...root.cache.records.keys()] : [model]) {
|
|
352
|
+
const byId = root.cache.records.get(name);
|
|
353
|
+
if (byId === undefined)
|
|
354
|
+
continue;
|
|
355
|
+
const pending = (sets) => [...(sets.get(name)?.values() ?? [])].flatMap((set) => [...set]);
|
|
356
|
+
const keep = new Set([
|
|
357
|
+
...(root.dirty.get(name)?.keys() ?? []),
|
|
358
|
+
...pending(root.triggers),
|
|
359
|
+
...pending(root.toCompute),
|
|
360
|
+
...pending(root.toCheck),
|
|
361
|
+
]);
|
|
362
|
+
for (const id of [...byId.keys()])
|
|
363
|
+
if (!keep.has(id))
|
|
364
|
+
scope.forget(name, id);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
230
367
|
/** The same scope with another language. */
|
|
231
368
|
withLang(lang) {
|
|
232
369
|
return this.#derive({ lang: assertLang(lang) });
|
|
@@ -242,6 +379,68 @@ export class Env {
|
|
|
242
379
|
throw new FlagNotAllowedError('checkCompany');
|
|
243
380
|
return this.#derive({ flags: Object.freeze({ ...this.flags, ...flags }) });
|
|
244
381
|
}
|
|
382
|
+
/**
|
|
383
|
+
* Runs `fn` reading the past (RFC 0018 §7.4): models with `history: true` are searched and loaded as they were at
|
|
384
|
+
* `instant` (rules, field groups and company scope apply as now); other models are read as they are now. The
|
|
385
|
+
* environment has its own cache and is read-only: writes are refused.
|
|
386
|
+
*
|
|
387
|
+
* ```ts
|
|
388
|
+
* const atClose = await env.asOf(new Date('2026-09-30T23:59:59Z'), (past) => past.model('account.move').search({ where: { state: 'posted' } }).then((m) => m.read(['name', 'amountTotal'])));
|
|
389
|
+
* ```
|
|
390
|
+
*/
|
|
391
|
+
async asOf(instant, fn) {
|
|
392
|
+
this.#assertUsable();
|
|
393
|
+
if (!(instant instanceof Date) || Number.isNaN(instant.getTime()))
|
|
394
|
+
throw new InvalidIdentityError('asOf() needs a valid Date.', "Pass the instant to read, e.g. new Date('2026-09-30T23:59:59Z').");
|
|
395
|
+
const parent = this.#scope;
|
|
396
|
+
const root = {
|
|
397
|
+
...parent.root,
|
|
398
|
+
top: undefined,
|
|
399
|
+
cache: createRecordCache(),
|
|
400
|
+
dirty: new Map(),
|
|
401
|
+
triggers: new Map(),
|
|
402
|
+
toCompute: new Map(),
|
|
403
|
+
toCheck: new Map(),
|
|
404
|
+
audit: [],
|
|
405
|
+
compute: {
|
|
406
|
+
recomputing: false,
|
|
407
|
+
computing: new Set(),
|
|
408
|
+
protected: new Map(),
|
|
409
|
+
previous: new Map(),
|
|
410
|
+
},
|
|
411
|
+
asOf: instant,
|
|
412
|
+
};
|
|
413
|
+
const scope = { ...parent, root, afterCommit: [], onRollback: [], journal: undefined };
|
|
414
|
+
root.top = scope;
|
|
415
|
+
const past = this.#derive({ readOnly: true }, scope);
|
|
416
|
+
scope.env = past;
|
|
417
|
+
try {
|
|
418
|
+
return await this.#runtime.als.run(scope, () => fn(past));
|
|
419
|
+
}
|
|
420
|
+
finally {
|
|
421
|
+
parent.root.queries += root.queries;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Runs `fn` with extra special grants in the same scope (RFC 0014 §7.9): a narrow, audited alternative to
|
|
426
|
+
* {@link asSuperuser} for code that must touch a model or feature its caller cannot. Record rules, field groups
|
|
427
|
+
* and company scoping still apply; only the named grants are added, and only inside `fn`.
|
|
428
|
+
*
|
|
429
|
+
* ```ts
|
|
430
|
+
* await env.withGrants({ grants: ['sale.order.line:read'], reason: 'invoice from orders' }, (e) => ...);
|
|
431
|
+
* ```
|
|
432
|
+
*/
|
|
433
|
+
async withGrants(options, fn) {
|
|
434
|
+
const reason = assertReason(options.reason);
|
|
435
|
+
const grants = assertGrants(options.grants);
|
|
436
|
+
this.#assertUsable();
|
|
437
|
+
const elevated = this.#derive({
|
|
438
|
+
grants: Object.freeze([...new Set([...this.grants, ...grants])]),
|
|
439
|
+
});
|
|
440
|
+
if (this.#runtime.registry !== undefined)
|
|
441
|
+
trackElevation(internalsOf(elevated), grants, reason);
|
|
442
|
+
return fn(elevated);
|
|
443
|
+
}
|
|
245
444
|
/**
|
|
246
445
|
* Runs `fn` with a superuser environment in the same scope. The elevation never leaks: only `su` and values
|
|
247
446
|
* returned by `fn` leave the callback, and `reason` is recorded for the audit trail (RFC 0003 §7.6).
|
|
@@ -253,7 +452,7 @@ export class Env {
|
|
|
253
452
|
if (this.#runtime.registry !== undefined)
|
|
254
453
|
trackSuperuser(internalsOf(su), reason);
|
|
255
454
|
// RLS policies read shutro.su: the setting is scoped to the call (RFC 0014 §7.5).
|
|
256
|
-
const wasSu = this.su;
|
|
455
|
+
const wasSu = this.su || this.administrator; // administrators already pass RLS (shutro.su = 1)
|
|
257
456
|
if (!wasSu)
|
|
258
457
|
await this.#query(compile(sqlTag `SELECT set_config(${'shutro.su'}, ${'1'}, true)`));
|
|
259
458
|
try {
|
|
@@ -294,6 +493,7 @@ export class Env {
|
|
|
294
493
|
tz: this.tz,
|
|
295
494
|
reason: this.reason,
|
|
296
495
|
groups: [...this.groups],
|
|
496
|
+
grants: [...this.grants],
|
|
297
497
|
su: this.su,
|
|
298
498
|
flags: this.flags,
|
|
299
499
|
readOnly: this.readOnly,
|
|
@@ -315,7 +515,7 @@ export class Env {
|
|
|
315
515
|
}
|
|
316
516
|
}
|
|
317
517
|
_a = Env;
|
|
318
|
-
function scopeInternals(env, scope, registry, query, driver) {
|
|
518
|
+
function scopeInternals(env, scope, registry, query, driver, overlay) {
|
|
319
519
|
const root = scope.root;
|
|
320
520
|
const dirtyOf = (model, id) => root.dirty.get(model)?.get(id);
|
|
321
521
|
const addIds = (sets, model, key, ids) => {
|
|
@@ -335,6 +535,8 @@ function scopeInternals(env, scope, registry, query, driver) {
|
|
|
335
535
|
const self = {
|
|
336
536
|
env,
|
|
337
537
|
registry,
|
|
538
|
+
overlay,
|
|
539
|
+
asOf: root.asOf,
|
|
338
540
|
cache: root.cache,
|
|
339
541
|
uid: root.uid,
|
|
340
542
|
now: root.now,
|
|
@@ -499,10 +701,33 @@ const defaultHookError = (error, phase) => {
|
|
|
499
701
|
process.emitWarning(`Shutro ${phase} hook failed: ${message}`, { code: 'SHUTRO_HOOK_FAILED' });
|
|
500
702
|
};
|
|
501
703
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
704
|
+
/**
|
|
705
|
+
* Standard sequences allocate in a short autonomous transaction on a second connection (RFC 0012 §7.3): with a pool
|
|
706
|
+
* of one, that waits forever for the connection the business transaction holds (feedback #21).
|
|
707
|
+
*/
|
|
708
|
+
function assertPoolFits(options) {
|
|
709
|
+
if (options.driver.max === undefined || options.driver.max > 1)
|
|
710
|
+
return;
|
|
711
|
+
const registry = options.registry;
|
|
712
|
+
const standard = [...(registry?.sequences.values() ?? [])]
|
|
713
|
+
.filter((d) => !d.gapless)
|
|
714
|
+
.map((d) => d.code);
|
|
715
|
+
if (standard.length === 0)
|
|
716
|
+
return;
|
|
717
|
+
throw new InvalidSequenceError(`Sequence(s) ${standard.join(', ')} need a pool of at least 2 connections; the driver has max: 1.`, 'Raise the driver max, or declare the sequences gapless: true (allocated inside the business transaction).');
|
|
718
|
+
}
|
|
719
|
+
function workerHost(shutro) {
|
|
720
|
+
return {
|
|
721
|
+
driver: shutro.driver,
|
|
722
|
+
run: (o, fn) => shutro.run(o, fn),
|
|
723
|
+
bootstrap: (o, fn) => shutro.bootstrap(o, fn),
|
|
724
|
+
};
|
|
725
|
+
}
|
|
502
726
|
/** Creates a {@link Shutro} instance on a driver (and a registry). */
|
|
503
727
|
export function createShutro(options) {
|
|
504
728
|
const attempts = options.retry?.attempts ?? 5;
|
|
505
729
|
const backoff = options.retry?.backoffMs ?? defaultBackoff;
|
|
730
|
+
assertPoolFits(options);
|
|
506
731
|
const runtime = {
|
|
507
732
|
als: new AsyncLocalStorage(),
|
|
508
733
|
onHookError: options.onHookError ?? defaultHookError,
|
|
@@ -511,10 +736,27 @@ export function createShutro(options) {
|
|
|
511
736
|
driver: options.driver,
|
|
512
737
|
keys: options.keys,
|
|
513
738
|
inspector: options.inspector,
|
|
739
|
+
security: { enabled: options.runtimeSecurity === true, current: undefined, loading: undefined },
|
|
514
740
|
};
|
|
515
741
|
const NOW = compile(sqlTag `SELECT now() AS now`);
|
|
742
|
+
const reload = async () => {
|
|
743
|
+
runtime.security.current = await loadRuntimeSecurity(options.driver);
|
|
744
|
+
};
|
|
745
|
+
const ensureSecurity = async () => {
|
|
746
|
+
if (!runtime.security.enabled || runtime.security.current !== undefined)
|
|
747
|
+
return;
|
|
748
|
+
runtime.security.loading ??= (async () => {
|
|
749
|
+
await reload();
|
|
750
|
+
// Every process reloads when any of them commits a change.
|
|
751
|
+
await options.driver.listen(SECURITY_CHANNEL, () => {
|
|
752
|
+
reload().catch((error) => runtime.onHookError(error, 'afterCommit'));
|
|
753
|
+
});
|
|
754
|
+
})();
|
|
755
|
+
await runtime.security.loading;
|
|
756
|
+
};
|
|
516
757
|
return {
|
|
517
758
|
async run(runOptions, fn) {
|
|
759
|
+
await ensureSecurity();
|
|
518
760
|
let identity = resolveIdentity(runOptions);
|
|
519
761
|
if (options.identity !== undefined) {
|
|
520
762
|
const verified = await options.identity(identity.uid);
|
|
@@ -532,11 +774,59 @@ export function createShutro(options) {
|
|
|
532
774
|
throw new InvalidIdentityError(`User ${identity.uid} is not in group(s) ${extra.join(', ')}.`, 'Pass only groups the user has (or omit groups to use the loaded ones).');
|
|
533
775
|
}
|
|
534
776
|
}
|
|
535
|
-
|
|
777
|
+
const askedGrants = runOptions.grants;
|
|
778
|
+
const extraGrants = (askedGrants ?? []).filter((g) => !(verified.grants ?? []).includes(g));
|
|
779
|
+
if (extraGrants.length > 0) {
|
|
780
|
+
throw new InvalidIdentityError(`User ${identity.uid} does not have the grant(s) ${extraGrants.join(', ')}.`, 'Pass only grants the user has (or omit grants to use the loaded ones).');
|
|
781
|
+
}
|
|
782
|
+
identity = {
|
|
783
|
+
...identity,
|
|
784
|
+
groups: Object.freeze([...(asked ?? verified.groups)]),
|
|
785
|
+
grants: Object.freeze([...(askedGrants ?? verified.grants ?? [])]),
|
|
786
|
+
};
|
|
536
787
|
}
|
|
788
|
+
return execute(identity, runOptions, fn);
|
|
789
|
+
},
|
|
790
|
+
async bootstrap(bootstrapOptions, fn) {
|
|
791
|
+
const reason = assertReason(bootstrapOptions.reason);
|
|
792
|
+
const company = bootstrapOptions.company === undefined
|
|
793
|
+
? SYSTEM_UID
|
|
794
|
+
: resolveIdentity({ user: 1, company: bootstrapOptions.company }).companyId;
|
|
795
|
+
const identity = {
|
|
796
|
+
uid: SYSTEM_UID,
|
|
797
|
+
companyId: company,
|
|
798
|
+
companyIds: Object.freeze([company]),
|
|
799
|
+
lang: 'en_US',
|
|
800
|
+
tz: 'UTC',
|
|
801
|
+
reason,
|
|
802
|
+
groups: Object.freeze([]),
|
|
803
|
+
grants: Object.freeze([]),
|
|
804
|
+
};
|
|
805
|
+
return execute(identity, { user: 1, company: 1 }, (env) => env.asSuperuser({ reason }, fn));
|
|
806
|
+
},
|
|
807
|
+
registry: options.registry,
|
|
808
|
+
driver: options.driver,
|
|
809
|
+
reloadSecurity: reload,
|
|
810
|
+
subscribe(name, topic, handler, subscribeOptions) {
|
|
811
|
+
return subscribe(workerHost(this), name, topic, handler, subscribeOptions);
|
|
812
|
+
},
|
|
813
|
+
work(handlers, workOptions) {
|
|
814
|
+
return work(workerHost(this), handlers, workOptions);
|
|
815
|
+
},
|
|
816
|
+
currentEnv() {
|
|
817
|
+
const scope = runtime.als.getStore();
|
|
818
|
+
if (scope === undefined)
|
|
819
|
+
throw new NoEnvironmentError();
|
|
820
|
+
return scope.env;
|
|
821
|
+
},
|
|
822
|
+
};
|
|
823
|
+
async function execute(identity, runOptions, fn) {
|
|
824
|
+
{
|
|
537
825
|
const groups = options.registry === undefined
|
|
538
826
|
? new Set(identity.groups)
|
|
539
|
-
: options.registry.security.
|
|
827
|
+
: closureWith(options.registry, runtime.security.current, identity.groups);
|
|
828
|
+
const administrator = options.registry !== undefined &&
|
|
829
|
+
isAdministratorWith(options.registry, runtime.security.current, groups);
|
|
540
830
|
const maxAttempts = runOptions.retry === false ? 1 : attempts;
|
|
541
831
|
for (let attempt = 1;; attempt++) {
|
|
542
832
|
let scope;
|
|
@@ -549,7 +839,8 @@ export function createShutro(options) {
|
|
|
549
839
|
'shutro.company_id': String(identity.companyId),
|
|
550
840
|
'shutro.company_ids': `{${identity.companyIds.join(',')}}`,
|
|
551
841
|
'shutro.groups': [...groups].join(','),
|
|
552
|
-
|
|
842
|
+
// Administrators pass every RLS policy, like superuser scopes (RFC 0014 §7.9).
|
|
843
|
+
'shutro.su': administrator ? '1' : '0',
|
|
553
844
|
timezone: 'UTC',
|
|
554
845
|
},
|
|
555
846
|
}, async (conn) => {
|
|
@@ -620,12 +911,6 @@ export function createShutro(options) {
|
|
|
620
911
|
await sleep(backoff(attempt + 1));
|
|
621
912
|
}
|
|
622
913
|
}
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
const scope = runtime.als.getStore();
|
|
626
|
-
if (scope === undefined)
|
|
627
|
-
throw new NoEnvironmentError();
|
|
628
|
-
return scope.env;
|
|
629
|
-
},
|
|
630
|
-
};
|
|
914
|
+
}
|
|
915
|
+
}
|
|
631
916
|
}
|
|
@@ -14,6 +14,11 @@ export interface Identity {
|
|
|
14
14
|
readonly reason?: string;
|
|
15
15
|
/** Security group codes of the user (RFC 0014 §7.1); implied groups are added by the registry. */
|
|
16
16
|
readonly groups?: readonly string[];
|
|
17
|
+
/**
|
|
18
|
+
* Special permissions of this user on top of the roles (RFC 0014 §7.9): feature permission codes
|
|
19
|
+
* (`'account.backdate'`) and model operations (`'account.move:unlink'`).
|
|
20
|
+
*/
|
|
21
|
+
readonly grants?: readonly string[];
|
|
17
22
|
}
|
|
18
23
|
/** A validated identity with defaults applied. */
|
|
19
24
|
export interface ResolvedIdentity {
|
|
@@ -24,7 +29,12 @@ export interface ResolvedIdentity {
|
|
|
24
29
|
readonly tz: string;
|
|
25
30
|
readonly reason: string | undefined;
|
|
26
31
|
readonly groups: readonly string[];
|
|
32
|
+
readonly grants: readonly string[];
|
|
27
33
|
}
|
|
34
|
+
/** The acting uid of `Shutro.bootstrap` scopes: no `res.users` row, so `created_by` / `updated_by` are `NULL`. */
|
|
35
|
+
export declare const SYSTEM_UID = 0;
|
|
36
|
+
/** Validates special grants (`'account.backdate'`, `'account.move:unlink'`). @throws {InvalidIdentityError} */
|
|
37
|
+
export declare function assertGrants(grants: readonly unknown[]): readonly string[];
|
|
28
38
|
/** Validates a language code (`'en_US'`, `'bn_BD'`). @throws {InvalidIdentityError} */
|
|
29
39
|
export declare function assertLang(lang: string): string;
|
|
30
40
|
/** Validates `reason` for superuser scopes and jobs. @throws {InvalidIdentityError} */
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { InvalidIdentityError } from '../errors.js';
|
|
2
2
|
import { assertTimeZone } from './time.js';
|
|
3
|
+
/** The acting uid of `Shutro.bootstrap` scopes: no `res.users` row, so `created_by` / `updated_by` are `NULL`. */
|
|
4
|
+
export const SYSTEM_UID = 0;
|
|
5
|
+
const GRANT = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+(:(read|write|create|unlink|export|import))?$/;
|
|
3
6
|
const LANG = /^[a-z]{2,3}_[A-Z]{2}$/;
|
|
4
7
|
function assertId(value, what) {
|
|
5
8
|
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
|
|
@@ -7,6 +10,14 @@ function assertId(value, what) {
|
|
|
7
10
|
}
|
|
8
11
|
return value;
|
|
9
12
|
}
|
|
13
|
+
/** Validates special grants (`'account.backdate'`, `'account.move:unlink'`). @throws {InvalidIdentityError} */
|
|
14
|
+
export function assertGrants(grants) {
|
|
15
|
+
return Object.freeze(grants.map((g) => {
|
|
16
|
+
if (typeof g !== 'string' || !GRANT.test(g))
|
|
17
|
+
throw new InvalidIdentityError(`${JSON.stringify(g)} is not a grant.`, "Grant a permission code ('account.backdate') or a model operation ('account.move:unlink').");
|
|
18
|
+
return g;
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
10
21
|
/** Validates a language code (`'en_US'`, `'bn_BD'`). @throws {InvalidIdentityError} */
|
|
11
22
|
export function assertLang(lang) {
|
|
12
23
|
if (!LANG.test(lang)) {
|
|
@@ -40,6 +51,11 @@ export function resolveIdentity(identity) {
|
|
|
40
51
|
lang: assertLang(identity.lang ?? 'en_US'),
|
|
41
52
|
tz,
|
|
42
53
|
reason: identity.reason === undefined ? undefined : assertReason(identity.reason),
|
|
54
|
+
grants: Object.freeze([...(identity.grants ?? [])].map((g) => {
|
|
55
|
+
if (typeof g !== 'string' || !GRANT.test(g))
|
|
56
|
+
throw new InvalidIdentityError(`${JSON.stringify(g)} is not a grant.`, "Grant a permission code ('account.backdate') or a model operation ('account.move:unlink').");
|
|
57
|
+
return g;
|
|
58
|
+
})),
|
|
43
59
|
groups: Object.freeze([...(identity.groups ?? [])].map((g) => {
|
|
44
60
|
if (typeof g !== 'string' || g === '')
|
|
45
61
|
throw new InvalidIdentityError(`${JSON.stringify(g)} is not a group code.`, "Pass group codes such as 'sale.user'.");
|
package/dist/core/errors.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Machine-readable reason for a {@link ShutroError}. */
|
|
2
|
-
export type ShutroErrorCode = 'NON_INTEGER_NUMBER' | 'INVALID_DECIMAL' | 'DIVISION_BY_ZERO' | 'INVALID_CURRENCY' | 'CURRENCY_MISMATCH' | 'INVALID_ALLOCATION' | 'MONEY_EMPTY_SUM' | 'INVALID_UOM' | 'UOM_MISMATCH' | 'UOM_CATEGORY_MISMATCH' | 'NO_ENVIRONMENT' | 'TRANSACTION_SCOPE' | 'CONCURRENT_UPDATE' | 'INVALID_IDENTITY' | 'COMPANY_NOT_ALLOWED' | 'FLAG_NOT_ALLOWED' | 'INVALID_FIELD' | 'INVALID_MODEL' | 'INVALID_MODULE' | 'DUPLICATE_MODULE' | 'DUPLICATE_MODEL' | 'UNDECLARED_DEPENDENCY' | 'UNKNOWN_MODEL' | 'INVALID_RELATION' | 'INVALID_DEPENDS_PATH' | 'FIELD_NOT_LOADED' | 'SINGLETON' | 'MISSING_RECORD' | 'INVALID_DOMAIN' | 'NO_REGISTRY' | 'VALIDATION' | 'INVALID_EXTENSION' | 'EXTENSION_CONFLICT' | 'COMPUTE_CYCLE' | 'COMPUTE_ASSIGNMENT' | 'RECOMPUTE_LIMIT' | 'CONSTRAINT' | 'CONSTRAINT_VIOLATION' | 'INVALID_TRANSITION' | 'TRANSITION_GUARD' | 'CROSS_COMPANY' | 'MISSING_RATE' | 'UNKNOWN_SEQUENCE' | 'ACCESS';
|
|
2
|
+
export type ShutroErrorCode = 'NON_INTEGER_NUMBER' | 'INVALID_DECIMAL' | 'DIVISION_BY_ZERO' | 'INVALID_CURRENCY' | 'CURRENCY_MISMATCH' | 'INVALID_ALLOCATION' | 'MONEY_EMPTY_SUM' | 'INVALID_UOM' | 'UOM_MISMATCH' | 'UOM_CATEGORY_MISMATCH' | 'NO_ENVIRONMENT' | 'TRANSACTION_SCOPE' | 'CONCURRENT_UPDATE' | 'INVALID_IDENTITY' | 'COMPANY_NOT_ALLOWED' | 'FLAG_NOT_ALLOWED' | 'INVALID_FIELD' | 'INVALID_MODEL' | 'INVALID_MODULE' | 'DUPLICATE_MODULE' | 'DUPLICATE_MODEL' | 'UNDECLARED_DEPENDENCY' | 'UNKNOWN_MODEL' | 'INVALID_RELATION' | 'INVALID_DEPENDS_PATH' | 'FIELD_NOT_LOADED' | 'SINGLETON' | 'MISSING_RECORD' | 'UNKNOWN_EXTERNAL_ID' | 'STALE_RECORD' | 'INVALID_DOMAIN' | 'NO_REGISTRY' | 'VALIDATION' | 'INVALID_EXTENSION' | 'EXTENSION_CONFLICT' | 'COMPUTE_CYCLE' | 'COMPUTE_ASSIGNMENT' | 'RECOMPUTE_LIMIT' | 'CONSTRAINT' | 'CONSTRAINT_VIOLATION' | 'INVALID_TRANSITION' | 'TRANSITION_GUARD' | 'CROSS_COMPANY' | 'MISSING_RATE' | 'UNKNOWN_SEQUENCE' | 'ACCESS';
|
|
3
3
|
/**
|
|
4
4
|
* Base class of every error raised by `@shutro/core`. The message says what went wrong and ends with
|
|
5
5
|
* {@link ShutroError.hint}, which says how to fix it (`CLAUDE.md` coding rules).
|
|
@@ -121,6 +121,20 @@ export declare class SingletonError extends ShutroError {
|
|
|
121
121
|
export declare class MissingRecordError extends ShutroError {
|
|
122
122
|
constructor(model: string, ids: readonly number[]);
|
|
123
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* A compare-and-set write found records changed since they were read (lost-update protection, RFC 0018 §7.1):
|
|
126
|
+
* someone else saved first.
|
|
127
|
+
*/
|
|
128
|
+
export declare class StaleRecordError extends ShutroError {
|
|
129
|
+
readonly model: string;
|
|
130
|
+
readonly records: readonly number[];
|
|
131
|
+
readonly fields: readonly string[];
|
|
132
|
+
constructor(model: string, records: readonly number[], fields: readonly string[]);
|
|
133
|
+
}
|
|
134
|
+
/** An external id (`module.name`, RFC 0017) that does not exist, or names a record of another model. */
|
|
135
|
+
export declare class UnknownExternalIdError extends ShutroError {
|
|
136
|
+
constructor(problem: string, hint: string);
|
|
137
|
+
}
|
|
124
138
|
/** A search domain that can't be compiled (RFC 0005 §7.1). */
|
|
125
139
|
export declare class InvalidDomainError extends ShutroError {
|
|
126
140
|
constructor(problem: string, hint: string);
|
package/dist/core/errors.js
CHANGED
|
@@ -180,6 +180,27 @@ export class MissingRecordError extends ShutroError {
|
|
|
180
180
|
super('MISSING_RECORD', `${model} record(s) ${ids.join(', ')} do not exist or are not accessible.`, 'The id may come from stale data or another company; search for the record instead of browsing a remembered id.');
|
|
181
181
|
}
|
|
182
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* A compare-and-set write found records changed since they were read (lost-update protection, RFC 0018 §7.1):
|
|
185
|
+
* someone else saved first.
|
|
186
|
+
*/
|
|
187
|
+
export class StaleRecordError extends ShutroError {
|
|
188
|
+
model;
|
|
189
|
+
records;
|
|
190
|
+
fields;
|
|
191
|
+
constructor(model, records, fields) {
|
|
192
|
+
super('STALE_RECORD', `${model} record(s) ${records.join(', ')} changed since they were read (${fields.join(', ')}).`, 'Someone else saved first: reload the record, reapply the change, and save again.');
|
|
193
|
+
this.model = model;
|
|
194
|
+
this.records = Object.freeze([...records]);
|
|
195
|
+
this.fields = Object.freeze([...fields]);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** An external id (`module.name`, RFC 0017) that does not exist, or names a record of another model. */
|
|
199
|
+
export class UnknownExternalIdError extends ShutroError {
|
|
200
|
+
constructor(problem, hint) {
|
|
201
|
+
super('UNKNOWN_EXTERNAL_ID', problem, hint);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
183
204
|
/** A search domain that can't be compiled (RFC 0005 §7.1). */
|
|
184
205
|
export class InvalidDomainError extends ShutroError {
|
|
185
206
|
constructor(problem, hint) {
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transactional events and jobs (RFC 0018 §7.2–§7.3). `env.emit` / `env.enqueue` insert in the business transaction,
|
|
3
|
+
* so events and jobs exist if and only if their transaction committed. Workers run each event or job inside a
|
|
4
|
+
* `run()` scope as the user who emitted / enqueued it; the subscription cursor advances, or the job is marked done,
|
|
5
|
+
* in that same transaction: database effects of a handler happen exactly once.
|
|
6
|
+
*/
|
|
7
|
+
import type { Driver } from '../../driver-pg/index.js';
|
|
8
|
+
export declare const OUTBOX_CHANNEL = "shutro_outbox";
|
|
9
|
+
export declare const JOB_CHANNEL = "shutro_job";
|
|
10
|
+
/** Statements creating the event and job tables (also created on first use). */
|
|
11
|
+
export declare function eventTableStatements(): readonly {
|
|
12
|
+
readonly text: string;
|
|
13
|
+
readonly params: readonly [];
|
|
14
|
+
}[];
|
|
15
|
+
type Query = <R extends Record<string, unknown>>(q: {
|
|
16
|
+
text: string;
|
|
17
|
+
params: readonly unknown[];
|
|
18
|
+
}) => Promise<readonly R[]>;
|
|
19
|
+
/** Creates the tables once per driver (or per query function). */
|
|
20
|
+
export declare function ensureEventTables(owner: object, query: Query): Promise<void>;
|
|
21
|
+
/** Who emitted / enqueued: handlers run as them. */
|
|
22
|
+
export interface Actor {
|
|
23
|
+
readonly uid: number;
|
|
24
|
+
readonly companyId: number;
|
|
25
|
+
readonly groups: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
/** `env.emit`: inserts the event in the current transaction. */
|
|
28
|
+
export declare function emitEvent(query: Query, actor: Actor, topic: string, payload: unknown): Promise<number>;
|
|
29
|
+
/** Options of `env.enqueue`. */
|
|
30
|
+
export interface EnqueueOptions {
|
|
31
|
+
/** Not before this instant. */
|
|
32
|
+
readonly runAt?: Date;
|
|
33
|
+
/** Deduplication: while a job with this key is pending or running, enqueueing it again does nothing. */
|
|
34
|
+
readonly key?: string;
|
|
35
|
+
/** Attempts before the job is marked `dead` (default 5). */
|
|
36
|
+
readonly attempts?: number;
|
|
37
|
+
}
|
|
38
|
+
/** `env.enqueue`: inserts the job in the current transaction. Returns its id, or `null` when deduplicated. */
|
|
39
|
+
export declare function enqueueJob(query: Query, actor: Actor, name: string, payload: unknown, options?: EnqueueOptions): Promise<number | null>;
|
|
40
|
+
/** Exponential backoff with a cap, in milliseconds (attempt 1 → 1 s, 2 → 2 s, … ≤ 10 min). */
|
|
41
|
+
export declare function backoffMs(attempt: number): number;
|
|
42
|
+
/** Releases jobs whose worker died while running them (locked longer than `staleMs`). */
|
|
43
|
+
export declare function releaseStale(driver: Driver, staleMs: number): Promise<number>;
|
|
44
|
+
export {};
|