shutro 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/dist/audit/index.d.ts +57 -0
  4. package/dist/audit/index.js +94 -0
  5. package/dist/cli/bin.d.ts +2 -0
  6. package/dist/cli/bin.js +11 -0
  7. package/dist/cli/cli.d.ts +10 -0
  8. package/dist/cli/cli.js +149 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +47 -0
  11. package/dist/cli/errors.d.ts +16 -0
  12. package/dist/cli/errors.js +23 -0
  13. package/dist/cli/generate/generate.d.ts +33 -0
  14. package/dist/cli/generate/generate.js +82 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +200 -0
  17. package/dist/cli/index.d.ts +12 -0
  18. package/dist/cli/index.js +12 -0
  19. package/dist/cli/init.d.ts +2 -0
  20. package/dist/cli/init.js +65 -0
  21. package/dist/cli/inspect.d.ts +10 -0
  22. package/dist/cli/inspect.js +82 -0
  23. package/dist/cli/packages.d.ts +6 -0
  24. package/dist/cli/packages.js +6 -0
  25. package/dist/cli/project.d.ts +18 -0
  26. package/dist/cli/project.js +39 -0
  27. package/dist/core/compute/graph.d.ts +52 -0
  28. package/dist/core/compute/graph.js +162 -0
  29. package/dist/core/env/env.d.ts +295 -0
  30. package/dist/core/env/env.js +631 -0
  31. package/dist/core/env/identity.d.ts +33 -0
  32. package/dist/core/env/identity.js +49 -0
  33. package/dist/core/env/inspector.d.ts +55 -0
  34. package/dist/core/env/inspector.js +85 -0
  35. package/dist/core/env/time.d.ts +12 -0
  36. package/dist/core/env/time.js +38 -0
  37. package/dist/core/errors.d.ts +242 -0
  38. package/dist/core/errors.js +339 -0
  39. package/dist/core/index.d.ts +43 -0
  40. package/dist/core/index.js +34 -0
  41. package/dist/core/model/company.d.ts +6 -0
  42. package/dist/core/model/company.js +31 -0
  43. package/dist/core/model/faces.d.ts +42 -0
  44. package/dist/core/model/faces.js +1 -0
  45. package/dist/core/model/field.d.ts +446 -0
  46. package/dist/core/model/field.js +398 -0
  47. package/dist/core/model/generated.d.ts +75 -0
  48. package/dist/core/model/generated.js +1 -0
  49. package/dist/core/model/id.d.ts +33 -0
  50. package/dist/core/model/id.js +4 -0
  51. package/dist/core/model/model.d.ts +347 -0
  52. package/dist/core/model/model.js +538 -0
  53. package/dist/core/model/partition.d.ts +31 -0
  54. package/dist/core/model/partition.js +71 -0
  55. package/dist/core/money/currency.d.ts +39 -0
  56. package/dist/core/money/currency.js +37 -0
  57. package/dist/core/money/decimal.d.ts +26 -0
  58. package/dist/core/money/decimal.js +51 -0
  59. package/dist/core/money/fx.d.ts +60 -0
  60. package/dist/core/money/fx.js +109 -0
  61. package/dist/core/money/money.d.ts +84 -0
  62. package/dist/core/money/money.js +173 -0
  63. package/dist/core/money/quantity.d.ts +67 -0
  64. package/dist/core/money/quantity.js +108 -0
  65. package/dist/core/money/rounding.d.ts +11 -0
  66. package/dist/core/money/rounding.js +12 -0
  67. package/dist/core/recordset/audit.d.ts +25 -0
  68. package/dist/core/recordset/audit.js +205 -0
  69. package/dist/core/recordset/compute.d.ts +34 -0
  70. package/dist/core/recordset/compute.js +405 -0
  71. package/dist/core/recordset/constraints.d.ts +9 -0
  72. package/dist/core/recordset/constraints.js +61 -0
  73. package/dist/core/recordset/domain.d.ts +27 -0
  74. package/dist/core/recordset/domain.js +228 -0
  75. package/dist/core/recordset/onchange.d.ts +43 -0
  76. package/dist/core/recordset/onchange.js +207 -0
  77. package/dist/core/recordset/recordset.d.ts +101 -0
  78. package/dist/core/recordset/recordset.js +723 -0
  79. package/dist/core/recordset/relations.d.ts +15 -0
  80. package/dist/core/recordset/relations.js +13 -0
  81. package/dist/core/recordset/rls.d.ts +15 -0
  82. package/dist/core/recordset/rls.js +108 -0
  83. package/dist/core/recordset/security.d.ts +42 -0
  84. package/dist/core/recordset/security.js +184 -0
  85. package/dist/core/recordset/sequences.d.ts +31 -0
  86. package/dist/core/recordset/sequences.js +154 -0
  87. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  88. package/dist/core/recordset/sqlErrors.js +39 -0
  89. package/dist/core/recordset/transitions.d.ts +10 -0
  90. package/dist/core/recordset/transitions.js +77 -0
  91. package/dist/core/recordset/types.d.ts +296 -0
  92. package/dist/core/recordset/types.js +8 -0
  93. package/dist/core/recordset/values.d.ts +27 -0
  94. package/dist/core/recordset/values.js +147 -0
  95. package/dist/core/recordset/writes.d.ts +37 -0
  96. package/dist/core/recordset/writes.js +581 -0
  97. package/dist/core/registry/ddl.d.ts +22 -0
  98. package/dist/core/registry/ddl.js +127 -0
  99. package/dist/core/registry/extension.d.ts +94 -0
  100. package/dist/core/registry/extension.js +90 -0
  101. package/dist/core/registry/module.d.ts +80 -0
  102. package/dist/core/registry/module.js +96 -0
  103. package/dist/core/registry/registry.d.ts +105 -0
  104. package/dist/core/registry/registry.js +496 -0
  105. package/dist/driver-pg/driver.d.ts +86 -0
  106. package/dist/driver-pg/driver.js +176 -0
  107. package/dist/driver-pg/errors.d.ts +72 -0
  108. package/dist/driver-pg/errors.js +182 -0
  109. package/dist/driver-pg/index.d.ts +7 -0
  110. package/dist/driver-pg/index.js +7 -0
  111. package/dist/i18n/index.d.ts +25 -0
  112. package/dist/i18n/index.js +51 -0
  113. package/dist/migrate/apply.d.ts +78 -0
  114. package/dist/migrate/apply.js +167 -0
  115. package/dist/migrate/catalog.d.ts +10 -0
  116. package/dist/migrate/catalog.js +122 -0
  117. package/dist/migrate/diff.d.ts +98 -0
  118. package/dist/migrate/diff.js +160 -0
  119. package/dist/migrate/errors.d.ts +21 -0
  120. package/dist/migrate/errors.js +31 -0
  121. package/dist/migrate/index.d.ts +18 -0
  122. package/dist/migrate/index.js +18 -0
  123. package/dist/migrate/render.d.ts +5 -0
  124. package/dist/migrate/render.js +101 -0
  125. package/dist/migrate/schema.d.ts +61 -0
  126. package/dist/migrate/schema.js +195 -0
  127. package/dist/security/index.d.ts +123 -0
  128. package/dist/security/index.js +262 -0
  129. package/dist/sequence/index.d.ts +63 -0
  130. package/dist/sequence/index.js +106 -0
  131. package/dist/sql/ast.d.ts +49 -0
  132. package/dist/sql/ast.js +47 -0
  133. package/dist/sql/builder/builder.d.ts +215 -0
  134. package/dist/sql/builder/builder.js +308 -0
  135. package/dist/sql/builder/expression.d.ts +80 -0
  136. package/dist/sql/builder/expression.js +126 -0
  137. package/dist/sql/compile.d.ts +18 -0
  138. package/dist/sql/compile.js +41 -0
  139. package/dist/sql/errors.d.ts +13 -0
  140. package/dist/sql/errors.js +16 -0
  141. package/dist/sql/index.d.ts +19 -0
  142. package/dist/sql/index.js +19 -0
  143. package/dist/sql/tag.d.ts +42 -0
  144. package/dist/sql/tag.js +95 -0
  145. package/package.json +82 -4
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Naming of many2many junction tables (RFC 0001 §7.3: derived deterministically).
3
+ */
4
+ import type { Field } from '../model/field.js';
5
+ import type { AnyModel } from '../model/model.js';
6
+ /** A many2many junction table and its two columns. */
7
+ export interface JunctionTable {
8
+ readonly table: string;
9
+ readonly sourceTable: string;
10
+ readonly sourceColumn: string;
11
+ readonly targetTable: string;
12
+ readonly targetColumn: string;
13
+ }
14
+ /** `sale_order` ⟷ `sale_tag` → table `sale_order_sale_tag_rel` with `sale_order_id`, `sale_tag_id`. */
15
+ export declare function junctionTable(source: AnyModel, field: Field, target: AnyModel): JunctionTable;
@@ -0,0 +1,13 @@
1
+ /** `sale_order` ⟷ `sale_tag` → table `sale_order_sale_tag_rel` with `sale_order_id`, `sale_tag_id`. */
2
+ export function junctionTable(source, field, target) {
3
+ const relation = field.relation;
4
+ const sourceColumn = `${source.table}_id`;
5
+ const targetColumn = source.table === target.table ? `${target.table}_other_id` : `${target.table}_id`;
6
+ return {
7
+ table: relation ?? `${source.table}_${target.table}_rel`,
8
+ sourceTable: source.table,
9
+ sourceColumn,
10
+ targetTable: target.table,
11
+ targetColumn,
12
+ };
13
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * PostgreSQL row-level security generated from record rules (RFC 0014 §7.5): one permissive policy per group rule,
3
+ * one restrictive policy per global rule, and the "no applicable group rule" and superuser escapes, all reading the
4
+ * session settings `shutro.run()` pushes.
5
+ */
6
+ import { type PolicyInput } from '../../security/index.js';
7
+ import type { AnyModel } from '../model/model.js';
8
+ import type { Registry } from '../registry/registry.js';
9
+ import { type ModelResolver } from './domain.js';
10
+ /** A rule domain as a boolean SQL expression over the table's columns and the session settings. */
11
+ export declare function ruleCondition(model: AnyModel, domain: Readonly<Record<string, unknown>>, resolve?: ModelResolver): string;
12
+ /** The policies of one model, or `[]` when it has no rules. */
13
+ export declare function modelPolicies(model: AnyModel, resolve?: ModelResolver): PolicyInput[];
14
+ /** Every statement that enables RLS for the models with record rules. Run them through `@shutro/migrate` or directly. */
15
+ export declare function rlsStatements(registry: Registry): string[];
@@ -0,0 +1,108 @@
1
+ /**
2
+ * PostgreSQL row-level security generated from record rules (RFC 0014 §7.5): one permissive policy per group rule,
3
+ * one restrictive policy per global rule, and the "no applicable group rule" and superuser escapes, all reading the
4
+ * session settings `shutro.run()` pushes.
5
+ */
6
+ import { rlsStatements as policyStatements, RLS_PLACEHOLDERS, RLS_SU, resolvePlaceholders, rlsGroupCondition, } from '../../security/index.js';
7
+ import { compile, sql } from '../../sql/index.js';
8
+ import { compileDomain } from './domain.js';
9
+ const MARK = '\u0000$env:';
10
+ const SENTINEL = { uid: Number.NaN, companyId: Number.NaN, companyIds: [] };
11
+ const COMMANDS = {
12
+ read: 'SELECT',
13
+ write: 'UPDATE',
14
+ create: 'INSERT',
15
+ unlink: 'DELETE',
16
+ };
17
+ function literal(value) {
18
+ if (typeof value === 'string') {
19
+ if (value === `${MARK}uid`)
20
+ return RLS_PLACEHOLDERS.uid;
21
+ if (value === `${MARK}companyId`)
22
+ return RLS_PLACEHOLDERS.companyId;
23
+ return `'${value.replaceAll("'", "''")}'`;
24
+ }
25
+ if (typeof value === 'number' || typeof value === 'bigint')
26
+ return String(value);
27
+ if (typeof value === 'boolean')
28
+ return value ? 'true' : 'false';
29
+ if (value === null || value === undefined)
30
+ return 'NULL';
31
+ if (Array.isArray(value)) {
32
+ if (value.length === 1 && value[0] === `${MARK}companyIds`)
33
+ return RLS_PLACEHOLDERS.companyIds;
34
+ return `ARRAY[${value.map(literal).join(', ')}]`;
35
+ }
36
+ if (value instanceof Date)
37
+ return `'${value.toISOString()}'::timestamptz`;
38
+ return `'${JSON.stringify(value).replaceAll("'", "''")}'::jsonb`;
39
+ }
40
+ /** A rule domain as a boolean SQL expression over the table's columns and the session settings. */
41
+ export function ruleCondition(model, domain, resolve) {
42
+ // Placeholders become markers that survive compilation as parameters, then turn into current_setting() reads.
43
+ const marked = resolvePlaceholders(domain, {
44
+ uid: `${MARK}uid`,
45
+ companyId: `${MARK}companyId`,
46
+ companyIds: [`${MARK}companyIds`],
47
+ });
48
+ void SENTINEL;
49
+ const conditions = compileDomain(model, marked, undefined, resolve);
50
+ if (conditions.length === 0)
51
+ return 'true';
52
+ const { text, params } = compile(sql.join(conditions, sql ` AND `));
53
+ return text.replace(/\$(\d+)/g, (_, n) => literal(params[Number(n) - 1]));
54
+ }
55
+ /** The policies of one model, or `[]` when it has no rules. */
56
+ export function modelPolicies(model, resolve) {
57
+ const policies = [];
58
+ const perms = ['read', 'write', 'create', 'unlink'];
59
+ for (const perm of perms) {
60
+ const command = COMMANDS[perm];
61
+ const rules = Object.entries(model.rules).filter(([, r]) => r.perms.includes(perm));
62
+ if (rules.length === 0)
63
+ continue;
64
+ const groupCodes = new Set();
65
+ for (const [key, rule] of rules) {
66
+ const name = `${model.table}_${key}_${perm}`.slice(0, 63);
67
+ if (rule.groups === 'global') {
68
+ policies.push({
69
+ table: model.table,
70
+ name,
71
+ command,
72
+ permissive: false,
73
+ condition: `${RLS_SU} OR (${ruleCondition(model, rule.domain, resolve)})`,
74
+ });
75
+ }
76
+ else {
77
+ for (const g of rule.groups)
78
+ groupCodes.add(g);
79
+ policies.push({
80
+ table: model.table,
81
+ name,
82
+ command,
83
+ permissive: true,
84
+ condition: `${RLS_SU} OR (${rlsGroupCondition(rule.groups)} AND (${ruleCondition(model, rule.domain, resolve)}))`,
85
+ });
86
+ }
87
+ }
88
+ // Users none of whose groups a rule names are unrestricted by group rules; without any group rule, everyone is.
89
+ policies.push({
90
+ table: model.table,
91
+ name: `${model.table}_nogroup_${perm}`.slice(0, 63),
92
+ command,
93
+ permissive: true,
94
+ condition: groupCodes.size === 0 ? 'true' : `${RLS_SU} OR NOT (${rlsGroupCondition([...groupCodes])})`,
95
+ });
96
+ }
97
+ return policies;
98
+ }
99
+ /** Every statement that enables RLS for the models with record rules. Run them through `@shutro/migrate` or directly. */
100
+ export function rlsStatements(registry) {
101
+ const out = [];
102
+ for (const { model } of registry.models.values()) {
103
+ const policies = modelPolicies(model, (n) => registry.get(n).model);
104
+ if (policies.length > 0)
105
+ out.push(...policyStatements(model.table, policies));
106
+ }
107
+ return out;
108
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Access control at runtime (RFC 0014): model ACL checks, field-level groups, record rules compiled into WHERE
3
+ * fragments, per-record checks for writes and deletes, and encryption of stored values. Superuser scopes bypass
4
+ * the checks; multi-company consistency does not live here (RFC 0003 §7.4).
5
+ */
6
+ import { type Perm, type RulePerm } from '../../security/index.js';
7
+ import { type SqlFragment } from '../../sql/index.js';
8
+ import type { ScopeInternals } from '../env/env.js';
9
+ import type { Field } from '../model/field.js';
10
+ import type { AnyModel } from '../model/model.js';
11
+ /** True when the environment may perform `perm` on the model (ACL, RFC 0014 §7.2). */
12
+ export declare function canAccess(internals: ScopeInternals, model: AnyModel, perm: Perm): boolean;
13
+ /** @throws {AccessError} unless {@link canAccess}. */
14
+ export declare function assertAccess(internals: ScopeInternals, model: AnyModel, perm: Perm): void;
15
+ /** True when the field may be read / written by the environment. */
16
+ export declare function canField(internals: ScopeInternals, model: AnyModel, key: string, kind: 'read' | 'write'): boolean;
17
+ /** @throws {AccessError} naming the first field the environment may not read / write. */
18
+ export declare function assertFields(internals: ScopeInternals, model: AnyModel, keys: Iterable<string>, kind: 'read' | 'write'): void;
19
+ /** The keys of `keys` the environment may read (restricted fields are left out of default projections). */
20
+ export declare function readableKeys(internals: ScopeInternals, model: AnyModel, keys: Iterable<string>): string[];
21
+ /**
22
+ * Checks that every field a domain mentions is readable, following relation paths and `any` / `none` into the
23
+ * related models: a filter on a hidden field would leak it through which records match (RFC 0014 §7.4).
24
+ */
25
+ export declare function assertDomainFields(internals: ScopeInternals, model: AnyModel, domain: unknown): void;
26
+ /** The field keys a domain mentions (through `or` / `and` / `not`). */
27
+ export declare function domainKeys(domain: unknown, out?: Set<string>): Set<string>;
28
+ /** Record-rule conditions for `perm` (RFC 0014 §7.3): globals ANDed, applicable group rules ORed. Empty under `su`. */
29
+ export declare function ruleConditions(internals: ScopeInternals, model: AnyModel, perm: RulePerm): SqlFragment[];
30
+ /** True when `perm` has rules for the model that apply to this environment. */
31
+ export declare function hasRules(internals: ScopeInternals, model: AnyModel, perm: RulePerm): boolean;
32
+ /**
33
+ * Checks that every id passes the rules for `perm` (RFC 0014 §7.3). Ids that exist but are out of scope are an
34
+ * {@link AccessError}; ids that do not exist are a {@link MissingRecordError}.
35
+ */
36
+ export declare function assertRecords(internals: ScopeInternals, model: AnyModel, ids: readonly number[], perm: RulePerm): Promise<void>;
37
+ /** Distinguishes missing records from records out of the rules' scope, and throws accordingly. */
38
+ export declare function explainDenied(internals: ScopeInternals, model: AnyModel, denied: readonly number[], perm: RulePerm): Promise<never>;
39
+ /** The value bound for a stored column: encrypted fields are encrypted with the current key (RFC 0014 §7.6). */
40
+ export declare function storedValue(internals: ScopeInternals, field: Field, value: unknown): unknown;
41
+ /** The plaintext of a loaded encrypted value. */
42
+ export declare function loadedValue(internals: ScopeInternals, field: Field, value: unknown): unknown;
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Access control at runtime (RFC 0014): model ACL checks, field-level groups, record rules compiled into WHERE
3
+ * fragments, per-record checks for writes and deletes, and encryption of stored values. Superuser scopes bypass
4
+ * the checks; multi-company consistency does not live here (RFC 0003 §7.4).
5
+ */
6
+ import { allowed, applicableRules, decrypt, EncryptionError, encrypt, fieldAllowed, resolvePlaceholders, } from '../../security/index.js';
7
+ import { compile, sql } from '../../sql/index.js';
8
+ import { AccessError, MissingRecordError } from '../errors.js';
9
+ import { compileDomain } from './domain.js';
10
+ import { bindValue } from './values.js';
11
+ const HINT = 'Ask an administrator for a group that grants it, or run the task inside env.asSuperuser({ reason }).';
12
+ /** True when the environment may perform `perm` on the model (ACL, RFC 0014 §7.2). */
13
+ export function canAccess(internals, model, perm) {
14
+ if (internals.env.su || !internals.registry.security.enforce)
15
+ return true;
16
+ return allowed(model.access, internals.env.groups, perm);
17
+ }
18
+ /** @throws {AccessError} unless {@link canAccess}. */
19
+ export function assertAccess(internals, model, perm) {
20
+ if (canAccess(internals, model, perm))
21
+ return;
22
+ throw new AccessError(model.name, perm, {
23
+ problem: `${perm} access to ${model.name} is denied.`,
24
+ hint: HINT,
25
+ });
26
+ }
27
+ /** True when the field may be read / written by the environment. */
28
+ export function canField(internals, model, key, kind) {
29
+ const field = model.fields[key];
30
+ if (field === undefined || internals.env.su || !internals.registry.security.enforce)
31
+ return true;
32
+ return fieldAllowed(field.groups, internals.env.groups, kind);
33
+ }
34
+ /** @throws {AccessError} naming the first field the environment may not read / write. */
35
+ export function assertFields(internals, model, keys, kind) {
36
+ for (const key of keys) {
37
+ if (canField(internals, model, key, kind))
38
+ continue;
39
+ throw new AccessError(model.name, kind, {
40
+ field: key,
41
+ problem: `field '${key}' of ${model.name} is restricted to groups ${(kind === 'read' ? model.fields[key]?.groups.read : model.fields[key]?.groups.write)?.join(', ') ?? ''}.`,
42
+ hint: HINT,
43
+ });
44
+ }
45
+ }
46
+ /** The keys of `keys` the environment may read (restricted fields are left out of default projections). */
47
+ export function readableKeys(internals, model, keys) {
48
+ return [...keys].filter((k) => canField(internals, model, k, 'read'));
49
+ }
50
+ /**
51
+ * Checks that every field a domain mentions is readable, following relation paths and `any` / `none` into the
52
+ * related models: a filter on a hidden field would leak it through which records match (RFC 0014 §7.4).
53
+ */
54
+ export function assertDomainFields(internals, model, domain) {
55
+ if (Array.isArray(domain)) {
56
+ for (const d of domain)
57
+ assertDomainFields(internals, model, d);
58
+ return;
59
+ }
60
+ if (typeof domain !== 'object' || domain === null)
61
+ return;
62
+ for (const [key, value] of Object.entries(domain)) {
63
+ if (key === 'or' || key === 'and' || key === 'not') {
64
+ assertDomainFields(internals, model, value);
65
+ continue;
66
+ }
67
+ const [head = '', ...rest] = key.split('.');
68
+ assertFields(internals, model, [head], 'read');
69
+ const field = model.fields[head];
70
+ const target = field?.target;
71
+ if (target === undefined)
72
+ continue;
73
+ const targetModel = internals.registry.get(target).model;
74
+ assertAccess(internals, targetModel, 'read');
75
+ if (rest.length > 0)
76
+ assertDomainFields(internals, targetModel, { [rest.join('.')]: value });
77
+ else if (typeof value === 'object' && value !== null) {
78
+ const v = value;
79
+ if (v.any !== undefined)
80
+ assertDomainFields(internals, targetModel, v.any);
81
+ if (v.none !== undefined)
82
+ assertDomainFields(internals, targetModel, v.none);
83
+ }
84
+ }
85
+ }
86
+ /** The field keys a domain mentions (through `or` / `and` / `not`). */
87
+ export function domainKeys(domain, out = new Set()) {
88
+ if (Array.isArray(domain)) {
89
+ for (const d of domain)
90
+ domainKeys(d, out);
91
+ return out;
92
+ }
93
+ if (typeof domain !== 'object' || domain === null)
94
+ return out;
95
+ for (const [key, value] of Object.entries(domain)) {
96
+ if (key === 'or' || key === 'and' || key === 'not')
97
+ domainKeys(value, out);
98
+ else
99
+ out.add(key);
100
+ }
101
+ return out;
102
+ }
103
+ /** Record-rule conditions for `perm` (RFC 0014 §7.3): globals ANDed, applicable group rules ORed. Empty under `su`. */
104
+ export function ruleConditions(internals, model, perm) {
105
+ const { env } = internals;
106
+ if (env.su || !internals.registry.security.enforce)
107
+ return [];
108
+ const { globals, groupRules, hasGroupRules } = applicableRules(model.rules, env.groups, perm);
109
+ const placeholders = { uid: env.uid, companyId: env.companyId, companyIds: env.companyIds };
110
+ const out = [];
111
+ for (const rule of globals) {
112
+ const conditions = compileDomain(model, resolvePlaceholders(rule.domain, placeholders), undefined, (n) => internals.registry.get(n).model);
113
+ if (conditions.length > 0)
114
+ out.push(sql `(${sql.join(conditions, sql ` AND `)})`);
115
+ }
116
+ if (hasGroupRules) {
117
+ if (groupRules.length === 0)
118
+ return out; // no group rule names the user's groups: unrestricted by group rules (Odoo semantics)
119
+ const alternatives = [];
120
+ for (const rule of groupRules) {
121
+ const conditions = compileDomain(model, resolvePlaceholders(rule.domain, placeholders), undefined, (n) => internals.registry.get(n).model);
122
+ if (conditions.length === 0)
123
+ return out; // an unconditional group rule grants everything the globals allow
124
+ alternatives.push(sql `(${sql.join(conditions, sql ` AND `)})`);
125
+ }
126
+ out.push(sql `(${sql.join(alternatives, sql ` OR `)})`);
127
+ }
128
+ return out;
129
+ }
130
+ /** True when `perm` has rules for the model that apply to this environment. */
131
+ export function hasRules(internals, model, perm) {
132
+ return ruleConditions(internals, model, perm).length > 0;
133
+ }
134
+ /**
135
+ * Checks that every id passes the rules for `perm` (RFC 0014 §7.3). Ids that exist but are out of scope are an
136
+ * {@link AccessError}; ids that do not exist are a {@link MissingRecordError}.
137
+ */
138
+ export async function assertRecords(internals, model, ids, perm) {
139
+ const real = ids.filter((id) => id > 0);
140
+ if (real.length === 0)
141
+ return;
142
+ const conditions = ruleConditions(internals, model, perm);
143
+ if (conditions.length === 0)
144
+ return;
145
+ const rows = await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(model.table)} WHERE ${sql.id('id')} = ANY(${sql.array(real, 'bigint')}) AND ${sql.join(conditions, sql ` AND `)}`));
146
+ const passed = new Set(rows.map((r) => Number(r.id)));
147
+ const denied = real.filter((id) => !passed.has(id));
148
+ if (denied.length === 0)
149
+ return;
150
+ await explainDenied(internals, model, denied, perm);
151
+ }
152
+ /** Distinguishes missing records from records out of the rules' scope, and throws accordingly. */
153
+ export async function explainDenied(internals, model, denied, perm) {
154
+ const existing = await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(model.table)} WHERE ${sql.id('id')} = ANY(${sql.array([...denied], 'bigint')})`));
155
+ const found = new Set(existing.map((r) => Number(r.id)));
156
+ const missing = denied.filter((id) => !found.has(id));
157
+ if (missing.length > 0 && found.size === 0)
158
+ throw new MissingRecordError(model.name, missing);
159
+ throw new AccessError(model.name, perm, {
160
+ records: denied.filter((id) => found.has(id)),
161
+ problem: `record rules deny ${perm} on ${model.name} record(s) ${denied.filter((id) => found.has(id)).join(', ')}.`,
162
+ hint: 'The records exist but are outside the rules that apply to this user (RFC 0014 §7.3).',
163
+ });
164
+ }
165
+ /** The value bound for a stored column: encrypted fields are encrypted with the current key (RFC 0014 §7.6). */
166
+ export function storedValue(internals, field, value) {
167
+ if (!field.encrypted || value === null || value === undefined)
168
+ return bindValue(field, value);
169
+ const ring = internals.keys;
170
+ if (ring === undefined) {
171
+ throw new EncryptionError('No encryption keys are configured.', 'Pass keys: createKeyRing({ current, keys }) to createShutro() before writing encrypted fields.');
172
+ }
173
+ return encrypt(ring, String(value));
174
+ }
175
+ /** The plaintext of a loaded encrypted value. */
176
+ export function loadedValue(internals, field, value) {
177
+ if (!field.encrypted || value === null || value === undefined)
178
+ return value;
179
+ const ring = internals.keys;
180
+ if (ring === undefined) {
181
+ throw new EncryptionError('No encryption keys are configured.', 'Pass keys: createKeyRing({ current, keys }) to createShutro() to read encrypted fields.');
182
+ }
183
+ return decrypt(ring, String(value));
184
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Document numbering at runtime (RFC 0012 §7.2–7.4): range allocation per (company, period) group, in the business
3
+ * transaction for gapless sequences or in a short autonomous one otherwise; filling sequence fields at create time;
4
+ * `records.assignNumber()` for manual numbering.
5
+ */
6
+ import { type SequenceDefinition } from '../../sequence/index.js';
7
+ import type { ScopeInternals } from '../env/env.js';
8
+ import type { Field } from '../model/field.js';
9
+ import type { AnyModel } from '../model/model.js';
10
+ import type { ComputeHost } from './compute.js';
11
+ /** The placeholder of a manually numbered document (RFC 0012 §7.4). */
12
+ export declare const UNNUMBERED = "/";
13
+ /** Allocates one formatted number per request, in one statement per (company, period) group. */
14
+ export declare function allocateNumbers(internals: ScopeInternals, definition: SequenceDefinition, requests: readonly {
15
+ readonly company: number | null;
16
+ readonly date: string;
17
+ }[]): Promise<string[]>;
18
+ /** Sequence fields of a model with their options. */
19
+ export declare function sequenceFields(model: AnyModel): {
20
+ readonly key: string;
21
+ readonly field: Field;
22
+ readonly options: NonNullable<Field['sequence']>;
23
+ }[];
24
+ /** Fills the `on: 'create'` sequence fields of rows that have no value (RFC 0012 §7.4). */
25
+ export declare function fillSequences(internals: ScopeInternals, model: AnyModel, rows: readonly {
26
+ readonly stored: Map<string, unknown>;
27
+ }[]): Promise<void>;
28
+ /** `records.assignNumber(key, { date })`: numbers unnumbered records through the unit of work. */
29
+ export declare function assignNumbers(host: ComputeHost, model: AnyModel, ids: readonly number[], key: string, options: {
30
+ readonly date?: string | undefined;
31
+ }): Promise<void>;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Document numbering at runtime (RFC 0012 §7.2–7.4): range allocation per (company, period) group, in the business
3
+ * transaction for gapless sequences or in a short autonomous one otherwise; filling sequence fields at create time;
4
+ * `records.assignNumber()` for manual numbering.
5
+ */
6
+ import { allocateStatement, formatNumber, numbersFrom, periodKey, SEQUENCE_TABLE, sequenceTableStatements, } from '../../sequence/index.js';
7
+ import { UnknownSequenceError, ValidationError } from '../errors.js';
8
+ import { trackChange } from './audit.js';
9
+ /** The placeholder of a manually numbered document (RFC 0012 §7.4). */
10
+ export const UNNUMBERED = '/';
11
+ const ensured = new WeakSet();
12
+ async function ensureTable(driver) {
13
+ if (ensured.has(driver))
14
+ return;
15
+ const [row] = await driver.query({
16
+ text: `SELECT to_regclass('${SEQUENCE_TABLE}') IS NOT NULL AS present`,
17
+ params: [],
18
+ });
19
+ if (row?.present !== true)
20
+ for (const statement of sequenceTableStatements())
21
+ await driver.query(statement);
22
+ ensured.add(driver);
23
+ }
24
+ function groupRequests(definition, requests) {
25
+ const groups = new Map();
26
+ requests.forEach((request, i) => {
27
+ const company = definition.perCompany ? (request.company ?? 0) : 0;
28
+ const period = periodKey(definition, request.date);
29
+ const key = `${company}|${period}`;
30
+ let group = groups.get(key);
31
+ if (group === undefined) {
32
+ group = { company, period, date: request.date, members: [] };
33
+ groups.set(key, group);
34
+ }
35
+ group.members.push(i);
36
+ });
37
+ return [...groups.values()];
38
+ }
39
+ /** Allocates one formatted number per request, in one statement per (company, period) group. */
40
+ export async function allocateNumbers(internals, definition, requests) {
41
+ const out = new Array(requests.length);
42
+ if (requests.length === 0)
43
+ return out;
44
+ await ensureTable(internals.driver);
45
+ for (const group of groupRequests(definition, requests)) {
46
+ const statement = allocateStatement(definition, group.company, group.period, group.members.length);
47
+ const rows = definition.gapless
48
+ ? await internals.query(statement) // row lock held until commit: no gaps
49
+ : await internals.driver.transaction({ isolation: 'read committed' }, (conn) => conn.query(statement)); // committed at once: no blocking, gaps on rollback
50
+ const first = Number(rows[0]?.first);
51
+ const numbers = numbersFrom(definition, first, group.members.length);
52
+ group.members.forEach((index, i) => {
53
+ out[index] = formatNumber(definition, numbers[i], requests[index]?.date ?? group.date);
54
+ });
55
+ }
56
+ return out;
57
+ }
58
+ /** Sequence fields of a model with their options. */
59
+ export function sequenceFields(model) {
60
+ return Object.entries(model.fields)
61
+ .filter(([, f]) => f.sequence !== undefined)
62
+ .map(([key, field]) => ({
63
+ key,
64
+ field,
65
+ options: field.sequence,
66
+ }));
67
+ }
68
+ function definitionOf(internals, model, key, code) {
69
+ const definition = internals.registry.sequences.get(code);
70
+ if (definition === undefined)
71
+ throw new UnknownSequenceError(code, `${model.name}.${key}`);
72
+ return definition;
73
+ }
74
+ function companyOf(model, values, internals) {
75
+ if (model.companyScoped === undefined)
76
+ return internals.env.companyId;
77
+ const company = values.get('company');
78
+ return typeof company === 'number' ? company : null;
79
+ }
80
+ function dateOf(values, dateField, fallback) {
81
+ const value = dateField === undefined ? undefined : values.get(dateField);
82
+ if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value))
83
+ return value.slice(0, 10);
84
+ if (value instanceof Date)
85
+ return value.toISOString().slice(0, 10);
86
+ return fallback;
87
+ }
88
+ /** Fills the `on: 'create'` sequence fields of rows that have no value (RFC 0012 §7.4). */
89
+ export async function fillSequences(internals, model, rows) {
90
+ for (const { key, options } of sequenceFields(model)) {
91
+ if (options.on === 'manual')
92
+ continue;
93
+ const definition = definitionOf(internals, model, key, options.code);
94
+ const pending = rows.filter((r) => r.stored.get(key) === null || r.stored.get(key) === undefined);
95
+ if (pending.length === 0)
96
+ continue;
97
+ const today = internals.env.today();
98
+ const numbers = await allocateNumbers(internals, definition, pending.map((r) => ({
99
+ company: companyOf(model, r.stored, internals),
100
+ date: dateOf(r.stored, options.dateField, today),
101
+ })));
102
+ pending.forEach((r, i) => {
103
+ r.stored.set(key, numbers[i]);
104
+ });
105
+ }
106
+ }
107
+ /** `records.assignNumber(key, { date })`: numbers unnumbered records through the unit of work. */
108
+ export async function assignNumbers(host, model, ids, key, options) {
109
+ const { internals } = host;
110
+ const field = model.fields[key];
111
+ if (field === undefined || field.sequence === undefined) {
112
+ throw new ValidationError(model.name, [key], `'${key}' is not a sequence field.`, "Declare it with f.char({ sequence: { code, on: 'manual' } }).");
113
+ }
114
+ if (ids.length === 0)
115
+ return;
116
+ const definition = definitionOf(internals, model, key, field.sequence.code);
117
+ const needed = new Set(['id', key]);
118
+ if (model.companyScoped !== undefined)
119
+ needed.add('company');
120
+ if (field.sequence.dateField !== undefined)
121
+ needed.add(field.sequence.dateField);
122
+ await host.load(model, ids, { fields: needed, relations: new Map() });
123
+ const numbered = ids.filter((id) => {
124
+ const current = host.values(model.name, id)?.get(key);
125
+ return current !== null && current !== undefined && current !== UNNUMBERED;
126
+ });
127
+ if (numbered.length > 0) {
128
+ throw new ValidationError(model.name, [key], `record(s) ${numbered.join(', ')} already have a number.`, 'A document is numbered once; assignNumber() only takes unnumbered records.');
129
+ }
130
+ const today = internals.env.today();
131
+ const numbers = await allocateNumbers(internals, definition, ids.map((id) => {
132
+ const values = host.values(model.name, id, true);
133
+ return {
134
+ company: companyOf(model, values, internals),
135
+ date: options.date ?? dateOf(values, field.sequence?.dateField, today),
136
+ };
137
+ }));
138
+ ids.forEach((id, i) => {
139
+ const values = host.values(model.name, id, true);
140
+ internals.journal({
141
+ kind: 'value',
142
+ model: model.name,
143
+ id,
144
+ key,
145
+ had: values.has(key),
146
+ prev: values.get(key),
147
+ wasDirty: internals.isDirty(model.name, id, key),
148
+ });
149
+ trackChange(internals, model, id, key, values.get(key), numbers[i], (k) => values.get(k));
150
+ values.set(key, numbers[i]);
151
+ internals.markDirty(model.name, id, key);
152
+ });
153
+ internals.trigger(model.name, key, ids);
154
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Maps PostgreSQL constraint violations to typed core errors carrying the declared message (RFC 0009 §7.2).
3
+ */
4
+ import type { Registry } from '../registry/registry.js';
5
+ /** The core error for a driver constraint violation, or the original error when no model declares the constraint. */
6
+ export declare function mapConstraintError(registry: Registry, error: unknown): unknown;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Maps PostgreSQL constraint violations to typed core errors carrying the declared message (RFC 0009 §7.2).
3
+ */
4
+ import { ConstraintViolationError } from '../errors.js';
5
+ const HINTS = {
6
+ unique: 'Change the value so it is unique, or update the existing record instead.',
7
+ check: 'Correct the value so it satisfies the rule.',
8
+ exclusion: 'Change the value so it does not overlap an existing record.',
9
+ foreign_key: 'Reference an existing record, or remove the records that still reference it first.',
10
+ };
11
+ /** The core error for a driver constraint violation, or the original error when no model declares the constraint. */
12
+ export function mapConstraintError(registry, error) {
13
+ // Shape-checked rather than instanceof: the driver's error class may come from another copy of the package.
14
+ if (!(error instanceof Error))
15
+ return error;
16
+ const { code, kind, constraint: name, } = error;
17
+ if (code !== 'CONSTRAINT_VIOLATION' || typeof name !== 'string')
18
+ return error;
19
+ if (kind !== 'unique' && kind !== 'check' && kind !== 'exclusion' && kind !== 'foreign_key')
20
+ return error;
21
+ for (const { model } of registry.models.values()) {
22
+ for (const c of model.sqlConstraints) {
23
+ if (c.name !== name)
24
+ continue;
25
+ return new ConstraintViolationError(model.name, c.key, kind, c.fields, c.message, HINTS[kind], {
26
+ cause: error,
27
+ });
28
+ }
29
+ if (kind === 'foreign_key') {
30
+ for (const [key, field] of Object.entries(model.fields)) {
31
+ if (field.kind !== 'many2one' || `${model.table}_${model.columns[key] ?? ''}_fkey` !== name)
32
+ continue;
33
+ const target = field.target ?? '?';
34
+ return new ConstraintViolationError(model.name, key, kind, [key], `'${key}' references a ${target} record that does not exist, or a ${model.name} record still references the ${target} record being deleted.`, HINTS.foreign_key, { cause: error });
35
+ }
36
+ }
37
+ }
38
+ return error;
39
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Running a state transition (RFC 0010 §7.2): validate the source states, run the guard, run the events, write the
3
+ * state through the unit of work.
4
+ */
5
+ import type { AnyModel } from '../model/model.js';
6
+ import type { ComputeHost } from './compute.js';
7
+ /** Runs transition `name` of state field `key` on `ids` of `model`. */
8
+ export declare function runTransition(host: ComputeHost, model: AnyModel, ids: readonly number[], key: string, name: string): Promise<void>;
9
+ /** Transition names available from the current state of one record (state must be loaded). */
10
+ export declare function availableTransitions(model: AnyModel, key: string, state: unknown): string[];