shutro 0.3.1 → 0.3.3
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/dist/core/data/load.d.ts +9 -0
- package/dist/core/data/load.js +27 -0
- package/dist/core/env/env.d.ts +11 -1
- package/dist/core/env/env.js +23 -5
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.js +1 -1
- package/dist/core/recordset/onchange.js +35 -0
- package/dist/core/security/runtime.d.ts +22 -0
- package/dist/core/security/runtime.js +33 -0
- package/package.json +1 -1
package/dist/core/data/load.d.ts
CHANGED
|
@@ -9,6 +9,15 @@ export declare function externalIdTableStatements(): readonly {
|
|
|
9
9
|
}[];
|
|
10
10
|
/** `env.refId(model, id)`. */
|
|
11
11
|
export declare function refId<M extends string>(env: Env, model: M, id: string): Promise<Id<M>>;
|
|
12
|
+
/**
|
|
13
|
+
* `env.setExternalId(model, id, externalId)` (RFC 0017 §4): names a record outside module data, as an import does
|
|
14
|
+
* (`__import__.partner_42`), so a later file can find it again with `env.refId`. The module part may not be an
|
|
15
|
+
* installed module's: those ids are its data, deleted by `loadData` when no longer declared. The record must exist
|
|
16
|
+
* and be readable in the scope. Naming the same record again does nothing; an id that names another record is
|
|
17
|
+
* refused. The row commits or rolls back with the scope's transaction.
|
|
18
|
+
* @throws {UnknownExternalIdError} for a malformed id, a module's id, an unreadable record or an id already taken
|
|
19
|
+
*/
|
|
20
|
+
export declare function setExternalId(env: Env, model: string, id: number, externalId: string): Promise<void>;
|
|
12
21
|
/** What {@link loadData} did for one module. */
|
|
13
22
|
export interface DataLoadResult {
|
|
14
23
|
readonly module: string;
|
package/dist/core/data/load.js
CHANGED
|
@@ -55,6 +55,33 @@ async function resolveExternalId(internals, id, model) {
|
|
|
55
55
|
export async function refId(env, model, id) {
|
|
56
56
|
return (await resolveExternalId(internalsOf(env), id, model));
|
|
57
57
|
}
|
|
58
|
+
const MODULE_PART = /^[a-z0-9_]+$/;
|
|
59
|
+
/**
|
|
60
|
+
* `env.setExternalId(model, id, externalId)` (RFC 0017 §4): names a record outside module data, as an import does
|
|
61
|
+
* (`__import__.partner_42`), so a later file can find it again with `env.refId`. The module part may not be an
|
|
62
|
+
* installed module's: those ids are its data, deleted by `loadData` when no longer declared. The record must exist
|
|
63
|
+
* and be readable in the scope. Naming the same record again does nothing; an id that names another record is
|
|
64
|
+
* refused. The row commits or rolls back with the scope's transaction.
|
|
65
|
+
* @throws {UnknownExternalIdError} for a malformed id, a module's id, an unreadable record or an id already taken
|
|
66
|
+
*/
|
|
67
|
+
export async function setExternalId(env, model, id, externalId) {
|
|
68
|
+
const internals = internalsOf(env);
|
|
69
|
+
const [module, name] = split(externalId);
|
|
70
|
+
if (!externalId.includes('.') || !MODULE_PART.test(module) || name === '')
|
|
71
|
+
throw new UnknownExternalIdError(`'${externalId}' is not an external id.`, 'Write it as module.name, e.g. __import__.partner_42.');
|
|
72
|
+
if (internals.registry.modules.some((m) => m.name === module))
|
|
73
|
+
throw new UnknownExternalIdError(`The external id '${externalId}' belongs to the module '${module}': its ids are its data.`, 'Use a module part no installed module has, e.g. __import__.');
|
|
74
|
+
const records = env.model(model);
|
|
75
|
+
const visible = await records.search({ where: { id }, limit: 1 });
|
|
76
|
+
if (visible.length === 0)
|
|
77
|
+
throw new UnknownExternalIdError(`No ${model} record ${id} to name '${externalId}'.`, 'Name a record that exists and that the scope can read.');
|
|
78
|
+
if (!(await tableExists(internals)))
|
|
79
|
+
for (const text of DDL)
|
|
80
|
+
await internals.query({ text, params: [] });
|
|
81
|
+
const [row] = await internals.query(compile(sql `INSERT INTO ${sql.id(EXTERNAL_ID_TABLE)} (module, name, model, res_id, noupdate) VALUES (${module}, ${name}, ${model}, ${id}, ${true}) ON CONFLICT (module, name) DO UPDATE SET updated_at = ${sql.id(EXTERNAL_ID_TABLE)}.updated_at RETURNING model, res_id`));
|
|
82
|
+
if (row !== undefined && (row.model !== model || Number(row.res_id) !== id))
|
|
83
|
+
throw new UnknownExternalIdError(`The external id '${externalId}' already names ${row.model} record ${row.res_id}.`, 'Use another name, or update that record instead.');
|
|
84
|
+
}
|
|
58
85
|
/** A stable text of declared values for checksums: refs by id, Decimals as strings, sorted keys. */
|
|
59
86
|
function stable(value) {
|
|
60
87
|
if (isRef(value))
|
package/dist/core/env/env.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ import type { ChangeRow } from '../recordset/changes.js';
|
|
|
10
10
|
import { type RecordCache } from '../recordset/recordset.js';
|
|
11
11
|
import type { ListLoaded, ModelName, ModelRef, RecordSet } from '../recordset/types.js';
|
|
12
12
|
import type { Registry } from '../registry/registry.js';
|
|
13
|
-
import { type RuntimeSecurity } from '../security/runtime.js';
|
|
13
|
+
import { type RuntimeSecurity, type RuntimeSecurityDescription } from '../security/runtime.js';
|
|
14
14
|
import { type Identity, type ResolvedIdentity } from './identity.js';
|
|
15
15
|
import type { Inspector } from './inspector.js';
|
|
16
16
|
/** Typed context flags (RFC 0003 §7.4). Module-contributed flags arrive with the registry's second half. */
|
|
@@ -251,6 +251,11 @@ export declare class Env<S = unknown> {
|
|
|
251
251
|
ref<M extends ModelName<S>>(model: M, id: string): Promise<RecordSet<S, M, ListLoaded<never>>>;
|
|
252
252
|
/** The id of the record with external id `id`. @throws {UnknownExternalIdError} */
|
|
253
253
|
refId<M extends ModelName<S>>(model: M, id: string): Promise<Id<M>>;
|
|
254
|
+
/**
|
|
255
|
+
* Names record `id` of `model` with external id `externalId` outside module data (imports, RFC 0017 §4).
|
|
256
|
+
* @throws {UnknownExternalIdError} for a module's id, an unreadable record or an id naming another record
|
|
257
|
+
*/
|
|
258
|
+
setExternalId<M extends ModelName<S>>(model: M, id: Id<M> | number, externalId: string): Promise<void>;
|
|
254
259
|
/**
|
|
255
260
|
* Runtime security administration (RFC 0014 §7.10): roles, model access, record rules and permission grants, on top
|
|
256
261
|
* of the code's declarations. Administrators (or superuser scopes) only; each change is validated against the
|
|
@@ -382,6 +387,11 @@ export interface BootstrapOptions {
|
|
|
382
387
|
}
|
|
383
388
|
/** `env.securityAdmin` (RFC 0014 §7.10). */
|
|
384
389
|
export interface SecurityAdmin {
|
|
390
|
+
/**
|
|
391
|
+
* The runtime additions as stored: roles, model access, record rules, permission grants and field groups (code
|
|
392
|
+
* declarations are in the registry). Read through this transaction.
|
|
393
|
+
*/
|
|
394
|
+
describe(): Promise<RuntimeSecurityDescription>;
|
|
385
395
|
/** Creates or updates a runtime role. */
|
|
386
396
|
saveRole(role: {
|
|
387
397
|
readonly code: string;
|
package/dist/core/env/env.js
CHANGED
|
@@ -4,7 +4,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
4
4
|
import { isRetryable, } from '../../driver-pg/index.js';
|
|
5
5
|
import { InvalidSequenceError } from '../../sequence/index.js';
|
|
6
6
|
import { compile, sql as sqlTag } from '../../sql/index.js';
|
|
7
|
-
import { refId } from '../data/load.js';
|
|
7
|
+
import { refId, setExternalId } from '../data/load.js';
|
|
8
8
|
import { AccessError, CompanyNotAllowedError, ConcurrentUpdateError, FlagNotAllowedError, InvalidIdentityError, NoEnvironmentError, NoRegistryError, TransactionScopeError, } from '../errors.js';
|
|
9
9
|
import { emitEvent, enqueueJob, ensureEventTables } from '../events/events.js';
|
|
10
10
|
import { subscribe, work, } from '../events/workers.js';
|
|
@@ -14,7 +14,7 @@ import { invalidateCached } from '../recordset/compute.js';
|
|
|
14
14
|
import { companyCurrencyId, createRecordCache, currencyById, flushAll, modelRef, } from '../recordset/recordset.js';
|
|
15
15
|
import { assertAccess, assertPermission, assertRecords, canAccess, canField, hasPermission, } from '../recordset/security.js';
|
|
16
16
|
import { mapConstraintError } from '../recordset/sqlErrors.js';
|
|
17
|
-
import { administratorCodes, changeStatement, closureWith, isAdministratorWith, loadRuntimeSecurity, SECURITY_CHANNEL, validateChange, } from '../security/runtime.js';
|
|
17
|
+
import { administratorCodes, changeStatement, closureWith, describeRuntimeSecurity, isAdministratorWith, loadRuntimeSecurity, SECURITY_CHANNEL, validateChange, } from '../security/runtime.js';
|
|
18
18
|
import { assertGrants, assertLang, assertReason, resolveIdentity, SYSTEM_UID, } from './identity.js';
|
|
19
19
|
import { assertTimeZone, calendarDateIn } from './time.js';
|
|
20
20
|
const DEFAULT_FLAGS = Object.freeze({
|
|
@@ -157,21 +157,31 @@ export class Env {
|
|
|
157
157
|
async refId(model, id) {
|
|
158
158
|
return refId(this, model, id);
|
|
159
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Names record `id` of `model` with external id `externalId` outside module data (imports, RFC 0017 §4).
|
|
162
|
+
* @throws {UnknownExternalIdError} for a module's id, an unreadable record or an id naming another record
|
|
163
|
+
*/
|
|
164
|
+
async setExternalId(model, id, externalId) {
|
|
165
|
+
return setExternalId(this, model, Number(id), externalId);
|
|
166
|
+
}
|
|
160
167
|
/**
|
|
161
168
|
* Runtime security administration (RFC 0014 §7.10): roles, model access, record rules and permission grants, on top
|
|
162
169
|
* of the code's declarations. Administrators (or superuser scopes) only; each change is validated against the
|
|
163
170
|
* registry, audited, and reloaded by every process once committed. Needs `createShutro({ runtimeSecurity: true })`.
|
|
164
171
|
*/
|
|
165
172
|
get securityAdmin() {
|
|
166
|
-
const
|
|
167
|
-
const scope = internalsOf(this);
|
|
173
|
+
const allowed = () => {
|
|
168
174
|
if (!this.#runtime.security.enabled)
|
|
169
175
|
throw new InvalidIdentityError('Runtime security is not enabled.', 'Pass runtimeSecurity: true to createShutro.');
|
|
170
176
|
if (!this.su && !this.administrator)
|
|
171
177
|
throw new AccessError('security', 'manage', {
|
|
172
|
-
problem: 'only administrators can change roles, access and rules.',
|
|
178
|
+
problem: 'only administrators can read or change roles, access and rules.',
|
|
173
179
|
hint: 'Use an administrator account (defineGroup({ administrator: true })).',
|
|
174
180
|
});
|
|
181
|
+
};
|
|
182
|
+
const apply = async (change) => {
|
|
183
|
+
const scope = internalsOf(this);
|
|
184
|
+
allowed();
|
|
175
185
|
// Read through this transaction: roles saved earlier in it count.
|
|
176
186
|
const overlay = await loadRuntimeSecurity({
|
|
177
187
|
query: (q) => scope.query(q),
|
|
@@ -185,6 +195,14 @@ export class Env {
|
|
|
185
195
|
});
|
|
186
196
|
};
|
|
187
197
|
return {
|
|
198
|
+
describe: async () => {
|
|
199
|
+
allowed();
|
|
200
|
+
const scope = internalsOf(this);
|
|
201
|
+
// Through this transaction: changes made earlier in it show.
|
|
202
|
+
return describeRuntimeSecurity({
|
|
203
|
+
query: (q) => scope.query(q),
|
|
204
|
+
});
|
|
205
|
+
},
|
|
188
206
|
saveRole: (role) => apply({ kind: 'role', ...role }),
|
|
189
207
|
deleteRole: (code) => apply({ kind: 'deleteRole', code }),
|
|
190
208
|
setAccess: (role, model, perms) => apply({ kind: 'access', role, model, perms }),
|
package/dist/core/index.d.ts
CHANGED
|
@@ -48,4 +48,4 @@ export { columnDefault, createTableStatements, historyStatements, historyTable,
|
|
|
48
48
|
export { type AnyExtension, type Extension, type ExtensionDefinition, extendModel, type FieldOverride, isExtension, type OverrideFn, type Replacement, replace, } from './registry/extension.js';
|
|
49
49
|
export { compareVersions, type DataMigration, defineModule, isModule, type MigrationContext, type Module, type ModuleBase, type ModuleDefinition, } from './registry/module.js';
|
|
50
50
|
export { buildRegistry, type MethodLayer, type Origin, type RegisteredModel, type Registry, type RegistryModelDescription, type RegistryOptions, type SchemaOfModule, type SchemaOfModules, type SecurityOptions, targetOf, } from './registry/registry.js';
|
|
51
|
-
export { loadRuntimeSecurity, type RuntimeRole, type RuntimeRule, type RuntimeSecurity, runtimeSecurityStatements, SECURITY_CHANNEL, } from './security/runtime.js';
|
|
51
|
+
export { describeRuntimeSecurity, loadRuntimeSecurity, type RuntimeRole, type RuntimeRule, type RuntimeSecurity, type RuntimeSecurityDescription, runtimeSecurityStatements, SECURITY_CHANNEL, } from './security/runtime.js';
|
package/dist/core/index.js
CHANGED
|
@@ -39,4 +39,4 @@ export { columnDefault, createTableStatements, historyStatements, historyTable,
|
|
|
39
39
|
export { extendModel, isExtension, replace, } from './registry/extension.js';
|
|
40
40
|
export { compareVersions, defineModule, isModule, } from './registry/module.js';
|
|
41
41
|
export { buildRegistry, targetOf, } from './registry/registry.js';
|
|
42
|
-
export { loadRuntimeSecurity, runtimeSecurityStatements, SECURITY_CHANNEL, } from './security/runtime.js';
|
|
42
|
+
export { describeRuntimeSecurity, loadRuntimeSecurity, runtimeSecurityStatements, SECURITY_CHANNEL, } from './security/runtime.js';
|
|
@@ -20,11 +20,38 @@ function isX2Many(field) {
|
|
|
20
20
|
function scalarKeys(model) {
|
|
21
21
|
return Object.keys(model.fields).filter((k) => !isX2Many(model.fields[k]));
|
|
22
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* The ids of a draft's many2many after a handler sets it: a list of ids, or commands (`set`, `link`, `unlink`,
|
|
25
|
+
* `clear`) applied to its current ids. The draft keeps ids, as for given values, so computes read it like any set.
|
|
26
|
+
*/
|
|
27
|
+
function many2manyIds(current, value) {
|
|
28
|
+
if (Array.isArray(value))
|
|
29
|
+
return value.filter((v) => typeof v === 'number');
|
|
30
|
+
const commands = (value ?? {});
|
|
31
|
+
let list = commands['clear'] === true ? [] : [...current];
|
|
32
|
+
if (Array.isArray(commands['set']))
|
|
33
|
+
list = [...commands['set']];
|
|
34
|
+
if (Array.isArray(commands['link']))
|
|
35
|
+
for (const id of commands['link'])
|
|
36
|
+
if (!list.includes(id))
|
|
37
|
+
list.push(id);
|
|
38
|
+
if (Array.isArray(commands['unlink'])) {
|
|
39
|
+
const gone = new Set(commands['unlink']);
|
|
40
|
+
list = list.filter((id) => !gone.has(id));
|
|
41
|
+
}
|
|
42
|
+
return list;
|
|
43
|
+
}
|
|
23
44
|
/** Writes one draft value into the cache: `null` is always allowed, everything else is normalized like a write. */
|
|
24
45
|
function setDraftValue(model, values, key, value, translation) {
|
|
25
46
|
const field = model.fields[key];
|
|
26
47
|
if (field === undefined || key === 'id')
|
|
27
48
|
fail(model, [key], `'${key}' is not a field.`, `Fields: ${Object.keys(model.fields).join(', ')}.`);
|
|
49
|
+
if (field.kind === 'many2many') {
|
|
50
|
+
values.set(key, value === null || value === undefined
|
|
51
|
+
? []
|
|
52
|
+
: many2manyIds(values.get(key) ?? [], value));
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
28
55
|
if (value === null || value === undefined) {
|
|
29
56
|
values.set(key, null);
|
|
30
57
|
return;
|
|
@@ -198,6 +225,9 @@ export async function runOnchange(host, model, input) {
|
|
|
198
225
|
// The input to compare against: a record's values and the given ones; for a new draft the given ones only, so
|
|
199
226
|
// its defaults come back (a new form shows them).
|
|
200
227
|
const [beforeRow] = host.read(model, [vid], keys.filter((k) => input.id === undefined || input.id === null ? k in input.values : values.has(k)));
|
|
228
|
+
// Many2many fields come back as their ids when a handler changed them (a line's taxes from its product).
|
|
229
|
+
const sets = Object.keys(model.fields).filter((k) => model.fields[k].kind === 'many2many' && canField(internals, model, k, 'read'));
|
|
230
|
+
const setsBefore = new Map(sets.map((k) => [k, JSON.stringify(values.get(k) ?? [])]));
|
|
201
231
|
// Handlers, cascading once per key: the draft's, then each new child row's for the fields it was given
|
|
202
232
|
// (feedback #10), so a line's product handler runs inside the order being edited and sees its values.
|
|
203
233
|
await runHandlers(host, model, vid, input.id ?? null, input.changed, warnings);
|
|
@@ -225,6 +255,11 @@ export async function runOnchange(host, model, input) {
|
|
|
225
255
|
if (JSON.stringify(row?.[key] ?? null) !== JSON.stringify(beforeRow?.[key] ?? null))
|
|
226
256
|
out[key] = row?.[key];
|
|
227
257
|
}
|
|
258
|
+
for (const key of sets) {
|
|
259
|
+
const now = values.get(key) ?? [];
|
|
260
|
+
if (JSON.stringify(now) !== setsBefore.get(key))
|
|
261
|
+
out[key] = [...now];
|
|
262
|
+
}
|
|
228
263
|
const children = {};
|
|
229
264
|
for (const [key, ids] of childIds) {
|
|
230
265
|
const target = internals.registry.get(model.fields[key].target ?? '').model;
|
|
@@ -44,6 +44,28 @@ export declare function runtimeSecurityStatements(): readonly {
|
|
|
44
44
|
}[];
|
|
45
45
|
/** Loads the runtime additions (creating the tables on first use). */
|
|
46
46
|
export declare function loadRuntimeSecurity(driver: Pick<Driver, 'query'>): Promise<RuntimeSecurity>;
|
|
47
|
+
/** The runtime additions as plain lists, for administration screens (RFC 0014 §7.10). */
|
|
48
|
+
export interface RuntimeSecurityDescription {
|
|
49
|
+
readonly roles: readonly RuntimeRole[];
|
|
50
|
+
readonly access: readonly {
|
|
51
|
+
readonly role: string;
|
|
52
|
+
readonly model: string;
|
|
53
|
+
readonly perms: readonly Perm[];
|
|
54
|
+
}[];
|
|
55
|
+
readonly rules: readonly RuntimeRule[];
|
|
56
|
+
readonly permissions: readonly {
|
|
57
|
+
readonly role: string;
|
|
58
|
+
readonly permission: string;
|
|
59
|
+
}[];
|
|
60
|
+
readonly fields: readonly {
|
|
61
|
+
readonly model: string;
|
|
62
|
+
readonly field: string;
|
|
63
|
+
readonly read: readonly string[];
|
|
64
|
+
readonly write: readonly string[];
|
|
65
|
+
}[];
|
|
66
|
+
}
|
|
67
|
+
/** Reads the runtime additions as stored (creating the tables on first use), ordered for display. */
|
|
68
|
+
export declare function describeRuntimeSecurity(driver: Pick<Driver, 'query'>): Promise<RuntimeSecurityDescription>;
|
|
47
69
|
/**
|
|
48
70
|
* The groups of a field with the runtime overlay (RFC 0014 §7.10): the code groups plus the roles given in the
|
|
49
71
|
* overlay. A field without code groups that gets runtime roles becomes restricted to them: the one narrowing the
|
|
@@ -77,6 +77,39 @@ export async function loadRuntimeSecurity(driver) {
|
|
|
77
77
|
fields: fieldMap,
|
|
78
78
|
});
|
|
79
79
|
}
|
|
80
|
+
/** Reads the runtime additions as stored (creating the tables on first use), ordered for display. */
|
|
81
|
+
export async function describeRuntimeSecurity(driver) {
|
|
82
|
+
for (const text of DDL)
|
|
83
|
+
await driver.query({ text, params: [] });
|
|
84
|
+
// One after the other: one transaction, one connection.
|
|
85
|
+
const roles = await driver.query({
|
|
86
|
+
text: 'SELECT code, label, implies, administrator FROM shutro_role ORDER BY code',
|
|
87
|
+
params: [],
|
|
88
|
+
});
|
|
89
|
+
const access = await driver.query({
|
|
90
|
+
text: 'SELECT role, model, perms FROM shutro_role_access ORDER BY role, model',
|
|
91
|
+
params: [],
|
|
92
|
+
});
|
|
93
|
+
const rules = await driver.query({
|
|
94
|
+
text: 'SELECT name, role, model, perms, domain FROM shutro_role_rule ORDER BY name',
|
|
95
|
+
params: [],
|
|
96
|
+
});
|
|
97
|
+
const permissions = await driver.query({
|
|
98
|
+
text: 'SELECT role, permission FROM shutro_role_permission ORDER BY role, permission',
|
|
99
|
+
params: [],
|
|
100
|
+
});
|
|
101
|
+
const fields = await driver.query({
|
|
102
|
+
text: 'SELECT model, field, read, write FROM shutro_role_field ORDER BY model, field',
|
|
103
|
+
params: [],
|
|
104
|
+
});
|
|
105
|
+
return Object.freeze({
|
|
106
|
+
roles: roles.map((r) => Object.freeze({ ...r, implies: Object.freeze([...r.implies]) })),
|
|
107
|
+
access: access.map((a) => Object.freeze({ ...a, perms: Object.freeze([...a.perms]) })),
|
|
108
|
+
rules: rules.map((r) => Object.freeze({ ...r, perms: Object.freeze([...r.perms]) })),
|
|
109
|
+
permissions: permissions.map((p) => Object.freeze({ ...p })),
|
|
110
|
+
fields: fields.map((f) => Object.freeze({ ...f, read: Object.freeze([...f.read]), write: Object.freeze([...f.write]) })),
|
|
111
|
+
});
|
|
112
|
+
}
|
|
80
113
|
/**
|
|
81
114
|
* The groups of a field with the runtime overlay (RFC 0014 §7.10): the code groups plus the roles given in the
|
|
82
115
|
* overlay. A field without code groups that gets runtime roles becomes restricted to them: the one narrowing the
|
package/package.json
CHANGED