shutro 0.0.0-stage → 0.2.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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/dist/audit/index.d.ts +59 -0
  4. package/dist/audit/index.js +96 -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 +164 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +49 -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 +84 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +249 -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/cli/resolve.d.ts +2 -0
  28. package/dist/cli/resolve.js +28 -0
  29. package/dist/core/compute/graph.d.ts +52 -0
  30. package/dist/core/compute/graph.js +162 -0
  31. package/dist/core/data/data.d.ts +59 -0
  32. package/dist/core/data/data.js +119 -0
  33. package/dist/core/data/load.d.ts +37 -0
  34. package/dist/core/data/load.js +236 -0
  35. package/dist/core/env/env.d.ts +468 -0
  36. package/dist/core/env/env.js +916 -0
  37. package/dist/core/env/identity.d.ts +43 -0
  38. package/dist/core/env/identity.js +65 -0
  39. package/dist/core/env/inspector.d.ts +55 -0
  40. package/dist/core/env/inspector.js +85 -0
  41. package/dist/core/env/time.d.ts +12 -0
  42. package/dist/core/env/time.js +38 -0
  43. package/dist/core/errors.d.ts +256 -0
  44. package/dist/core/errors.js +360 -0
  45. package/dist/core/events/events.d.ts +44 -0
  46. package/dist/core/events/events.js +58 -0
  47. package/dist/core/events/workers.d.ts +56 -0
  48. package/dist/core/events/workers.js +155 -0
  49. package/dist/core/index.d.ts +51 -0
  50. package/dist/core/index.js +42 -0
  51. package/dist/core/model/company.d.ts +6 -0
  52. package/dist/core/model/company.js +31 -0
  53. package/dist/core/model/faces.d.ts +42 -0
  54. package/dist/core/model/faces.js +1 -0
  55. package/dist/core/model/field.d.ts +479 -0
  56. package/dist/core/model/field.js +461 -0
  57. package/dist/core/model/generated.d.ts +77 -0
  58. package/dist/core/model/generated.js +1 -0
  59. package/dist/core/model/id.d.ts +33 -0
  60. package/dist/core/model/id.js +4 -0
  61. package/dist/core/model/model.d.ts +387 -0
  62. package/dist/core/model/model.js +566 -0
  63. package/dist/core/model/partition.d.ts +31 -0
  64. package/dist/core/model/partition.js +71 -0
  65. package/dist/core/model/related.d.ts +17 -0
  66. package/dist/core/model/related.js +60 -0
  67. package/dist/core/model/typed.d.ts +107 -0
  68. package/dist/core/model/typed.js +46 -0
  69. package/dist/core/money/currency.d.ts +39 -0
  70. package/dist/core/money/currency.js +37 -0
  71. package/dist/core/money/decimal.d.ts +26 -0
  72. package/dist/core/money/decimal.js +51 -0
  73. package/dist/core/money/fx.d.ts +68 -0
  74. package/dist/core/money/fx.js +124 -0
  75. package/dist/core/money/money.d.ts +84 -0
  76. package/dist/core/money/money.js +173 -0
  77. package/dist/core/money/quantity.d.ts +67 -0
  78. package/dist/core/money/quantity.js +108 -0
  79. package/dist/core/money/rounding.d.ts +11 -0
  80. package/dist/core/money/rounding.js +12 -0
  81. package/dist/core/recordset/aggregate.d.ts +22 -0
  82. package/dist/core/recordset/aggregate.js +258 -0
  83. package/dist/core/recordset/audit.d.ts +33 -0
  84. package/dist/core/recordset/audit.js +262 -0
  85. package/dist/core/recordset/compute.d.ts +36 -0
  86. package/dist/core/recordset/compute.js +414 -0
  87. package/dist/core/recordset/constraints.d.ts +9 -0
  88. package/dist/core/recordset/constraints.js +61 -0
  89. package/dist/core/recordset/domain.d.ts +31 -0
  90. package/dist/core/recordset/domain.js +300 -0
  91. package/dist/core/recordset/onchange.d.ts +43 -0
  92. package/dist/core/recordset/onchange.js +240 -0
  93. package/dist/core/recordset/recordset.d.ts +110 -0
  94. package/dist/core/recordset/recordset.js +789 -0
  95. package/dist/core/recordset/relations.d.ts +15 -0
  96. package/dist/core/recordset/relations.js +13 -0
  97. package/dist/core/recordset/rls.d.ts +15 -0
  98. package/dist/core/recordset/rls.js +108 -0
  99. package/dist/core/recordset/security.d.ts +56 -0
  100. package/dist/core/recordset/security.js +269 -0
  101. package/dist/core/recordset/sequences.d.ts +31 -0
  102. package/dist/core/recordset/sequences.js +154 -0
  103. package/dist/core/recordset/source.d.ts +9 -0
  104. package/dist/core/recordset/source.js +19 -0
  105. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  106. package/dist/core/recordset/sqlErrors.js +39 -0
  107. package/dist/core/recordset/transitions.d.ts +10 -0
  108. package/dist/core/recordset/transitions.js +80 -0
  109. package/dist/core/recordset/types.d.ts +415 -0
  110. package/dist/core/recordset/types.js +8 -0
  111. package/dist/core/recordset/values.d.ts +33 -0
  112. package/dist/core/recordset/values.js +177 -0
  113. package/dist/core/recordset/writes.d.ts +42 -0
  114. package/dist/core/recordset/writes.js +786 -0
  115. package/dist/core/registry/ddl.d.ts +31 -0
  116. package/dist/core/registry/ddl.js +174 -0
  117. package/dist/core/registry/extension.d.ts +94 -0
  118. package/dist/core/registry/extension.js +90 -0
  119. package/dist/core/registry/module.d.ts +89 -0
  120. package/dist/core/registry/module.js +98 -0
  121. package/dist/core/registry/registry.d.ts +130 -0
  122. package/dist/core/registry/registry.js +591 -0
  123. package/dist/core/security/runtime.d.ts +102 -0
  124. package/dist/core/security/runtime.js +232 -0
  125. package/dist/driver-pg/driver.d.ts +88 -0
  126. package/dist/driver-pg/driver.js +177 -0
  127. package/dist/driver-pg/errors.d.ts +72 -0
  128. package/dist/driver-pg/errors.js +182 -0
  129. package/dist/driver-pg/index.d.ts +7 -0
  130. package/dist/driver-pg/index.js +7 -0
  131. package/dist/i18n/index.d.ts +25 -0
  132. package/dist/i18n/index.js +51 -0
  133. package/dist/migrate/apply.d.ts +78 -0
  134. package/dist/migrate/apply.js +167 -0
  135. package/dist/migrate/catalog.d.ts +10 -0
  136. package/dist/migrate/catalog.js +122 -0
  137. package/dist/migrate/diff.d.ts +98 -0
  138. package/dist/migrate/diff.js +160 -0
  139. package/dist/migrate/errors.d.ts +21 -0
  140. package/dist/migrate/errors.js +31 -0
  141. package/dist/migrate/index.d.ts +18 -0
  142. package/dist/migrate/index.js +18 -0
  143. package/dist/migrate/render.d.ts +5 -0
  144. package/dist/migrate/render.js +101 -0
  145. package/dist/migrate/schema.d.ts +61 -0
  146. package/dist/migrate/schema.js +233 -0
  147. package/dist/security/index.d.ts +147 -0
  148. package/dist/security/index.js +278 -0
  149. package/dist/sequence/index.d.ts +63 -0
  150. package/dist/sequence/index.js +106 -0
  151. package/dist/sql/ast.d.ts +49 -0
  152. package/dist/sql/ast.js +47 -0
  153. package/dist/sql/builder/builder.d.ts +215 -0
  154. package/dist/sql/builder/builder.js +308 -0
  155. package/dist/sql/builder/expression.d.ts +80 -0
  156. package/dist/sql/builder/expression.js +126 -0
  157. package/dist/sql/compile.d.ts +18 -0
  158. package/dist/sql/compile.js +41 -0
  159. package/dist/sql/errors.d.ts +13 -0
  160. package/dist/sql/errors.js +16 -0
  161. package/dist/sql/index.d.ts +19 -0
  162. package/dist/sql/index.js +19 -0
  163. package/dist/sql/tag.d.ts +47 -0
  164. package/dist/sql/tag.js +123 -0
  165. package/package.json +82 -4
@@ -0,0 +1,233 @@
1
+ /**
2
+ * The intended database schema, derived from a registry (RFC 0001 §7.5 naming, RFC 0002 origins). The same shape
3
+ * describes the live schema read from `pg_catalog`, so the two can be diffed directly.
4
+ */
5
+ import { columnDefault, junctionTable, snakeCase, targetOf, } from '../core/index.js';
6
+ import { compile } from '../sql/index.js';
7
+ import { MigrationError } from './errors.js';
8
+ /** Maps the builders' type spellings to `format_type` output. */
9
+ export function canonicalType(pgType) {
10
+ const m = /^varchar\((\d+)\)$/.exec(pgType);
11
+ if (m)
12
+ return `character varying(${m[1]})`;
13
+ if (pgType === 'timestamptz')
14
+ return 'timestamp with time zone';
15
+ return pgType.replace(/\s+/g, ' ').replace(/numeric\((\d+), ?(\d+)\)/, 'numeric($1,$2)');
16
+ }
17
+ /** A SQL literal for a backfill (`'x'`, `1`, `true`). */
18
+ export function literalOf(value) {
19
+ if (typeof value === 'boolean')
20
+ return value ? 'true' : 'false';
21
+ if (typeof value === 'number' && Number.isFinite(value))
22
+ return String(value);
23
+ if (typeof value === 'string')
24
+ return `'${value.replaceAll("'", "''")}'`;
25
+ if (typeof value === 'object' &&
26
+ value !== null &&
27
+ typeof value.toFixed === 'function')
28
+ return `'${value.toFixed()}'`;
29
+ return null;
30
+ }
31
+ function fragmentText(fragment, what) {
32
+ const compiled = compile(fragment);
33
+ if (compiled.params.length > 0) {
34
+ throw new MigrationError(`${what} contains ${compiled.params.length} parameter(s).`, 'DDL cannot take bind parameters: write the expression with literals only, e.g. sql`amount >= 0`.');
35
+ }
36
+ return compiled.text;
37
+ }
38
+ function columnOf(key, field, column) {
39
+ if (key === 'id')
40
+ return {
41
+ name: column,
42
+ type: 'bigint',
43
+ nullable: false,
44
+ default: null,
45
+ identity: true,
46
+ backfill: null,
47
+ };
48
+ const type = field.kind === 'many2one' && !field.companyDependent ? 'bigint' : canonicalType(field.pgType);
49
+ const dbDefault = columnDefault(key, field);
50
+ const backfill = typeof field.default === 'function' ? null : literalOf(field.default);
51
+ return {
52
+ name: column,
53
+ type,
54
+ nullable: !field.required || field.computed, // stored computes are filled after insert (RFC 0008 §7.6)
55
+ default: dbDefault,
56
+ identity: false,
57
+ backfill,
58
+ };
59
+ }
60
+ const ON_DELETE = {
61
+ restrict: 'RESTRICT',
62
+ cascade: 'CASCADE',
63
+ 'set null': 'SET NULL',
64
+ };
65
+ /** Builds the intended schema for every model in the registry. */
66
+ export function desiredSchema(registry) {
67
+ const tables = {};
68
+ const extensions = new Set();
69
+ for (const { model } of registry.models.values()) {
70
+ const columns = {};
71
+ const foreignKeys = {};
72
+ const indexes = {};
73
+ for (const [key, field] of Object.entries(model.fields)) {
74
+ const column = model.columns[key];
75
+ if (column === undefined) {
76
+ if (field.kind === 'many2many') {
77
+ const target = registry.get(targetOf(field) ?? '').model;
78
+ const j = junctionTable(model, field, target);
79
+ tables[j.table] = {
80
+ name: j.table,
81
+ columns: {
82
+ [j.sourceColumn]: {
83
+ name: j.sourceColumn,
84
+ type: 'bigint',
85
+ nullable: false,
86
+ default: null,
87
+ identity: false,
88
+ backfill: null,
89
+ },
90
+ [j.targetColumn]: {
91
+ name: j.targetColumn,
92
+ type: 'bigint',
93
+ nullable: false,
94
+ default: null,
95
+ identity: false,
96
+ backfill: null,
97
+ },
98
+ },
99
+ primaryKey: [j.sourceColumn, j.targetColumn],
100
+ foreignKeys: {
101
+ [`${j.table}_${j.sourceColumn}_fkey`]: {
102
+ column: j.sourceColumn,
103
+ references: j.sourceTable,
104
+ onDelete: 'CASCADE',
105
+ },
106
+ [`${j.table}_${j.targetColumn}_fkey`]: {
107
+ column: j.targetColumn,
108
+ references: j.targetTable,
109
+ onDelete: 'CASCADE',
110
+ },
111
+ },
112
+ uniques: {},
113
+ checks: {},
114
+ indexes: {},
115
+ };
116
+ }
117
+ continue;
118
+ }
119
+ columns[column] = columnOf(key, field, column);
120
+ if (field.kind === 'many2one' &&
121
+ field.foreignKey !== false &&
122
+ !field.companyDependent) {
123
+ const target = registry.get(targetOf(field) ?? '').model;
124
+ foreignKeys[`${model.table}_${column}_fkey`] = {
125
+ column,
126
+ references: target.table,
127
+ onDelete: ON_DELETE[field.ondelete] ?? 'RESTRICT',
128
+ };
129
+ }
130
+ if (field.index !== undefined && key !== 'id') {
131
+ const name = `${model.table}_${column}_idx`;
132
+ if (field.index === 'trigram') {
133
+ extensions.add('pg_trgm');
134
+ indexes[name] = {
135
+ columns: [column],
136
+ unique: false,
137
+ method: 'gin',
138
+ opclass: 'gin_trgm_ops',
139
+ };
140
+ }
141
+ else if (field.index === 'brin')
142
+ indexes[name] = { columns: [column], unique: false, method: 'brin' };
143
+ else
144
+ indexes[name] = { columns: [column], unique: field.index === 'unique', method: 'btree' };
145
+ }
146
+ }
147
+ for (const index of model.indexes) {
148
+ indexes[index.name] = {
149
+ columns: [...index.columns],
150
+ unique: index.unique,
151
+ method: index.method,
152
+ ...(index.where === undefined
153
+ ? {}
154
+ : { where: fragmentText(index.where, `index ${index.name}`) }),
155
+ };
156
+ }
157
+ const uniques = {};
158
+ const checks = {};
159
+ for (const c of model.sqlConstraints) {
160
+ if (c.kind === 'unique') {
161
+ if (c.where !== undefined) {
162
+ // A partial unique constraint is a unique partial index in PostgreSQL.
163
+ indexes[c.name] = {
164
+ columns: [...c.columns],
165
+ unique: true,
166
+ method: 'btree',
167
+ where: fragmentText(c.where, `constraint ${c.name}`),
168
+ };
169
+ }
170
+ else
171
+ uniques[c.name] = [...c.columns];
172
+ }
173
+ else if (c.check !== undefined)
174
+ checks[c.name] = fragmentText(c.check, `constraint ${c.name}`);
175
+ }
176
+ tables[model.table] = {
177
+ name: model.table,
178
+ columns,
179
+ primaryKey: model.partition === undefined ? ['id'] : ['id', model.columns[model.partition.key] ?? ''],
180
+ foreignKeys,
181
+ uniques,
182
+ checks,
183
+ indexes,
184
+ ...(model.partition === undefined
185
+ ? {}
186
+ : {
187
+ partition: { by: model.partition.by, column: model.columns[model.partition.key] ?? '' },
188
+ }),
189
+ };
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
+ }
227
+ return { tables, extensions: [...extensions].sort() };
228
+ }
229
+ /** Column name of a field key, as `defineModel` derives it (exported for callers building names). */
230
+ export function columnName(key, many2one) {
231
+ const snake = snakeCase(key);
232
+ return many2one ? `${snake}_id` : snake;
233
+ }
@@ -0,0 +1,147 @@
1
+ /** A security group. `implies` are inherited: a member of `sale.manager` is also a member of `sale.user`. */
2
+ export interface GroupDefinition {
3
+ /** `module.name`, e.g. `'sale.user'`. */
4
+ readonly code: string;
5
+ readonly label: string;
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[];
23
+ }
24
+ export declare const GROUP_CODE: RegExp;
25
+ /** A security declaration that cannot be used. */
26
+ export declare class SecurityDefinitionError extends Error {
27
+ readonly hint: string;
28
+ constructor(problem: string, hint: string);
29
+ }
30
+ /** Validates a group. */
31
+ export declare function defineGroup(input: {
32
+ readonly code: string;
33
+ readonly label?: string;
34
+ readonly implies?: readonly string[];
35
+ /** Members can do everything, without grants (see {@link GroupDefinition.administrator}). */
36
+ readonly administrator?: boolean;
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;
44
+ /** The transitive closure of `codes` over `implies` (unknown codes are kept as given). */
45
+ export declare function groupClosure(groups: ReadonlyMap<string, GroupDefinition>, codes: Iterable<string>): Set<string>;
46
+ /** What a group may do with a model. */
47
+ export type Perm = 'read' | 'write' | 'create' | 'unlink' | 'export' | 'import';
48
+ export declare const PERMS: readonly Perm[];
49
+ /** Group code → permissions. Absence means denied (default deny, RFC 0014 §7.2). */
50
+ export type AccessSpec = Readonly<Record<string, readonly Perm[]>>;
51
+ /** Validates an access declaration. */
52
+ export declare function assertAccessSpec(spec: AccessSpec, where: string): void;
53
+ /** True when any of the user's (closed) groups grants `perm`. */
54
+ export declare function allowed(spec: AccessSpec, groups: ReadonlySet<string>, perm: Perm): boolean;
55
+ /** Merges access declarations (an extension adds permissions, never removes). */
56
+ export declare function mergeAccess(base: AccessSpec, extra: AccessSpec): AccessSpec;
57
+ /** Operations a rule can restrict. */
58
+ export type RulePerm = 'read' | 'write' | 'create' | 'unlink';
59
+ /** A record rule: a domain over the model with `{ $env: ... }` placeholders (RFC 0005 §7.1). */
60
+ export interface RuleSpec {
61
+ /** Group codes the rule applies to, or `'global'` for everyone (including users with other rules). */
62
+ readonly groups: readonly string[] | 'global';
63
+ readonly perms: readonly RulePerm[];
64
+ /** The domain (serializable; `{ $env: 'uid' | 'companyId' | 'companyIds' }` where a value goes). */
65
+ readonly domain: Readonly<Record<string, unknown>>;
66
+ readonly label?: string;
67
+ }
68
+ /** Validates a rule. */
69
+ export declare function assertRuleSpec(rule: RuleSpec, where: string): void;
70
+ /** The rules that apply to a user for an operation: globals (ANDed) and group rules (ORed). */
71
+ export interface ApplicableRules {
72
+ readonly globals: readonly RuleSpec[];
73
+ readonly groupRules: readonly RuleSpec[];
74
+ /** True when at least one group rule for the operation exists in the model at all (then users without any applicable group rule are unrestricted by group rules, as in Odoo). */
75
+ readonly hasGroupRules: boolean;
76
+ }
77
+ /** Splits a model's rules for `perm` into what applies to `groups` (RFC 0014 §7.3). */
78
+ export declare function applicableRules(rules: Readonly<Record<string, RuleSpec>>, groups: ReadonlySet<string>, perm: RulePerm): ApplicableRules;
79
+ /** The environment values placeholders may name. */
80
+ export interface PlaceholderEnv {
81
+ readonly uid: number;
82
+ readonly companyId: number;
83
+ readonly companyIds: readonly number[];
84
+ }
85
+ /** Replaces `{ $env: name }` objects in a domain with the environment's values. */
86
+ export declare function resolvePlaceholders(domain: unknown, env: PlaceholderEnv): unknown;
87
+ /** Who may read / write a field. Empty means everyone with model access. */
88
+ export interface FieldGroups {
89
+ readonly read: readonly string[];
90
+ readonly write: readonly string[];
91
+ }
92
+ /** `groups: ['hr.manager']` (both) or `{ read: [...], write: [...] }`. */
93
+ export type FieldGroupsInput = readonly string[] | {
94
+ readonly read?: readonly string[];
95
+ readonly write?: readonly string[];
96
+ };
97
+ /** Normalizes a field's groups option. */
98
+ export declare function normalizeFieldGroups(input: FieldGroupsInput | undefined): FieldGroups;
99
+ /** True when the field has no restriction for `kind` or the user is in one of its groups. */
100
+ export declare function fieldAllowed(groups: FieldGroups, userGroups: ReadonlySet<string>, kind: 'read' | 'write'): boolean;
101
+ /** The session settings `shutro.run()` pushes (RFC 0003 §7.1) and RLS policies read. */
102
+ export declare const RLS_SETTINGS: Readonly<{
103
+ user: string;
104
+ company: string;
105
+ companies: string;
106
+ groups: string;
107
+ su: string;
108
+ }>;
109
+ /** SQL expressions for the placeholders, reading the session settings. */
110
+ export declare const RLS_PLACEHOLDERS: Readonly<Record<'uid' | 'companyId' | 'companyIds', string>>;
111
+ /** `true` when the session is a superuser scope. */
112
+ export declare const RLS_SU: string;
113
+ /** `true` when the session's groups intersect `codes`. */
114
+ export declare function rlsGroupCondition(codes: readonly string[]): string;
115
+ /** A policy to create. */
116
+ export interface PolicyInput {
117
+ readonly table: string;
118
+ readonly name: string;
119
+ readonly command: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE';
120
+ readonly permissive: boolean;
121
+ /** Boolean SQL over the table's columns and the session settings. */
122
+ readonly condition: string;
123
+ }
124
+ /** The DDL enabling RLS on a table and installing policies (idempotent: policies are dropped and recreated). */
125
+ export declare function rlsStatements(table: string, policies: readonly PolicyInput[]): string[];
126
+ /** Keys live in the application (env vars, a KMS), never in the database (RFC 0014 §7.6). */
127
+ export interface KeyRing {
128
+ /** The id new writes encrypt with. */
129
+ readonly current: string;
130
+ /** Every key still needed to decrypt stored values. 32 bytes each (raw or base64). */
131
+ readonly keys: Readonly<Record<string, Uint8Array | string>>;
132
+ }
133
+ /** Encryption failed or a token cannot be decrypted. */
134
+ export declare class EncryptionError extends Error {
135
+ readonly hint: string;
136
+ constructor(problem: string, hint: string, options?: {
137
+ readonly cause?: unknown;
138
+ });
139
+ }
140
+ /** Validates a key ring. */
141
+ export declare function createKeyRing(ring: KeyRing): KeyRing;
142
+ /** AES-256-GCM; the token names the key so rotation only changes `current`. */
143
+ export declare function encrypt(ring: KeyRing, plaintext: string): string;
144
+ /** True for a value produced by {@link encrypt}. */
145
+ export declare function isEncrypted(value: unknown): value is string;
146
+ /** Decrypts a token; a wrong key or a tampered token is an {@link EncryptionError}. */
147
+ export declare function decrypt(ring: KeyRing, token: string): string;
@@ -0,0 +1,278 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/security` (RFC 0014): the pure rules of access control — groups with inheritance, model ACL, record rules
4
+ * (which rules apply, how they combine), field-level groups, the PostgreSQL RLS policy text, and field encryption
5
+ * with keys that never enter the database. Core applies them; applications and Kosh can call them directly.
6
+ */
7
+ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
8
+ export const GROUP_CODE = /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/;
9
+ /** A security declaration that cannot be used. */
10
+ export class SecurityDefinitionError extends Error {
11
+ hint;
12
+ constructor(problem, hint) {
13
+ super(`${problem} ${hint}`);
14
+ this.name = 'SecurityDefinitionError';
15
+ this.hint = hint;
16
+ }
17
+ }
18
+ /** Validates a group. */
19
+ export function defineGroup(input) {
20
+ if (typeof input.code !== 'string' || !GROUP_CODE.test(input.code)) {
21
+ throw new SecurityDefinitionError(`${JSON.stringify(input.code)} is not a group code.`, "Use 'module.name', e.g. 'sale.user' or 'account.manager'.");
22
+ }
23
+ for (const code of input.implies ?? []) {
24
+ if (!GROUP_CODE.test(code))
25
+ throw new SecurityDefinitionError(`Group '${input.code}' implies ${JSON.stringify(code)}, which is not a group code.`, "Use 'module.name'.");
26
+ }
27
+ return Object.freeze({
28
+ code: input.code,
29
+ label: input.label ?? input.code,
30
+ implies: Object.freeze([...(input.implies ?? [])]),
31
+ administrator: input.administrator === true,
32
+ });
33
+ }
34
+ /** Declares a feature permission. @throws {SecurityDefinitionError} for malformed codes. */
35
+ export function definePermission(input) {
36
+ if (typeof input.code !== 'string' || !GROUP_CODE.test(input.code)) {
37
+ throw new SecurityDefinitionError(`${JSON.stringify(input.code)} is not a permission code.`, "Use 'module.name', e.g. 'sale.discount_approve'.");
38
+ }
39
+ for (const code of input.groups) {
40
+ if (!GROUP_CODE.test(code))
41
+ throw new SecurityDefinitionError(`Permission '${input.code}' is granted to ${JSON.stringify(code)}, which is not a group code.`, "Use 'module.name'.");
42
+ }
43
+ return Object.freeze({
44
+ code: input.code,
45
+ label: input.label ?? input.code,
46
+ groups: Object.freeze([...input.groups]),
47
+ });
48
+ }
49
+ /** The transitive closure of `codes` over `implies` (unknown codes are kept as given). */
50
+ export function groupClosure(groups, codes) {
51
+ const out = new Set();
52
+ const stack = [...codes];
53
+ while (stack.length > 0) {
54
+ const code = stack.pop();
55
+ if (out.has(code))
56
+ continue;
57
+ out.add(code);
58
+ for (const implied of groups.get(code)?.implies ?? [])
59
+ stack.push(implied);
60
+ }
61
+ return out;
62
+ }
63
+ export const PERMS = Object.freeze([
64
+ 'read',
65
+ 'write',
66
+ 'create',
67
+ 'unlink',
68
+ 'export',
69
+ 'import',
70
+ ]);
71
+ /** Validates an access declaration. */
72
+ export function assertAccessSpec(spec, where) {
73
+ for (const [group, perms] of Object.entries(spec)) {
74
+ if (!GROUP_CODE.test(group))
75
+ throw new SecurityDefinitionError(`${where}: access group ${JSON.stringify(group)} is not a group code.`, "Use 'module.name'.");
76
+ if (!Array.isArray(perms) || perms.some((p) => !PERMS.includes(p)))
77
+ throw new SecurityDefinitionError(`${where}: access of '${group}' lists an unknown permission.`, `Use: ${PERMS.join(', ')}.`);
78
+ }
79
+ }
80
+ /** True when any of the user's (closed) groups grants `perm`. */
81
+ export function allowed(spec, groups, perm) {
82
+ for (const [group, perms] of Object.entries(spec)) {
83
+ if (groups.has(group) && perms.includes(perm))
84
+ return true;
85
+ }
86
+ return false;
87
+ }
88
+ /** Merges access declarations (an extension adds permissions, never removes). */
89
+ export function mergeAccess(base, extra) {
90
+ const out = {};
91
+ for (const [group, perms] of Object.entries(base))
92
+ out[group] = [...perms];
93
+ for (const [group, perms] of Object.entries(extra)) {
94
+ const current = out[group] ?? [];
95
+ for (const p of perms)
96
+ if (!current.includes(p))
97
+ current.push(p);
98
+ out[group] = current;
99
+ }
100
+ return out;
101
+ }
102
+ const RULE_PERMS = Object.freeze(['read', 'write', 'create', 'unlink']);
103
+ /** Validates a rule. */
104
+ export function assertRuleSpec(rule, where) {
105
+ if (rule.groups !== 'global' &&
106
+ (!Array.isArray(rule.groups) || rule.groups.some((g) => !GROUP_CODE.test(g))))
107
+ throw new SecurityDefinitionError(`${where}: groups must be 'global' or group codes.`, "Use groups: ['sale.user'] or groups: 'global'.");
108
+ if (!Array.isArray(rule.perms) ||
109
+ rule.perms.length === 0 ||
110
+ rule.perms.some((p) => !RULE_PERMS.includes(p)))
111
+ throw new SecurityDefinitionError(`${where}: perms lists an unknown permission.`, `Use a non-empty subset of: ${RULE_PERMS.join(', ')}.`);
112
+ if (typeof rule.domain !== 'object' || rule.domain === null || Array.isArray(rule.domain))
113
+ throw new SecurityDefinitionError(`${where}: domain must be an object.`, "E.g. { user: { $env: 'uid' } }.");
114
+ }
115
+ /** Splits a model's rules for `perm` into what applies to `groups` (RFC 0014 §7.3). */
116
+ export function applicableRules(rules, groups, perm) {
117
+ const globals = [];
118
+ const groupRules = [];
119
+ let hasGroupRules = false;
120
+ for (const rule of Object.values(rules)) {
121
+ if (!rule.perms.includes(perm))
122
+ continue;
123
+ if (rule.groups === 'global')
124
+ globals.push(rule);
125
+ else {
126
+ hasGroupRules = true;
127
+ if (rule.groups.some((g) => groups.has(g)))
128
+ groupRules.push(rule);
129
+ }
130
+ }
131
+ return { globals, groupRules, hasGroupRules };
132
+ }
133
+ /** Replaces `{ $env: name }` objects in a domain with the environment's values. */
134
+ export function resolvePlaceholders(domain, env) {
135
+ if (Array.isArray(domain))
136
+ return domain.map((d) => resolvePlaceholders(d, env));
137
+ if (typeof domain !== 'object' || domain === null)
138
+ return domain;
139
+ const keys = Object.keys(domain);
140
+ if (keys.length === 1 && keys[0] === '$env') {
141
+ const name = domain.$env;
142
+ if (name === 'uid')
143
+ return env.uid;
144
+ if (name === 'companyId')
145
+ return env.companyId;
146
+ if (name === 'companyIds')
147
+ return [...env.companyIds];
148
+ throw new SecurityDefinitionError(`Unknown placeholder { $env: ${JSON.stringify(name)} }.`, "Use 'uid', 'companyId' or 'companyIds'.");
149
+ }
150
+ const out = {};
151
+ for (const [k, v] of Object.entries(domain))
152
+ out[k] = resolvePlaceholders(v, env);
153
+ return out;
154
+ }
155
+ /** Normalizes a field's groups option. */
156
+ export function normalizeFieldGroups(input) {
157
+ if (input === undefined)
158
+ return Object.freeze({ read: Object.freeze([]), write: Object.freeze([]) });
159
+ if (Array.isArray(input)) {
160
+ const list = Object.freeze([...input]);
161
+ return Object.freeze({ read: list, write: list });
162
+ }
163
+ const obj = input;
164
+ const read = Object.freeze([...(obj.read ?? [])]);
165
+ // Writing implies reading: a write-only field would be unreadable by its own writers.
166
+ const write = Object.freeze([...(obj.write ?? obj.read ?? [])]);
167
+ return Object.freeze({ read, write });
168
+ }
169
+ /** True when the field has no restriction for `kind` or the user is in one of its groups. */
170
+ export function fieldAllowed(groups, userGroups, kind) {
171
+ const required = kind === 'read' ? groups.read : groups.write;
172
+ return required.length === 0 || required.some((g) => userGroups.has(g));
173
+ }
174
+ // ---------------------------------------------------------------------------------------------------- RLS
175
+ /** The session settings `shutro.run()` pushes (RFC 0003 §7.1) and RLS policies read. */
176
+ export const RLS_SETTINGS = Object.freeze({
177
+ user: 'shutro.user_id',
178
+ company: 'shutro.company_id',
179
+ companies: 'shutro.company_ids',
180
+ groups: 'shutro.groups',
181
+ su: 'shutro.su',
182
+ });
183
+ function literal(value) {
184
+ return `'${value.replaceAll("'", "''")}'`;
185
+ }
186
+ /** SQL expressions for the placeholders, reading the session settings. */
187
+ export const RLS_PLACEHOLDERS = Object.freeze({
188
+ uid: `current_setting('${RLS_SETTINGS.user}', true)::bigint`,
189
+ companyId: `current_setting('${RLS_SETTINGS.company}', true)::bigint`,
190
+ companyIds: `string_to_array(trim(both '{}' from current_setting('${RLS_SETTINGS.companies}', true)), ',')::bigint[]`,
191
+ });
192
+ /** `true` when the session is a superuser scope. */
193
+ export const RLS_SU = `current_setting('${RLS_SETTINGS.su}', true) = '1'`;
194
+ /** `true` when the session's groups intersect `codes`. */
195
+ export function rlsGroupCondition(codes) {
196
+ if (codes.length === 0)
197
+ return 'false';
198
+ return `string_to_array(current_setting('${RLS_SETTINGS.groups}', true), ',') && ARRAY[${codes.map(literal).join(', ')}]::text[]`;
199
+ }
200
+ /** The DDL enabling RLS on a table and installing policies (idempotent: policies are dropped and recreated). */
201
+ export function rlsStatements(table, policies) {
202
+ const t = `"${table}"`;
203
+ const out = [
204
+ `ALTER TABLE ${t} ENABLE ROW LEVEL SECURITY`,
205
+ `ALTER TABLE ${t} FORCE ROW LEVEL SECURITY`,
206
+ ];
207
+ for (const p of policies) {
208
+ out.push(`DROP POLICY IF EXISTS "${p.name}" ON ${t}`);
209
+ const clause = p.command === 'INSERT'
210
+ ? `WITH CHECK (${p.condition})`
211
+ : p.command === 'UPDATE'
212
+ ? `USING (${p.condition}) WITH CHECK (${p.condition})`
213
+ : `USING (${p.condition})`;
214
+ out.push(`CREATE POLICY "${p.name}" ON ${t} AS ${p.permissive ? 'PERMISSIVE' : 'RESTRICTIVE'} FOR ${p.command} ${clause}`);
215
+ }
216
+ return out;
217
+ }
218
+ /** Encryption failed or a token cannot be decrypted. */
219
+ export class EncryptionError extends Error {
220
+ hint;
221
+ constructor(problem, hint, options) {
222
+ super(`${problem} ${hint}`, options);
223
+ this.name = 'EncryptionError';
224
+ this.hint = hint;
225
+ }
226
+ }
227
+ const TOKEN_PREFIX = 'shutro1';
228
+ function keyBytes(ring, id) {
229
+ const raw = ring.keys[id];
230
+ if (raw === undefined)
231
+ throw new EncryptionError(`No key '${id}' in the key ring.`, 'Keep every key that encrypted a stored value until the data is re-encrypted.');
232
+ const key = typeof raw === 'string' ? Buffer.from(raw, 'base64') : Buffer.from(raw);
233
+ if (key.length !== 32)
234
+ throw new EncryptionError(`Key '${id}' is ${key.length} bytes.`, 'Keys are 32 bytes (AES-256), raw or base64.');
235
+ return key;
236
+ }
237
+ /** Validates a key ring. */
238
+ export function createKeyRing(ring) {
239
+ keyBytes(ring, ring.current);
240
+ for (const id of Object.keys(ring.keys))
241
+ keyBytes(ring, id);
242
+ return Object.freeze({ current: ring.current, keys: Object.freeze({ ...ring.keys }) });
243
+ }
244
+ /** AES-256-GCM; the token names the key so rotation only changes `current`. */
245
+ export function encrypt(ring, plaintext) {
246
+ const key = keyBytes(ring, ring.current);
247
+ const iv = randomBytes(12);
248
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
249
+ const data = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
250
+ const tag = cipher.getAuthTag();
251
+ return [
252
+ TOKEN_PREFIX,
253
+ ring.current,
254
+ iv.toString('base64'),
255
+ tag.toString('base64'),
256
+ data.toString('base64'),
257
+ ].join(':');
258
+ }
259
+ /** True for a value produced by {@link encrypt}. */
260
+ export function isEncrypted(value) {
261
+ return typeof value === 'string' && value.startsWith(`${TOKEN_PREFIX}:`);
262
+ }
263
+ /** Decrypts a token; a wrong key or a tampered token is an {@link EncryptionError}. */
264
+ export function decrypt(ring, token) {
265
+ const parts = token.split(':');
266
+ if (parts.length !== 5 || parts[0] !== TOKEN_PREFIX)
267
+ throw new EncryptionError('The stored value is not an encrypted token.', 'Values of encrypted fields are written by the ORM; do not update the column by hand.');
268
+ const [, id = '', iv = '', tag = '', data = ''] = parts;
269
+ const key = keyBytes(ring, id);
270
+ try {
271
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'base64'));
272
+ decipher.setAuthTag(Buffer.from(tag, 'base64'));
273
+ return Buffer.concat([decipher.update(Buffer.from(data, 'base64')), decipher.final()]).toString('utf8');
274
+ }
275
+ catch (cause) {
276
+ throw new EncryptionError(`The value encrypted with key '${id}' cannot be decrypted.`, 'The key is wrong or the stored value was tampered with.', { cause });
277
+ }
278
+ }