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
|
@@ -5,11 +5,14 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { DuplicateModelError, DuplicateModuleError, ExtensionConflictError, InvalidDependsPathError, InvalidExtensionError, InvalidModuleError, InvalidRelationError, UndeclaredDependencyError, UnknownModelError, UnknownSequenceError, } from '../errors.js';
|
|
7
7
|
import { overrideField, } from '../model/field.js';
|
|
8
|
-
import { defineModel, markTransition, transitionOf, } from '../model/model.js';
|
|
8
|
+
import { defineModel, markTransition, RESERVED_KEYS, transitionOf, } from '../model/model.js';
|
|
9
9
|
import { isModule } from './module.js';
|
|
10
10
|
// ------------------------------------------------------------------------------------------------- schema types
|
|
11
|
-
import { groupClosure, mergeAccess, normalizeFieldGroups, } from '../../security/index.js';
|
|
11
|
+
import { groupClosure, mergeAccess, normalizeFieldGroups, SecurityDefinitionError, } from '../../security/index.js';
|
|
12
12
|
import { buildComputeGraph } from '../compute/graph.js';
|
|
13
|
+
import { validateData } from '../data/data.js';
|
|
14
|
+
import { delegatedField } from '../model/field.js';
|
|
15
|
+
import { relatedPath } from '../model/related.js';
|
|
13
16
|
const RELATION_KINDS = new Set(['many2one', 'one2many', 'many2many']);
|
|
14
17
|
/** The target model of a relation field, else `undefined`. */
|
|
15
18
|
export function targetOf(field) {
|
|
@@ -346,6 +349,24 @@ export function buildRegistry(options) {
|
|
|
346
349
|
applyExtension(draft, ext, module.name, reachable);
|
|
347
350
|
}
|
|
348
351
|
}
|
|
352
|
+
// Delegation: the parent's fields (after its extensions) become writable related fields of the child.
|
|
353
|
+
for (const draft of drafts.values()) {
|
|
354
|
+
for (const key of draft.base.definition.delegates ??
|
|
355
|
+
[]) {
|
|
356
|
+
const target = draft.fields[key]?.target ?? '';
|
|
357
|
+
const parent = drafts.get(target);
|
|
358
|
+
if (parent === undefined)
|
|
359
|
+
throw new UnknownModelError(target, `delegates '${key}' of '${draft.base.name}'`);
|
|
360
|
+
for (const [pk, pf] of Object.entries(parent.fields)) {
|
|
361
|
+
if (RESERVED_KEYS.includes(pk) || pk in draft.fields)
|
|
362
|
+
continue;
|
|
363
|
+
if (pf.kind === 'one2many' || pf.kind === 'many2many' || pf.kind === 'state')
|
|
364
|
+
continue;
|
|
365
|
+
draft.fields[pk] = delegatedField(pf, `${key}.${pk}`);
|
|
366
|
+
draft.fieldOrigins[pk] = parent.fieldOrigins[pk] ?? parent.module;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
349
370
|
const models = new Map();
|
|
350
371
|
for (const [name, draft] of drafts)
|
|
351
372
|
models.set(name, finalize(draft));
|
|
@@ -366,6 +387,30 @@ export function buildRegistry(options) {
|
|
|
366
387
|
securityGroups.set(group.code, group);
|
|
367
388
|
}
|
|
368
389
|
}
|
|
390
|
+
const permissions = new Map();
|
|
391
|
+
for (const module of modules) {
|
|
392
|
+
for (const permission of module.permissions) {
|
|
393
|
+
if (permissions.has(permission.code))
|
|
394
|
+
throw new InvalidModuleError(`Module '${module.name}' declares the permission '${permission.code}', which another module already declares.`, 'Permission codes are global: declare each permission once.');
|
|
395
|
+
for (const code of permission.groups)
|
|
396
|
+
if (!securityGroups.has(code))
|
|
397
|
+
throw new InvalidModuleError(`Permission '${permission.code}' is granted to the group '${code}', which no module declares.`, 'Declare it with defineGroup() in a module, or fix the code.');
|
|
398
|
+
permissions.set(permission.code, permission);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
for (const { model } of models.values()) {
|
|
402
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
403
|
+
const transitions = field.transitions;
|
|
404
|
+
for (const [name, t] of Object.entries(transitions ?? {}))
|
|
405
|
+
if (t.requires !== undefined && !permissions.has(t.requires))
|
|
406
|
+
throw new InvalidModuleError(`Transition '${name}' of ${model.name}.${key} requires the permission '${t.requires}', which no module declares.`, 'Declare it with definePermission() in a module, or fix the code.');
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
for (const { model } of models.values()) {
|
|
410
|
+
if (model.backdate !== undefined && !permissions.has(model.backdate.permission))
|
|
411
|
+
throw new InvalidModuleError(`Model '${model.name}' requires the permission '${model.backdate.permission}' for back-dated entries, which no module declares.`, 'Declare it with definePermission() in a module, or fix the code.');
|
|
412
|
+
}
|
|
413
|
+
const administrators = new Set([...securityGroups.values()].filter((g) => g.administrator).map((g) => g.code));
|
|
369
414
|
for (const { model } of models.values()) {
|
|
370
415
|
for (const code of [
|
|
371
416
|
...Object.keys(model.access),
|
|
@@ -392,8 +437,9 @@ export function buildRegistry(options) {
|
|
|
392
437
|
const target = targetOf(field);
|
|
393
438
|
if (target !== undefined) {
|
|
394
439
|
const other = resolve(fromModule, target, where);
|
|
395
|
-
|
|
396
|
-
|
|
440
|
+
const withoutKey = field.kind === 'many2one' && field.foreignKey === false;
|
|
441
|
+
if (field.kind !== 'one2many' && other.model.partition !== undefined && !withoutKey) {
|
|
442
|
+
throw new InvalidRelationError(`${where} points at '${target}', which is partitioned.`, 'A foreign key cannot reference a partitioned table without its partition key: use f.many2one(target, { foreignKey: false }) (ids checked by the ORM), or reference a non-partitioned model.');
|
|
397
443
|
}
|
|
398
444
|
if (field.kind === 'one2many') {
|
|
399
445
|
const inverseKey = field.inverseField;
|
|
@@ -453,14 +499,63 @@ export function buildRegistry(options) {
|
|
|
453
499
|
}
|
|
454
500
|
}
|
|
455
501
|
}
|
|
502
|
+
const enforce = options.security?.enforce ?? true;
|
|
503
|
+
const mode = enforce === 'warn' ? 'warn' : enforce ? 'enforce' : 'off';
|
|
504
|
+
if (mode === 'warn' && process.env['NODE_ENV'] === 'production') {
|
|
505
|
+
throw new SecurityDefinitionError("security: { enforce: 'warn' } is refused when NODE_ENV=production.", "Declare the missing access grants (the warnings name them) and remove enforce: 'warn'.");
|
|
506
|
+
}
|
|
507
|
+
const reported = new Set();
|
|
508
|
+
const onDenied = options.security?.onDenied ??
|
|
509
|
+
((message) => {
|
|
510
|
+
process.emitWarning(message, { code: 'SHUTRO_ACCESS_WOULD_DENY' });
|
|
511
|
+
});
|
|
512
|
+
// Related fields mirror a field of the same kind at the end of their path (many2one steps only).
|
|
513
|
+
for (const { model } of models.values()) {
|
|
514
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
515
|
+
const path = relatedPath(field.compute);
|
|
516
|
+
if (path === undefined)
|
|
517
|
+
continue;
|
|
518
|
+
const where = `Related field '${key}' of ${model.name} ('${path}')`;
|
|
519
|
+
let current = model;
|
|
520
|
+
const steps = path.split('.');
|
|
521
|
+
for (const [i, step] of steps.entries()) {
|
|
522
|
+
const f = current.fields[step];
|
|
523
|
+
if (f === undefined)
|
|
524
|
+
throw new InvalidRelationError(`${where}: '${step}' is not a field of ${current.name}.`, 'Fix the path.');
|
|
525
|
+
if (i === steps.length - 1) {
|
|
526
|
+
const sameTarget = f.kind !== 'many2one' || targetOf(f) === targetOf(field);
|
|
527
|
+
if (f.kind !== field.kind || !sameTarget)
|
|
528
|
+
throw new InvalidRelationError(`${where} is a ${field.kind}${field.kind === 'many2one' ? ` of ${targetOf(field)}` : ''}, but the path ends at a ${f.kind}${f.kind === 'many2one' ? ` of ${targetOf(f)}` : ''}.`, 'Declare the related field with the same kind (and target) as the field it mirrors.');
|
|
529
|
+
break;
|
|
530
|
+
}
|
|
531
|
+
if (f.kind !== 'many2one')
|
|
532
|
+
throw new InvalidRelationError(`${where}: '${step}' is a ${f.kind}; related paths go through many2one fields.`, 'Use a compute for x2many paths.');
|
|
533
|
+
const next = models.get(targetOf(f) ?? '');
|
|
534
|
+
if (next === undefined)
|
|
535
|
+
break; // the relation check reports unknown targets
|
|
536
|
+
current = next.model;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
const externalIds = validateData(modules, models);
|
|
456
541
|
const registry = {
|
|
457
542
|
modules: Object.freeze(modules),
|
|
458
543
|
compute: buildComputeGraph(models),
|
|
459
544
|
sequences,
|
|
545
|
+
externalIds,
|
|
460
546
|
security: {
|
|
461
547
|
groups: securityGroups,
|
|
462
548
|
closure: (codes) => groupClosure(securityGroups, codes),
|
|
463
|
-
|
|
549
|
+
isAdministrator: (groups) => [...administrators].some((code) => groups.has(code)),
|
|
550
|
+
permissions,
|
|
551
|
+
enforce: mode !== 'off',
|
|
552
|
+
mode,
|
|
553
|
+
denied(message) {
|
|
554
|
+
if (reported.has(message))
|
|
555
|
+
return;
|
|
556
|
+
reported.add(message);
|
|
557
|
+
onDenied(message);
|
|
558
|
+
},
|
|
464
559
|
},
|
|
465
560
|
loadOrder: Object.freeze(modules.map((m) => m.name)),
|
|
466
561
|
models,
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime security (RFC 0014 §7.10): roles, model access, record rules and feature-permission grants stored in the
|
|
3
|
+
* database and edited while the system runs. Code declarations are the reviewed baseline; the database extends it
|
|
4
|
+
* (it never removes a grant the code makes). Every change is validated against the registry when saved, audited,
|
|
5
|
+
* and announced with NOTIFY so every process reloads.
|
|
6
|
+
*/
|
|
7
|
+
import type { Driver } from '../../driver-pg/index.js';
|
|
8
|
+
import { type FieldGroups, type Perm, type RulePerm, type RuleSpec } from '../../security/index.js';
|
|
9
|
+
import { compile } from '../../sql/index.js';
|
|
10
|
+
import type { Registry } from '../registry/registry.js';
|
|
11
|
+
/** The NOTIFY channel runtime security changes are announced on. */
|
|
12
|
+
export declare const SECURITY_CHANNEL = "shutro_security";
|
|
13
|
+
/** A role defined at runtime. */
|
|
14
|
+
export interface RuntimeRole {
|
|
15
|
+
readonly code: string;
|
|
16
|
+
readonly label: string;
|
|
17
|
+
readonly implies: readonly string[];
|
|
18
|
+
readonly administrator: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** A record rule defined at runtime, for one role. */
|
|
21
|
+
export interface RuntimeRule {
|
|
22
|
+
readonly name: string;
|
|
23
|
+
readonly role: string;
|
|
24
|
+
readonly model: string;
|
|
25
|
+
readonly perms: readonly RulePerm[];
|
|
26
|
+
readonly domain: Readonly<Record<string, unknown>>;
|
|
27
|
+
}
|
|
28
|
+
/** The runtime additions, as loaded. */
|
|
29
|
+
export interface RuntimeSecurity {
|
|
30
|
+
readonly roles: ReadonlyMap<string, RuntimeRole>;
|
|
31
|
+
/** model → role → permissions. */
|
|
32
|
+
readonly access: ReadonlyMap<string, ReadonlyMap<string, ReadonlySet<Perm>>>;
|
|
33
|
+
/** model → rules (as rule specs for that role). */
|
|
34
|
+
readonly rules: ReadonlyMap<string, Readonly<Record<string, RuleSpec>>>;
|
|
35
|
+
/** feature permission → roles granted it. */
|
|
36
|
+
readonly permissions: ReadonlyMap<string, ReadonlySet<string>>;
|
|
37
|
+
/** model → field → the roles that may read / write it (in addition to the field's code groups). */
|
|
38
|
+
readonly fields: ReadonlyMap<string, ReadonlyMap<string, FieldGroups>>;
|
|
39
|
+
}
|
|
40
|
+
/** Statements creating the runtime security tables. */
|
|
41
|
+
export declare function runtimeSecurityStatements(): readonly {
|
|
42
|
+
readonly text: string;
|
|
43
|
+
readonly params: readonly [];
|
|
44
|
+
}[];
|
|
45
|
+
/** Loads the runtime additions (creating the tables on first use). */
|
|
46
|
+
export declare function loadRuntimeSecurity(driver: Pick<Driver, 'query'>): Promise<RuntimeSecurity>;
|
|
47
|
+
/**
|
|
48
|
+
* The groups of a field with the runtime overlay (RFC 0014 §7.10): the code groups plus the roles given in the
|
|
49
|
+
* overlay. A field without code groups that gets runtime roles becomes restricted to them: the one narrowing the
|
|
50
|
+
* overlay allows, so administrators can hide or lock a field without code.
|
|
51
|
+
*/
|
|
52
|
+
export declare function effectiveFieldGroups(overlay: RuntimeSecurity | undefined, model: string, field: string, code: FieldGroups): FieldGroups;
|
|
53
|
+
/** The codes (code groups and runtime roles) whose closure includes an administrator group. */
|
|
54
|
+
export declare function administratorCodes(registry: Registry, overlay: RuntimeSecurity | undefined): ReadonlySet<string>;
|
|
55
|
+
/** The closure of `codes` over `implies`, code groups and runtime roles together. */
|
|
56
|
+
export declare function closureWith(registry: Registry, overlay: RuntimeSecurity | undefined, codes: Iterable<string>): Set<string>;
|
|
57
|
+
/** True when the groups include an administrator group, from code or from a runtime role. */
|
|
58
|
+
export declare function isAdministratorWith(registry: Registry, overlay: RuntimeSecurity | undefined, groups: ReadonlySet<string>): boolean;
|
|
59
|
+
/** Validates a change against the registry and the current overlay (RFC 0014 §7.10). @throws {InvalidModuleError} */
|
|
60
|
+
export declare function validateChange(registry: Registry, overlay: RuntimeSecurity, change: SecurityChange): void;
|
|
61
|
+
/** One change to runtime security. */
|
|
62
|
+
export type SecurityChange = {
|
|
63
|
+
readonly kind: 'role';
|
|
64
|
+
readonly code: string;
|
|
65
|
+
readonly label?: string;
|
|
66
|
+
readonly implies?: readonly string[];
|
|
67
|
+
readonly administrator?: boolean;
|
|
68
|
+
} | {
|
|
69
|
+
readonly kind: 'deleteRole';
|
|
70
|
+
readonly code: string;
|
|
71
|
+
} | {
|
|
72
|
+
readonly kind: 'access';
|
|
73
|
+
readonly role: string;
|
|
74
|
+
readonly model: string;
|
|
75
|
+
readonly perms: readonly Perm[];
|
|
76
|
+
} | {
|
|
77
|
+
readonly kind: 'rule';
|
|
78
|
+
readonly name: string;
|
|
79
|
+
readonly role: string;
|
|
80
|
+
readonly model: string;
|
|
81
|
+
readonly perms: readonly RulePerm[];
|
|
82
|
+
readonly domain: Readonly<Record<string, unknown>>;
|
|
83
|
+
} | {
|
|
84
|
+
readonly kind: 'deleteRule';
|
|
85
|
+
readonly name: string;
|
|
86
|
+
} | {
|
|
87
|
+
readonly kind: 'permission';
|
|
88
|
+
readonly role: string;
|
|
89
|
+
readonly permission: string;
|
|
90
|
+
} | {
|
|
91
|
+
readonly kind: 'revokePermission';
|
|
92
|
+
readonly role: string;
|
|
93
|
+
readonly permission: string;
|
|
94
|
+
} | {
|
|
95
|
+
readonly kind: 'fields';
|
|
96
|
+
readonly model: string;
|
|
97
|
+
readonly field: string;
|
|
98
|
+
readonly read: readonly string[];
|
|
99
|
+
readonly write: readonly string[];
|
|
100
|
+
};
|
|
101
|
+
/** The statement that applies a validated change. */
|
|
102
|
+
export declare function changeStatement(change: SecurityChange): ReturnType<typeof compile>;
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { GROUP_CODE, resolvePlaceholders, } from '../../security/index.js';
|
|
2
|
+
import { compile, sql } from '../../sql/index.js';
|
|
3
|
+
import { InvalidModuleError } from '../errors.js';
|
|
4
|
+
import { compileDomain } from '../recordset/domain.js';
|
|
5
|
+
/** The NOTIFY channel runtime security changes are announced on. */
|
|
6
|
+
export const SECURITY_CHANNEL = 'shutro_security';
|
|
7
|
+
const PERMS = ['read', 'write', 'create', 'unlink', 'export', 'import'];
|
|
8
|
+
const RULE_PERMS = ['read', 'write', 'create', 'unlink'];
|
|
9
|
+
const DDL = [
|
|
10
|
+
'CREATE TABLE IF NOT EXISTS "shutro_role" ("code" text PRIMARY KEY, "label" text NOT NULL, "implies" text[] NOT NULL DEFAULT \'{}\', "administrator" boolean NOT NULL DEFAULT false)',
|
|
11
|
+
'CREATE TABLE IF NOT EXISTS "shutro_role_access" ("role" text NOT NULL, "model" text NOT NULL, "perms" text[] NOT NULL, PRIMARY KEY ("role", "model"))',
|
|
12
|
+
'CREATE TABLE IF NOT EXISTS "shutro_role_rule" ("name" text PRIMARY KEY, "role" text NOT NULL, "model" text NOT NULL, "perms" text[] NOT NULL, "domain" jsonb NOT NULL)',
|
|
13
|
+
'CREATE TABLE IF NOT EXISTS "shutro_role_permission" ("role" text NOT NULL, "permission" text NOT NULL, PRIMARY KEY ("role", "permission"))',
|
|
14
|
+
`CREATE TABLE IF NOT EXISTS "shutro_role_field" ("model" text NOT NULL, "field" text NOT NULL, "read" text[] NOT NULL DEFAULT '{}', "write" text[] NOT NULL DEFAULT '{}', PRIMARY KEY ("model", "field"))`,
|
|
15
|
+
];
|
|
16
|
+
/** Statements creating the runtime security tables. */
|
|
17
|
+
export function runtimeSecurityStatements() {
|
|
18
|
+
return DDL.map((text) => ({ text, params: [] }));
|
|
19
|
+
}
|
|
20
|
+
/** Loads the runtime additions (creating the tables on first use). */
|
|
21
|
+
export async function loadRuntimeSecurity(driver) {
|
|
22
|
+
for (const text of DDL)
|
|
23
|
+
await driver.query({ text, params: [] });
|
|
24
|
+
const roles = await driver.query({
|
|
25
|
+
text: 'SELECT code, label, implies, administrator FROM shutro_role',
|
|
26
|
+
params: [],
|
|
27
|
+
});
|
|
28
|
+
const access = await driver.query({
|
|
29
|
+
text: 'SELECT role, model, perms FROM shutro_role_access',
|
|
30
|
+
params: [],
|
|
31
|
+
});
|
|
32
|
+
const rules = await driver.query({
|
|
33
|
+
text: 'SELECT name, role, model, perms, domain FROM shutro_role_rule ORDER BY name',
|
|
34
|
+
params: [],
|
|
35
|
+
});
|
|
36
|
+
const grants = await driver.query({
|
|
37
|
+
text: 'SELECT role, permission FROM shutro_role_permission',
|
|
38
|
+
params: [],
|
|
39
|
+
});
|
|
40
|
+
const fieldRows = await driver.query({
|
|
41
|
+
text: 'SELECT model, field, read, write FROM shutro_role_field',
|
|
42
|
+
params: [],
|
|
43
|
+
});
|
|
44
|
+
const fieldMap = new Map();
|
|
45
|
+
for (const f of fieldRows) {
|
|
46
|
+
const byField = fieldMap.get(f.model) ?? new Map();
|
|
47
|
+
// Writers can read: when reading is restricted, the roles allowed to write are allowed to read. An empty read
|
|
48
|
+
// list leaves reading open (`{ write: [...] }` makes the field read-only for everyone else).
|
|
49
|
+
const read = Object.freeze(f.read.length === 0 ? [] : [...new Set([...f.read, ...f.write])]);
|
|
50
|
+
byField.set(f.field, Object.freeze({ read, write: Object.freeze([...f.write]) }));
|
|
51
|
+
fieldMap.set(f.model, byField);
|
|
52
|
+
}
|
|
53
|
+
const accessMap = new Map();
|
|
54
|
+
for (const a of access) {
|
|
55
|
+
const byRole = accessMap.get(a.model) ?? new Map();
|
|
56
|
+
byRole.set(a.role, new Set(a.perms));
|
|
57
|
+
accessMap.set(a.model, byRole);
|
|
58
|
+
}
|
|
59
|
+
const ruleMap = new Map();
|
|
60
|
+
for (const r of rules) {
|
|
61
|
+
const byName = ruleMap.get(r.model) ?? {};
|
|
62
|
+
byName[`runtime:${r.name}`] = Object.freeze({
|
|
63
|
+
groups: [r.role],
|
|
64
|
+
perms: r.perms,
|
|
65
|
+
domain: r.domain,
|
|
66
|
+
});
|
|
67
|
+
ruleMap.set(r.model, byName);
|
|
68
|
+
}
|
|
69
|
+
const permissionMap = new Map();
|
|
70
|
+
for (const g of grants)
|
|
71
|
+
permissionMap.set(g.permission, (permissionMap.get(g.permission) ?? new Set()).add(g.role));
|
|
72
|
+
return Object.freeze({
|
|
73
|
+
roles: new Map(roles.map((r) => [r.code, Object.freeze({ ...r, implies: Object.freeze([...r.implies]) })])),
|
|
74
|
+
access: accessMap,
|
|
75
|
+
rules: ruleMap,
|
|
76
|
+
permissions: permissionMap,
|
|
77
|
+
fields: fieldMap,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The groups of a field with the runtime overlay (RFC 0014 §7.10): the code groups plus the roles given in the
|
|
82
|
+
* overlay. A field without code groups that gets runtime roles becomes restricted to them: the one narrowing the
|
|
83
|
+
* overlay allows, so administrators can hide or lock a field without code.
|
|
84
|
+
*/
|
|
85
|
+
export function effectiveFieldGroups(overlay, model, field, code) {
|
|
86
|
+
const extra = overlay?.fields.get(model)?.get(field);
|
|
87
|
+
if (extra === undefined)
|
|
88
|
+
return code;
|
|
89
|
+
const merge = (a, b) => b.length === 0 ? a : Object.freeze([...new Set([...a, ...b])]);
|
|
90
|
+
return Object.freeze({
|
|
91
|
+
read: merge(code.read, extra.read),
|
|
92
|
+
write: merge(code.write, extra.write),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/** The codes (code groups and runtime roles) whose closure includes an administrator group. */
|
|
96
|
+
export function administratorCodes(registry, overlay) {
|
|
97
|
+
const codes = [...registry.security.groups.keys(), ...(overlay?.roles.keys() ?? [])];
|
|
98
|
+
return new Set(codes.filter((code) => isAdministratorWith(registry, overlay, closureWith(registry, overlay, [code]))));
|
|
99
|
+
}
|
|
100
|
+
/** The closure of `codes` over `implies`, code groups and runtime roles together. */
|
|
101
|
+
export function closureWith(registry, overlay, codes) {
|
|
102
|
+
if (overlay === undefined || overlay.roles.size === 0)
|
|
103
|
+
return registry.security.closure(codes);
|
|
104
|
+
const out = new Set();
|
|
105
|
+
const stack = [...codes];
|
|
106
|
+
while (stack.length > 0) {
|
|
107
|
+
const code = stack.pop();
|
|
108
|
+
if (out.has(code))
|
|
109
|
+
continue;
|
|
110
|
+
out.add(code);
|
|
111
|
+
for (const implied of registry.security.groups.get(code)?.implies ?? [])
|
|
112
|
+
stack.push(implied);
|
|
113
|
+
for (const implied of overlay.roles.get(code)?.implies ?? [])
|
|
114
|
+
stack.push(implied);
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
/** True when the groups include an administrator group, from code or from a runtime role. */
|
|
119
|
+
export function isAdministratorWith(registry, overlay, groups) {
|
|
120
|
+
if (registry.security.isAdministrator(groups))
|
|
121
|
+
return true;
|
|
122
|
+
for (const role of overlay?.roles.values() ?? [])
|
|
123
|
+
if (role.administrator && groups.has(role.code))
|
|
124
|
+
return true;
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
function invalid(problem, hint) {
|
|
128
|
+
throw new InvalidModuleError(problem, hint);
|
|
129
|
+
}
|
|
130
|
+
function knownRole(registry, overlay, role) {
|
|
131
|
+
if (!registry.security.groups.has(role) && !overlay.roles.has(role))
|
|
132
|
+
invalid(`The role '${role}' does not exist.`, 'Create it with saveRole(), or use a group a module declares.');
|
|
133
|
+
}
|
|
134
|
+
/** Validates a change against the registry and the current overlay (RFC 0014 §7.10). @throws {InvalidModuleError} */
|
|
135
|
+
export function validateChange(registry, overlay, change) {
|
|
136
|
+
switch (change.kind) {
|
|
137
|
+
case 'role': {
|
|
138
|
+
if (!GROUP_CODE.test(change.code))
|
|
139
|
+
invalid(`'${change.code}' is not a role code.`, "Use 'module.name', e.g. 'sale.team_lead'.");
|
|
140
|
+
if (registry.security.groups.has(change.code))
|
|
141
|
+
invalid(`'${change.code}' is declared in code.`, 'Code groups are changed in their module; create a new role instead.');
|
|
142
|
+
for (const code of change.implies ?? [])
|
|
143
|
+
if (code !== change.code)
|
|
144
|
+
knownRole(registry, overlay, code);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
case 'access': {
|
|
148
|
+
knownRole(registry, overlay, change.role);
|
|
149
|
+
if (!registry.has(change.model))
|
|
150
|
+
invalid(`The model '${change.model}' is not installed.`, 'Check the model name.');
|
|
151
|
+
for (const p of change.perms)
|
|
152
|
+
if (!PERMS.includes(p))
|
|
153
|
+
invalid(`'${p}' is not a permission.`, `Use ${PERMS.join(', ')}.`);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
case 'rule': {
|
|
157
|
+
knownRole(registry, overlay, change.role);
|
|
158
|
+
if (!registry.has(change.model))
|
|
159
|
+
invalid(`The model '${change.model}' is not installed.`, 'Check the model name.');
|
|
160
|
+
if (change.perms.length === 0)
|
|
161
|
+
invalid(`Rule '${change.name}' applies to no operation.`, `Give perms among ${RULE_PERMS.join(', ')}.`);
|
|
162
|
+
for (const p of change.perms)
|
|
163
|
+
if (!RULE_PERMS.includes(p))
|
|
164
|
+
invalid(`'${p}' is not a rule permission.`, `Use ${RULE_PERMS.join(', ')}.`);
|
|
165
|
+
// Compiled now, with placeholder values: a broken domain is refused when saved, not when users hit it.
|
|
166
|
+
const resolved = resolvePlaceholders(change.domain, {
|
|
167
|
+
uid: 0,
|
|
168
|
+
companyId: 0,
|
|
169
|
+
companyIds: [0],
|
|
170
|
+
});
|
|
171
|
+
compileDomain(registry.get(change.model).model, resolved, undefined, (n) => registry.get(n).model);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
case 'deleteRole': {
|
|
175
|
+
for (const [model, byField] of overlay.fields)
|
|
176
|
+
for (const [field, groups] of byField)
|
|
177
|
+
if (groups.read.includes(change.code) || groups.write.includes(change.code))
|
|
178
|
+
invalid(`The role '${change.code}' is used by the field security of ${model}.${field}.`, 'Remove it from that field first (setFieldGroups): deleting it would change who sees the field.');
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
case 'fields': {
|
|
182
|
+
if (!registry.has(change.model))
|
|
183
|
+
invalid(`The model '${change.model}' is not installed.`, 'Check the model name.');
|
|
184
|
+
const field = registry.get(change.model).model.fields[change.field];
|
|
185
|
+
if (field === undefined)
|
|
186
|
+
invalid(`${change.model} has no field '${change.field}'.`, 'Check the field name.');
|
|
187
|
+
if (change.field === 'id')
|
|
188
|
+
invalid('The id field cannot be restricted.', 'Restrict other fields, or the model access.');
|
|
189
|
+
for (const role of [...change.read, ...change.write])
|
|
190
|
+
knownRole(registry, overlay, role);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
case 'permission': {
|
|
194
|
+
knownRole(registry, overlay, change.role);
|
|
195
|
+
if (!registry.security.permissions.has(change.permission))
|
|
196
|
+
invalid(`The permission '${change.permission}' is not declared by any module.`, 'Grant a permission a module declares with definePermission().');
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
default:
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/** The statement that applies a validated change. */
|
|
204
|
+
export function changeStatement(change) {
|
|
205
|
+
switch (change.kind) {
|
|
206
|
+
case 'role':
|
|
207
|
+
return compile(sql `INSERT INTO shutro_role (code, label, implies, administrator) VALUES (${change.code}, ${change.label ?? change.code}, ${sql.array([...(change.implies ?? [])], 'text')}, ${change.administrator === true})
|
|
208
|
+
ON CONFLICT (code) DO UPDATE SET label = EXCLUDED.label, implies = EXCLUDED.implies, administrator = EXCLUDED.administrator`);
|
|
209
|
+
case 'deleteRole':
|
|
210
|
+
return compile(sql `WITH a AS (DELETE FROM shutro_role_access WHERE role = ${change.code}), r AS (DELETE FROM shutro_role_rule WHERE role = ${change.code}), p AS (DELETE FROM shutro_role_permission WHERE role = ${change.code})
|
|
211
|
+
DELETE FROM shutro_role WHERE code = ${change.code}`);
|
|
212
|
+
case 'access':
|
|
213
|
+
return change.perms.length === 0
|
|
214
|
+
? compile(sql `DELETE FROM shutro_role_access WHERE role = ${change.role} AND model = ${change.model}`)
|
|
215
|
+
: compile(sql `INSERT INTO shutro_role_access (role, model, perms) VALUES (${change.role}, ${change.model}, ${sql.array([...change.perms], 'text')})
|
|
216
|
+
ON CONFLICT (role, model) DO UPDATE SET perms = EXCLUDED.perms`);
|
|
217
|
+
case 'rule':
|
|
218
|
+
return compile(sql `INSERT INTO shutro_role_rule (name, role, model, perms, domain) VALUES (${change.name}, ${change.role}, ${change.model}, ${sql.array([...change.perms], 'text')}, (${sql.param(JSON.stringify(change.domain), 'text')})::jsonb)
|
|
219
|
+
ON CONFLICT (name) DO UPDATE SET role = EXCLUDED.role, model = EXCLUDED.model, perms = EXCLUDED.perms, domain = EXCLUDED.domain`);
|
|
220
|
+
case 'deleteRule':
|
|
221
|
+
return compile(sql `DELETE FROM shutro_role_rule WHERE name = ${change.name}`);
|
|
222
|
+
case 'permission':
|
|
223
|
+
return compile(sql `INSERT INTO shutro_role_permission (role, permission) VALUES (${change.role}, ${change.permission}) ON CONFLICT DO NOTHING`);
|
|
224
|
+
case 'revokePermission':
|
|
225
|
+
return compile(sql `DELETE FROM shutro_role_permission WHERE role = ${change.role} AND permission = ${change.permission}`);
|
|
226
|
+
case 'fields':
|
|
227
|
+
return change.read.length === 0 && change.write.length === 0
|
|
228
|
+
? compile(sql `DELETE FROM shutro_role_field WHERE model = ${change.model} AND field = ${change.field}`)
|
|
229
|
+
: compile(sql `INSERT INTO shutro_role_field (model, field, read, write) VALUES (${change.model}, ${change.field}, ${sql.array([...change.read], 'text')}, ${sql.array([...change.write], 'text')})
|
|
230
|
+
ON CONFLICT (model, field) DO UPDATE SET read = EXCLUDED.read, write = EXCLUDED.write`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -33,6 +33,8 @@ export interface DriverConnection {
|
|
|
33
33
|
}
|
|
34
34
|
/** The connection pool. */
|
|
35
35
|
export interface Driver {
|
|
36
|
+
/** Pool size (`max`), when known: Shutro checks it against features that need a second connection. */
|
|
37
|
+
readonly max?: number;
|
|
36
38
|
/** Runs one statement in its own implicit transaction (DDL, maintenance). Business code uses `transaction()`. */
|
|
37
39
|
query<R extends Row = Row>(query: DriverQuery): Promise<readonly R[]>;
|
|
38
40
|
/**
|
package/dist/driver-pg/driver.js
CHANGED
package/dist/migrate/apply.d.ts
CHANGED
|
@@ -11,11 +11,15 @@ export interface MigrationPlan {
|
|
|
11
11
|
readonly destructive: boolean;
|
|
12
12
|
}[];
|
|
13
13
|
}
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* Compares the registry with the live database and plans the changes. Tables in `ignore` belong to the
|
|
16
|
+
* application, not to the models (a framework's own tables, e.g. `kosh_*`): they are never altered or dropped.
|
|
17
|
+
*/
|
|
15
18
|
export declare function planMigration(options: {
|
|
16
19
|
readonly driver: Driver;
|
|
17
20
|
readonly registry: Registry;
|
|
18
21
|
readonly schema?: string;
|
|
22
|
+
readonly ignore?: readonly (string | RegExp)[];
|
|
19
23
|
}): Promise<MigrationPlan>;
|
|
20
24
|
/** A migration file on disk. */
|
|
21
25
|
export interface MigrationFile {
|
package/dist/migrate/apply.js
CHANGED
|
@@ -11,9 +11,27 @@ import { diffSchema } from './diff.js';
|
|
|
11
11
|
import { DestructiveMigrationError, MigrationChecksumError, MigrationFileError } from './errors.js';
|
|
12
12
|
import { renderOperation } from './render.js';
|
|
13
13
|
import { desiredSchema } from './schema.js';
|
|
14
|
-
/**
|
|
14
|
+
/** True when `ignore` names the table: an exact name, a `prefix*`, or a regular expression. */
|
|
15
|
+
function ignored(name, ignore) {
|
|
16
|
+
return ignore.some((p) => typeof p === 'string'
|
|
17
|
+
? p.endsWith('*')
|
|
18
|
+
? name.startsWith(p.slice(0, -1))
|
|
19
|
+
: name === p
|
|
20
|
+
: p.test(name));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Compares the registry with the live database and plans the changes. Tables in `ignore` belong to the
|
|
24
|
+
* application, not to the models (a framework's own tables, e.g. `kosh_*`): they are never altered or dropped.
|
|
25
|
+
*/
|
|
15
26
|
export async function planMigration(options) {
|
|
16
|
-
const
|
|
27
|
+
const read = await readLiveSchema(options.driver, options.schema ?? 'public');
|
|
28
|
+
const ignore = options.ignore ?? [];
|
|
29
|
+
const live = ignore.length === 0
|
|
30
|
+
? read
|
|
31
|
+
: {
|
|
32
|
+
...read,
|
|
33
|
+
tables: Object.fromEntries(Object.entries(read.tables).filter(([name]) => !ignored(name, ignore))),
|
|
34
|
+
};
|
|
17
35
|
const operations = diffSchema(desiredSchema(options.registry), live);
|
|
18
36
|
return {
|
|
19
37
|
operations,
|
package/dist/migrate/schema.js
CHANGED
|
@@ -45,7 +45,7 @@ function columnOf(key, field, column) {
|
|
|
45
45
|
identity: true,
|
|
46
46
|
backfill: null,
|
|
47
47
|
};
|
|
48
|
-
const type = field.kind === 'many2one' ? 'bigint' : canonicalType(field.pgType);
|
|
48
|
+
const type = field.kind === 'many2one' && !field.companyDependent ? 'bigint' : canonicalType(field.pgType);
|
|
49
49
|
const dbDefault = columnDefault(key, field);
|
|
50
50
|
const backfill = typeof field.default === 'function' ? null : literalOf(field.default);
|
|
51
51
|
return {
|
|
@@ -117,7 +117,9 @@ export function desiredSchema(registry) {
|
|
|
117
117
|
continue;
|
|
118
118
|
}
|
|
119
119
|
columns[column] = columnOf(key, field, column);
|
|
120
|
-
if (field.kind === 'many2one'
|
|
120
|
+
if (field.kind === 'many2one' &&
|
|
121
|
+
field.foreignKey !== false &&
|
|
122
|
+
!field.companyDependent) {
|
|
121
123
|
const target = registry.get(targetOf(field) ?? '').model;
|
|
122
124
|
foreignKeys[`${model.table}_${column}_fkey`] = {
|
|
123
125
|
column,
|
|
@@ -186,6 +188,42 @@ export function desiredSchema(registry) {
|
|
|
186
188
|
}),
|
|
187
189
|
};
|
|
188
190
|
}
|
|
191
|
+
// History tables (RFC 0018 §7.4): the main table's columns, nullable and unconstrained, plus the validity range.
|
|
192
|
+
for (const { model } of registry.models.values()) {
|
|
193
|
+
if (!model.history)
|
|
194
|
+
continue;
|
|
195
|
+
const main = tables[model.table];
|
|
196
|
+
if (main === undefined)
|
|
197
|
+
continue;
|
|
198
|
+
const name = `${model.table}_history`.slice(0, 63);
|
|
199
|
+
const columns = {};
|
|
200
|
+
for (const [column, spec] of Object.entries(main.columns))
|
|
201
|
+
columns[column] = {
|
|
202
|
+
...spec,
|
|
203
|
+
nullable: column !== 'id',
|
|
204
|
+
default: null,
|
|
205
|
+
identity: false,
|
|
206
|
+
backfill: null,
|
|
207
|
+
};
|
|
208
|
+
for (const column of ['valid_from', 'valid_to'])
|
|
209
|
+
columns[column] = {
|
|
210
|
+
name: column,
|
|
211
|
+
type: 'timestamp with time zone',
|
|
212
|
+
nullable: false,
|
|
213
|
+
default: null,
|
|
214
|
+
identity: false,
|
|
215
|
+
backfill: null,
|
|
216
|
+
};
|
|
217
|
+
tables[name] = {
|
|
218
|
+
name,
|
|
219
|
+
columns,
|
|
220
|
+
primaryKey: ['id', 'valid_to'],
|
|
221
|
+
foreignKeys: {},
|
|
222
|
+
uniques: {},
|
|
223
|
+
checks: {},
|
|
224
|
+
indexes: {},
|
|
225
|
+
};
|
|
226
|
+
}
|
|
189
227
|
return { tables, extensions: [...extensions].sort() };
|
|
190
228
|
}
|
|
191
229
|
/** Column name of a field key, as `defineModel` derives it (exported for callers building names). */
|
package/dist/security/index.d.ts
CHANGED
|
@@ -4,6 +4,22 @@ export interface GroupDefinition {
|
|
|
4
4
|
readonly code: string;
|
|
5
5
|
readonly label: string;
|
|
6
6
|
readonly implies: readonly string[];
|
|
7
|
+
/**
|
|
8
|
+
* Members (directly or through `implies`) are administrators: every ACL, record-rule, field-group and permission
|
|
9
|
+
* check passes for them, on every model and feature of every module, without any grant.
|
|
10
|
+
*/
|
|
11
|
+
readonly administrator: boolean;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A named permission for a feature that is not a model operation: an app, a menu, a button, an approval
|
|
15
|
+
* (`'sale.discount_approve'`). Granted to groups; administrators always have it.
|
|
16
|
+
*/
|
|
17
|
+
export interface PermissionDefinition {
|
|
18
|
+
/** `module.name`, e.g. `'sale.discount_approve'`. */
|
|
19
|
+
readonly code: string;
|
|
20
|
+
readonly label: string;
|
|
21
|
+
/** Groups that grant it (implied groups count). */
|
|
22
|
+
readonly groups: readonly string[];
|
|
7
23
|
}
|
|
8
24
|
export declare const GROUP_CODE: RegExp;
|
|
9
25
|
/** A security declaration that cannot be used. */
|
|
@@ -16,7 +32,15 @@ export declare function defineGroup(input: {
|
|
|
16
32
|
readonly code: string;
|
|
17
33
|
readonly label?: string;
|
|
18
34
|
readonly implies?: readonly string[];
|
|
35
|
+
/** Members can do everything, without grants (see {@link GroupDefinition.administrator}). */
|
|
36
|
+
readonly administrator?: boolean;
|
|
19
37
|
}): GroupDefinition;
|
|
38
|
+
/** Declares a feature permission. @throws {SecurityDefinitionError} for malformed codes. */
|
|
39
|
+
export declare function definePermission(input: {
|
|
40
|
+
readonly code: string;
|
|
41
|
+
readonly label?: string;
|
|
42
|
+
readonly groups: readonly string[];
|
|
43
|
+
}): PermissionDefinition;
|
|
20
44
|
/** The transitive closure of `codes` over `implies` (unknown codes are kept as given). */
|
|
21
45
|
export declare function groupClosure(groups: ReadonlyMap<string, GroupDefinition>, codes: Iterable<string>): Set<string>;
|
|
22
46
|
/** What a group may do with a model. */
|