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.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/audit/index.d.ts +57 -0
- package/dist/audit/index.js +94 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +11 -0
- package/dist/cli/cli.d.ts +10 -0
- package/dist/cli/cli.js +149 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +47 -0
- package/dist/cli/errors.d.ts +16 -0
- package/dist/cli/errors.js +23 -0
- package/dist/cli/generate/generate.d.ts +33 -0
- package/dist/cli/generate/generate.js +82 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +200 -0
- package/dist/cli/index.d.ts +12 -0
- package/dist/cli/index.js +12 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +65 -0
- package/dist/cli/inspect.d.ts +10 -0
- package/dist/cli/inspect.js +82 -0
- package/dist/cli/packages.d.ts +6 -0
- package/dist/cli/packages.js +6 -0
- package/dist/cli/project.d.ts +18 -0
- package/dist/cli/project.js +39 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/env/env.d.ts +295 -0
- package/dist/core/env/env.js +631 -0
- package/dist/core/env/identity.d.ts +33 -0
- package/dist/core/env/identity.js +49 -0
- package/dist/core/env/inspector.d.ts +55 -0
- package/dist/core/env/inspector.js +85 -0
- package/dist/core/env/time.d.ts +12 -0
- package/dist/core/env/time.js +38 -0
- package/dist/core/errors.d.ts +242 -0
- package/dist/core/errors.js +339 -0
- package/dist/core/index.d.ts +43 -0
- package/dist/core/index.js +34 -0
- package/dist/core/model/company.d.ts +6 -0
- package/dist/core/model/company.js +31 -0
- package/dist/core/model/faces.d.ts +42 -0
- package/dist/core/model/faces.js +1 -0
- package/dist/core/model/field.d.ts +446 -0
- package/dist/core/model/field.js +398 -0
- package/dist/core/model/generated.d.ts +75 -0
- package/dist/core/model/generated.js +1 -0
- package/dist/core/model/id.d.ts +33 -0
- package/dist/core/model/id.js +4 -0
- package/dist/core/model/model.d.ts +347 -0
- package/dist/core/model/model.js +538 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -0
- package/dist/core/money/currency.d.ts +39 -0
- package/dist/core/money/currency.js +37 -0
- package/dist/core/money/decimal.d.ts +26 -0
- package/dist/core/money/decimal.js +51 -0
- package/dist/core/money/fx.d.ts +60 -0
- package/dist/core/money/fx.js +109 -0
- package/dist/core/money/money.d.ts +84 -0
- package/dist/core/money/money.js +173 -0
- package/dist/core/money/quantity.d.ts +67 -0
- package/dist/core/money/quantity.js +108 -0
- package/dist/core/money/rounding.d.ts +11 -0
- package/dist/core/money/rounding.js +12 -0
- package/dist/core/recordset/audit.d.ts +25 -0
- package/dist/core/recordset/audit.js +205 -0
- package/dist/core/recordset/compute.d.ts +34 -0
- package/dist/core/recordset/compute.js +405 -0
- package/dist/core/recordset/constraints.d.ts +9 -0
- package/dist/core/recordset/constraints.js +61 -0
- package/dist/core/recordset/domain.d.ts +27 -0
- package/dist/core/recordset/domain.js +228 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +207 -0
- package/dist/core/recordset/recordset.d.ts +101 -0
- package/dist/core/recordset/recordset.js +723 -0
- package/dist/core/recordset/relations.d.ts +15 -0
- package/dist/core/recordset/relations.js +13 -0
- package/dist/core/recordset/rls.d.ts +15 -0
- package/dist/core/recordset/rls.js +108 -0
- package/dist/core/recordset/security.d.ts +42 -0
- package/dist/core/recordset/security.js +184 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/sqlErrors.d.ts +6 -0
- package/dist/core/recordset/sqlErrors.js +39 -0
- package/dist/core/recordset/transitions.d.ts +10 -0
- package/dist/core/recordset/transitions.js +77 -0
- package/dist/core/recordset/types.d.ts +296 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +27 -0
- package/dist/core/recordset/values.js +147 -0
- package/dist/core/recordset/writes.d.ts +37 -0
- package/dist/core/recordset/writes.js +581 -0
- package/dist/core/registry/ddl.d.ts +22 -0
- package/dist/core/registry/ddl.js +127 -0
- package/dist/core/registry/extension.d.ts +94 -0
- package/dist/core/registry/extension.js +90 -0
- package/dist/core/registry/module.d.ts +80 -0
- package/dist/core/registry/module.js +96 -0
- package/dist/core/registry/registry.d.ts +105 -0
- package/dist/core/registry/registry.js +496 -0
- package/dist/driver-pg/driver.d.ts +86 -0
- package/dist/driver-pg/driver.js +176 -0
- package/dist/driver-pg/errors.d.ts +72 -0
- package/dist/driver-pg/errors.js +182 -0
- package/dist/driver-pg/index.d.ts +7 -0
- package/dist/driver-pg/index.js +7 -0
- package/dist/i18n/index.d.ts +25 -0
- package/dist/i18n/index.js +51 -0
- package/dist/migrate/apply.d.ts +78 -0
- package/dist/migrate/apply.js +167 -0
- package/dist/migrate/catalog.d.ts +10 -0
- package/dist/migrate/catalog.js +122 -0
- package/dist/migrate/diff.d.ts +98 -0
- package/dist/migrate/diff.js +160 -0
- package/dist/migrate/errors.d.ts +21 -0
- package/dist/migrate/errors.js +31 -0
- package/dist/migrate/index.d.ts +18 -0
- package/dist/migrate/index.js +18 -0
- package/dist/migrate/render.d.ts +5 -0
- package/dist/migrate/render.js +101 -0
- package/dist/migrate/schema.d.ts +61 -0
- package/dist/migrate/schema.js +195 -0
- package/dist/security/index.d.ts +123 -0
- package/dist/security/index.js +262 -0
- package/dist/sequence/index.d.ts +63 -0
- package/dist/sequence/index.js +106 -0
- package/dist/sql/ast.d.ts +49 -0
- package/dist/sql/ast.js +47 -0
- package/dist/sql/builder/builder.d.ts +215 -0
- package/dist/sql/builder/builder.js +308 -0
- package/dist/sql/builder/expression.d.ts +80 -0
- package/dist/sql/builder/expression.js +126 -0
- package/dist/sql/compile.d.ts +18 -0
- package/dist/sql/compile.js +41 -0
- package/dist/sql/errors.d.ts +13 -0
- package/dist/sql/errors.js +16 -0
- package/dist/sql/index.d.ts +19 -0
- package/dist/sql/index.js +19 -0
- package/dist/sql/tag.d.ts +42 -0
- package/dist/sql/tag.js +95 -0
- package/package.json +82 -4
|
@@ -0,0 +1,262 @@
|
|
|
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
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/** The transitive closure of `codes` over `implies` (unknown codes are kept as given). */
|
|
34
|
+
export function groupClosure(groups, codes) {
|
|
35
|
+
const out = new Set();
|
|
36
|
+
const stack = [...codes];
|
|
37
|
+
while (stack.length > 0) {
|
|
38
|
+
const code = stack.pop();
|
|
39
|
+
if (out.has(code))
|
|
40
|
+
continue;
|
|
41
|
+
out.add(code);
|
|
42
|
+
for (const implied of groups.get(code)?.implies ?? [])
|
|
43
|
+
stack.push(implied);
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
export const PERMS = Object.freeze([
|
|
48
|
+
'read',
|
|
49
|
+
'write',
|
|
50
|
+
'create',
|
|
51
|
+
'unlink',
|
|
52
|
+
'export',
|
|
53
|
+
'import',
|
|
54
|
+
]);
|
|
55
|
+
/** Validates an access declaration. */
|
|
56
|
+
export function assertAccessSpec(spec, where) {
|
|
57
|
+
for (const [group, perms] of Object.entries(spec)) {
|
|
58
|
+
if (!GROUP_CODE.test(group))
|
|
59
|
+
throw new SecurityDefinitionError(`${where}: access group ${JSON.stringify(group)} is not a group code.`, "Use 'module.name'.");
|
|
60
|
+
if (!Array.isArray(perms) || perms.some((p) => !PERMS.includes(p)))
|
|
61
|
+
throw new SecurityDefinitionError(`${where}: access of '${group}' lists an unknown permission.`, `Use: ${PERMS.join(', ')}.`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** True when any of the user's (closed) groups grants `perm`. */
|
|
65
|
+
export function allowed(spec, groups, perm) {
|
|
66
|
+
for (const [group, perms] of Object.entries(spec)) {
|
|
67
|
+
if (groups.has(group) && perms.includes(perm))
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
/** Merges access declarations (an extension adds permissions, never removes). */
|
|
73
|
+
export function mergeAccess(base, extra) {
|
|
74
|
+
const out = {};
|
|
75
|
+
for (const [group, perms] of Object.entries(base))
|
|
76
|
+
out[group] = [...perms];
|
|
77
|
+
for (const [group, perms] of Object.entries(extra)) {
|
|
78
|
+
const current = out[group] ?? [];
|
|
79
|
+
for (const p of perms)
|
|
80
|
+
if (!current.includes(p))
|
|
81
|
+
current.push(p);
|
|
82
|
+
out[group] = current;
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
const RULE_PERMS = Object.freeze(['read', 'write', 'create', 'unlink']);
|
|
87
|
+
/** Validates a rule. */
|
|
88
|
+
export function assertRuleSpec(rule, where) {
|
|
89
|
+
if (rule.groups !== 'global' &&
|
|
90
|
+
(!Array.isArray(rule.groups) || rule.groups.some((g) => !GROUP_CODE.test(g))))
|
|
91
|
+
throw new SecurityDefinitionError(`${where}: groups must be 'global' or group codes.`, "Use groups: ['sale.user'] or groups: 'global'.");
|
|
92
|
+
if (!Array.isArray(rule.perms) ||
|
|
93
|
+
rule.perms.length === 0 ||
|
|
94
|
+
rule.perms.some((p) => !RULE_PERMS.includes(p)))
|
|
95
|
+
throw new SecurityDefinitionError(`${where}: perms lists an unknown permission.`, `Use a non-empty subset of: ${RULE_PERMS.join(', ')}.`);
|
|
96
|
+
if (typeof rule.domain !== 'object' || rule.domain === null || Array.isArray(rule.domain))
|
|
97
|
+
throw new SecurityDefinitionError(`${where}: domain must be an object.`, "E.g. { user: { $env: 'uid' } }.");
|
|
98
|
+
}
|
|
99
|
+
/** Splits a model's rules for `perm` into what applies to `groups` (RFC 0014 §7.3). */
|
|
100
|
+
export function applicableRules(rules, groups, perm) {
|
|
101
|
+
const globals = [];
|
|
102
|
+
const groupRules = [];
|
|
103
|
+
let hasGroupRules = false;
|
|
104
|
+
for (const rule of Object.values(rules)) {
|
|
105
|
+
if (!rule.perms.includes(perm))
|
|
106
|
+
continue;
|
|
107
|
+
if (rule.groups === 'global')
|
|
108
|
+
globals.push(rule);
|
|
109
|
+
else {
|
|
110
|
+
hasGroupRules = true;
|
|
111
|
+
if (rule.groups.some((g) => groups.has(g)))
|
|
112
|
+
groupRules.push(rule);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { globals, groupRules, hasGroupRules };
|
|
116
|
+
}
|
|
117
|
+
/** Replaces `{ $env: name }` objects in a domain with the environment's values. */
|
|
118
|
+
export function resolvePlaceholders(domain, env) {
|
|
119
|
+
if (Array.isArray(domain))
|
|
120
|
+
return domain.map((d) => resolvePlaceholders(d, env));
|
|
121
|
+
if (typeof domain !== 'object' || domain === null)
|
|
122
|
+
return domain;
|
|
123
|
+
const keys = Object.keys(domain);
|
|
124
|
+
if (keys.length === 1 && keys[0] === '$env') {
|
|
125
|
+
const name = domain.$env;
|
|
126
|
+
if (name === 'uid')
|
|
127
|
+
return env.uid;
|
|
128
|
+
if (name === 'companyId')
|
|
129
|
+
return env.companyId;
|
|
130
|
+
if (name === 'companyIds')
|
|
131
|
+
return [...env.companyIds];
|
|
132
|
+
throw new SecurityDefinitionError(`Unknown placeholder { $env: ${JSON.stringify(name)} }.`, "Use 'uid', 'companyId' or 'companyIds'.");
|
|
133
|
+
}
|
|
134
|
+
const out = {};
|
|
135
|
+
for (const [k, v] of Object.entries(domain))
|
|
136
|
+
out[k] = resolvePlaceholders(v, env);
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
/** Normalizes a field's groups option. */
|
|
140
|
+
export function normalizeFieldGroups(input) {
|
|
141
|
+
if (input === undefined)
|
|
142
|
+
return Object.freeze({ read: Object.freeze([]), write: Object.freeze([]) });
|
|
143
|
+
if (Array.isArray(input)) {
|
|
144
|
+
const list = Object.freeze([...input]);
|
|
145
|
+
return Object.freeze({ read: list, write: list });
|
|
146
|
+
}
|
|
147
|
+
const obj = input;
|
|
148
|
+
const read = Object.freeze([...(obj.read ?? [])]);
|
|
149
|
+
// Writing implies reading: a write-only field would be unreadable by its own writers.
|
|
150
|
+
const write = Object.freeze([...(obj.write ?? obj.read ?? [])]);
|
|
151
|
+
return Object.freeze({ read, write });
|
|
152
|
+
}
|
|
153
|
+
/** True when the field has no restriction for `kind` or the user is in one of its groups. */
|
|
154
|
+
export function fieldAllowed(groups, userGroups, kind) {
|
|
155
|
+
const required = kind === 'read' ? groups.read : groups.write;
|
|
156
|
+
return required.length === 0 || required.some((g) => userGroups.has(g));
|
|
157
|
+
}
|
|
158
|
+
// ---------------------------------------------------------------------------------------------------- RLS
|
|
159
|
+
/** The session settings `shutro.run()` pushes (RFC 0003 §7.1) and RLS policies read. */
|
|
160
|
+
export const RLS_SETTINGS = Object.freeze({
|
|
161
|
+
user: 'shutro.user_id',
|
|
162
|
+
company: 'shutro.company_id',
|
|
163
|
+
companies: 'shutro.company_ids',
|
|
164
|
+
groups: 'shutro.groups',
|
|
165
|
+
su: 'shutro.su',
|
|
166
|
+
});
|
|
167
|
+
function literal(value) {
|
|
168
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
169
|
+
}
|
|
170
|
+
/** SQL expressions for the placeholders, reading the session settings. */
|
|
171
|
+
export const RLS_PLACEHOLDERS = Object.freeze({
|
|
172
|
+
uid: `current_setting('${RLS_SETTINGS.user}', true)::bigint`,
|
|
173
|
+
companyId: `current_setting('${RLS_SETTINGS.company}', true)::bigint`,
|
|
174
|
+
companyIds: `string_to_array(trim(both '{}' from current_setting('${RLS_SETTINGS.companies}', true)), ',')::bigint[]`,
|
|
175
|
+
});
|
|
176
|
+
/** `true` when the session is a superuser scope. */
|
|
177
|
+
export const RLS_SU = `current_setting('${RLS_SETTINGS.su}', true) = '1'`;
|
|
178
|
+
/** `true` when the session's groups intersect `codes`. */
|
|
179
|
+
export function rlsGroupCondition(codes) {
|
|
180
|
+
if (codes.length === 0)
|
|
181
|
+
return 'false';
|
|
182
|
+
return `string_to_array(current_setting('${RLS_SETTINGS.groups}', true), ',') && ARRAY[${codes.map(literal).join(', ')}]::text[]`;
|
|
183
|
+
}
|
|
184
|
+
/** The DDL enabling RLS on a table and installing policies (idempotent: policies are dropped and recreated). */
|
|
185
|
+
export function rlsStatements(table, policies) {
|
|
186
|
+
const t = `"${table}"`;
|
|
187
|
+
const out = [
|
|
188
|
+
`ALTER TABLE ${t} ENABLE ROW LEVEL SECURITY`,
|
|
189
|
+
`ALTER TABLE ${t} FORCE ROW LEVEL SECURITY`,
|
|
190
|
+
];
|
|
191
|
+
for (const p of policies) {
|
|
192
|
+
out.push(`DROP POLICY IF EXISTS "${p.name}" ON ${t}`);
|
|
193
|
+
const clause = p.command === 'INSERT'
|
|
194
|
+
? `WITH CHECK (${p.condition})`
|
|
195
|
+
: p.command === 'UPDATE'
|
|
196
|
+
? `USING (${p.condition}) WITH CHECK (${p.condition})`
|
|
197
|
+
: `USING (${p.condition})`;
|
|
198
|
+
out.push(`CREATE POLICY "${p.name}" ON ${t} AS ${p.permissive ? 'PERMISSIVE' : 'RESTRICTIVE'} FOR ${p.command} ${clause}`);
|
|
199
|
+
}
|
|
200
|
+
return out;
|
|
201
|
+
}
|
|
202
|
+
/** Encryption failed or a token cannot be decrypted. */
|
|
203
|
+
export class EncryptionError extends Error {
|
|
204
|
+
hint;
|
|
205
|
+
constructor(problem, hint, options) {
|
|
206
|
+
super(`${problem} ${hint}`, options);
|
|
207
|
+
this.name = 'EncryptionError';
|
|
208
|
+
this.hint = hint;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const TOKEN_PREFIX = 'shutro1';
|
|
212
|
+
function keyBytes(ring, id) {
|
|
213
|
+
const raw = ring.keys[id];
|
|
214
|
+
if (raw === undefined)
|
|
215
|
+
throw new EncryptionError(`No key '${id}' in the key ring.`, 'Keep every key that encrypted a stored value until the data is re-encrypted.');
|
|
216
|
+
const key = typeof raw === 'string' ? Buffer.from(raw, 'base64') : Buffer.from(raw);
|
|
217
|
+
if (key.length !== 32)
|
|
218
|
+
throw new EncryptionError(`Key '${id}' is ${key.length} bytes.`, 'Keys are 32 bytes (AES-256), raw or base64.');
|
|
219
|
+
return key;
|
|
220
|
+
}
|
|
221
|
+
/** Validates a key ring. */
|
|
222
|
+
export function createKeyRing(ring) {
|
|
223
|
+
keyBytes(ring, ring.current);
|
|
224
|
+
for (const id of Object.keys(ring.keys))
|
|
225
|
+
keyBytes(ring, id);
|
|
226
|
+
return Object.freeze({ current: ring.current, keys: Object.freeze({ ...ring.keys }) });
|
|
227
|
+
}
|
|
228
|
+
/** AES-256-GCM; the token names the key so rotation only changes `current`. */
|
|
229
|
+
export function encrypt(ring, plaintext) {
|
|
230
|
+
const key = keyBytes(ring, ring.current);
|
|
231
|
+
const iv = randomBytes(12);
|
|
232
|
+
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
233
|
+
const data = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
|
234
|
+
const tag = cipher.getAuthTag();
|
|
235
|
+
return [
|
|
236
|
+
TOKEN_PREFIX,
|
|
237
|
+
ring.current,
|
|
238
|
+
iv.toString('base64'),
|
|
239
|
+
tag.toString('base64'),
|
|
240
|
+
data.toString('base64'),
|
|
241
|
+
].join(':');
|
|
242
|
+
}
|
|
243
|
+
/** True for a value produced by {@link encrypt}. */
|
|
244
|
+
export function isEncrypted(value) {
|
|
245
|
+
return typeof value === 'string' && value.startsWith(`${TOKEN_PREFIX}:`);
|
|
246
|
+
}
|
|
247
|
+
/** Decrypts a token; a wrong key or a tampered token is an {@link EncryptionError}. */
|
|
248
|
+
export function decrypt(ring, token) {
|
|
249
|
+
const parts = token.split(':');
|
|
250
|
+
if (parts.length !== 5 || parts[0] !== TOKEN_PREFIX)
|
|
251
|
+
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.');
|
|
252
|
+
const [, id = '', iv = '', tag = '', data = ''] = parts;
|
|
253
|
+
const key = keyBytes(ring, id);
|
|
254
|
+
try {
|
|
255
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'base64'));
|
|
256
|
+
decipher.setAuthTag(Buffer.from(tag, 'base64'));
|
|
257
|
+
return Buffer.concat([decipher.update(Buffer.from(data, 'base64')), decipher.final()]).toString('utf8');
|
|
258
|
+
}
|
|
259
|
+
catch (cause) {
|
|
260
|
+
throw new EncryptionError(`The value encrypted with key '${id}' cannot be decrypted.`, 'The key is wrong or the stored value was tampered with.', { cause });
|
|
261
|
+
}
|
|
262
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
* `@shutro/sequence`: document numbering (RFC 0012). The definition (`defineSequence`), the number format, the
|
|
4
|
+
* period key, and the SQL that allocates ranges from the `shutro_sequence` table. Core runs the allocation either in
|
|
5
|
+
* the business transaction (gapless: the counter row stays locked until commit, so a rollback never leaves a hole)
|
|
6
|
+
* or in a short autonomous transaction (standard: no blocking, gaps on rollback).
|
|
7
|
+
*/
|
|
8
|
+
import { type CompiledSql } from '../sql/index.js';
|
|
9
|
+
/** How often the counter restarts. */
|
|
10
|
+
export type SequenceReset = 'never' | 'yearly' | 'monthly' | 'daily';
|
|
11
|
+
/** A sequence definition. */
|
|
12
|
+
export interface SequenceDefinition {
|
|
13
|
+
/** Unique code, referenced by `f.char({ sequence: code })`, e.g. `'sale.order'`. */
|
|
14
|
+
readonly code: string;
|
|
15
|
+
/** Text before the number; placeholders `{year}`, `{yy}`, `{month}`, `{day}` use the document date. */
|
|
16
|
+
readonly prefix: string;
|
|
17
|
+
/** Text after the number; same placeholders. */
|
|
18
|
+
readonly suffix: string;
|
|
19
|
+
/** Minimum digits of the number (zero-padded). */
|
|
20
|
+
readonly padding: number;
|
|
21
|
+
/** First number of each period. */
|
|
22
|
+
readonly start: number;
|
|
23
|
+
readonly step: number;
|
|
24
|
+
/** No holes, ever: allocation serializes concurrent transactions until they commit. Only where the law needs it. */
|
|
25
|
+
readonly gapless: boolean;
|
|
26
|
+
/** One counter per company (default), or one shared counter. */
|
|
27
|
+
readonly perCompany: boolean;
|
|
28
|
+
readonly reset: SequenceReset;
|
|
29
|
+
}
|
|
30
|
+
/** Input of {@link defineSequence}: everything but `code` is optional. */
|
|
31
|
+
export interface SequenceInput {
|
|
32
|
+
readonly code: string;
|
|
33
|
+
readonly prefix?: string;
|
|
34
|
+
readonly suffix?: string;
|
|
35
|
+
readonly padding?: number;
|
|
36
|
+
readonly start?: number;
|
|
37
|
+
readonly step?: number;
|
|
38
|
+
readonly gapless?: boolean;
|
|
39
|
+
readonly perCompany?: boolean;
|
|
40
|
+
readonly reset?: SequenceReset;
|
|
41
|
+
}
|
|
42
|
+
/** A sequence definition that cannot be used. */
|
|
43
|
+
export declare class InvalidSequenceError extends Error {
|
|
44
|
+
readonly hint: string;
|
|
45
|
+
constructor(problem: string, hint: string);
|
|
46
|
+
}
|
|
47
|
+
/** Validates and completes a definition. @throws {InvalidSequenceError} */
|
|
48
|
+
export declare function defineSequence(input: SequenceInput): SequenceDefinition;
|
|
49
|
+
/** The counter period a document date falls in (`''` when the sequence never resets). */
|
|
50
|
+
export declare function periodKey(definition: SequenceDefinition, date: string): string;
|
|
51
|
+
/** The formatted document number. */
|
|
52
|
+
export declare function formatNumber(definition: SequenceDefinition, number: number, date: string): string;
|
|
53
|
+
/** The counter table (shared by every sequence; `company_id` 0 means a shared counter). */
|
|
54
|
+
export declare const SEQUENCE_TABLE = "shutro_sequence";
|
|
55
|
+
/** DDL of the counter table, idempotent. */
|
|
56
|
+
export declare function sequenceTableStatements(): readonly CompiledSql[];
|
|
57
|
+
/**
|
|
58
|
+
* The statement that reserves `count` consecutive numbers and returns the first one. Run it in the business
|
|
59
|
+
* transaction for gapless sequences (the row lock is the guarantee) or in a short autonomous one otherwise.
|
|
60
|
+
*/
|
|
61
|
+
export declare function allocateStatement(definition: SequenceDefinition, company: number, period: string, count: number): CompiledSql;
|
|
62
|
+
/** The numbers of an allocation that returned `first`. */
|
|
63
|
+
export declare function numbersFrom(definition: SequenceDefinition, first: number, count: number): number[];
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
* `@shutro/sequence`: document numbering (RFC 0012). The definition (`defineSequence`), the number format, the
|
|
4
|
+
* period key, and the SQL that allocates ranges from the `shutro_sequence` table. Core runs the allocation either in
|
|
5
|
+
* the business transaction (gapless: the counter row stays locked until commit, so a rollback never leaves a hole)
|
|
6
|
+
* or in a short autonomous transaction (standard: no blocking, gaps on rollback).
|
|
7
|
+
*/
|
|
8
|
+
import { compile, sql } from '../sql/index.js';
|
|
9
|
+
/** A sequence definition that cannot be used. */
|
|
10
|
+
export class InvalidSequenceError extends Error {
|
|
11
|
+
hint;
|
|
12
|
+
constructor(problem, hint) {
|
|
13
|
+
super(`${problem} ${hint}`);
|
|
14
|
+
this.name = 'InvalidSequenceError';
|
|
15
|
+
this.hint = hint;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const CODE = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;
|
|
19
|
+
const PLACEHOLDER = /\{(year|yy|month|day)\}/g;
|
|
20
|
+
const RESETS = ['never', 'yearly', 'monthly', 'daily'];
|
|
21
|
+
/** Validates and completes a definition. @throws {InvalidSequenceError} */
|
|
22
|
+
export function defineSequence(input) {
|
|
23
|
+
if (typeof input.code !== 'string' || !CODE.test(input.code)) {
|
|
24
|
+
throw new InvalidSequenceError(`${JSON.stringify(input.code)} is not a sequence code.`, "Use a dotted lower-case identifier such as 'sale.order' or 'account.move.invoice'.");
|
|
25
|
+
}
|
|
26
|
+
const padding = input.padding ?? 5;
|
|
27
|
+
if (!Number.isInteger(padding) || padding < 0 || padding > 20) {
|
|
28
|
+
throw new InvalidSequenceError(`Sequence '${input.code}': padding ${padding} is out of range.`, 'Use 0 to 20 digits.');
|
|
29
|
+
}
|
|
30
|
+
const start = input.start ?? 1;
|
|
31
|
+
const step = input.step ?? 1;
|
|
32
|
+
if (!Number.isInteger(start) || start < 0 || !Number.isInteger(step) || step < 1) {
|
|
33
|
+
throw new InvalidSequenceError(`Sequence '${input.code}': start must be a non-negative integer and step a positive one.`, 'E.g. { start: 1, step: 1 }.');
|
|
34
|
+
}
|
|
35
|
+
const reset = input.reset ?? 'never';
|
|
36
|
+
if (!RESETS.includes(reset)) {
|
|
37
|
+
throw new InvalidSequenceError(`Sequence '${input.code}': reset ${JSON.stringify(reset)} is unknown.`, `Use one of: ${RESETS.join(', ')}.`);
|
|
38
|
+
}
|
|
39
|
+
for (const [what, text] of [
|
|
40
|
+
['prefix', input.prefix ?? ''],
|
|
41
|
+
['suffix', input.suffix ?? ''],
|
|
42
|
+
]) {
|
|
43
|
+
const unknown = text.match(/\{[^}]*\}/g)?.filter((p) => !/^\{(year|yy|month|day)\}$/.test(p));
|
|
44
|
+
if (unknown !== undefined && unknown.length > 0) {
|
|
45
|
+
throw new InvalidSequenceError(`Sequence '${input.code}': ${what} uses unknown placeholder(s) ${unknown.join(', ')}.`, 'Use {year}, {yy}, {month} or {day}.');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return Object.freeze({
|
|
49
|
+
code: input.code,
|
|
50
|
+
prefix: input.prefix ?? '',
|
|
51
|
+
suffix: input.suffix ?? '',
|
|
52
|
+
padding,
|
|
53
|
+
start,
|
|
54
|
+
step,
|
|
55
|
+
gapless: input.gapless ?? false,
|
|
56
|
+
perCompany: input.perCompany ?? true,
|
|
57
|
+
reset,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/** The counter period a document date falls in (`''` when the sequence never resets). */
|
|
61
|
+
export function periodKey(definition, date) {
|
|
62
|
+
const [year = '0000', month = '00', day = '00'] = date.split('-');
|
|
63
|
+
switch (definition.reset) {
|
|
64
|
+
case 'never':
|
|
65
|
+
return '';
|
|
66
|
+
case 'yearly':
|
|
67
|
+
return year;
|
|
68
|
+
case 'monthly':
|
|
69
|
+
return `${year}-${month}`;
|
|
70
|
+
case 'daily':
|
|
71
|
+
return `${year}-${month}-${day}`;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** The formatted document number. */
|
|
75
|
+
export function formatNumber(definition, number, date) {
|
|
76
|
+
const [year = '0000', month = '00', day = '00'] = date.split('-');
|
|
77
|
+
const fill = (text) => text.replace(PLACEHOLDER, (_, name) => name === 'year' ? year : name === 'yy' ? year.slice(-2) : name === 'month' ? month : day);
|
|
78
|
+
return `${fill(definition.prefix)}${String(number).padStart(definition.padding, '0')}${fill(definition.suffix)}`;
|
|
79
|
+
}
|
|
80
|
+
/** The counter table (shared by every sequence; `company_id` 0 means a shared counter). */
|
|
81
|
+
export const SEQUENCE_TABLE = 'shutro_sequence';
|
|
82
|
+
/** DDL of the counter table, idempotent. */
|
|
83
|
+
export function sequenceTableStatements() {
|
|
84
|
+
return [
|
|
85
|
+
Object.freeze({
|
|
86
|
+
text: `CREATE TABLE IF NOT EXISTS "${SEQUENCE_TABLE}" ("code" text NOT NULL, "company_id" bigint NOT NULL DEFAULT 0, "period" text NOT NULL DEFAULT '', "next" bigint NOT NULL, PRIMARY KEY ("code", "company_id", "period"))`,
|
|
87
|
+
params: Object.freeze([]),
|
|
88
|
+
}),
|
|
89
|
+
];
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The statement that reserves `count` consecutive numbers and returns the first one. Run it in the business
|
|
93
|
+
* transaction for gapless sequences (the row lock is the guarantee) or in a short autonomous one otherwise.
|
|
94
|
+
*/
|
|
95
|
+
export function allocateStatement(definition, company, period, count) {
|
|
96
|
+
const total = count * definition.step;
|
|
97
|
+
return compile(sql `INSERT INTO ${sql.id(SEQUENCE_TABLE)} (${sql.id('code')}, ${sql.id('company_id')}, ${sql.id('period')}, ${sql.id('next')})
|
|
98
|
+
VALUES (${definition.code}, ${company}, ${period}, ${definition.start + total})
|
|
99
|
+
ON CONFLICT (${sql.id('code')}, ${sql.id('company_id')}, ${sql.id('period')})
|
|
100
|
+
DO UPDATE SET ${sql.id('next')} = ${sql.id(SEQUENCE_TABLE)}.${sql.id('next')} + ${total}
|
|
101
|
+
RETURNING ${sql.id('next')} - ${total} AS ${sql.id('first')}`);
|
|
102
|
+
}
|
|
103
|
+
/** The numbers of an allocation that returned `first`. */
|
|
104
|
+
export function numbersFrom(definition, first, count) {
|
|
105
|
+
return Array.from({ length: count }, (_, i) => first + i * definition.step);
|
|
106
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SQL AST shared by every Shutro front-end (the `sql` tag now; the typed builder and domains later, RFC 0005 §6).
|
|
3
|
+
* Nodes are immutable. Text nodes can only come from template-literal strings written in source code.
|
|
4
|
+
*/
|
|
5
|
+
/** Literal SQL text, taken verbatim from a template literal. Never built from runtime values. */
|
|
6
|
+
export interface TextNode {
|
|
7
|
+
readonly kind: 'text';
|
|
8
|
+
readonly text: string;
|
|
9
|
+
}
|
|
10
|
+
/** A bound value, rendered as `$n` (with `::cast` when given). The value itself never reaches the SQL text. */
|
|
11
|
+
export interface ParamNode {
|
|
12
|
+
readonly kind: 'param';
|
|
13
|
+
readonly value: unknown;
|
|
14
|
+
/** Validated PostgreSQL type, e.g. `numeric` or `bigint[]`. */
|
|
15
|
+
readonly cast: string | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** A validated, always-quoted identifier, optionally qualified (`"so"."amount_total"`). */
|
|
18
|
+
export interface IdentNode {
|
|
19
|
+
readonly kind: 'ident';
|
|
20
|
+
readonly parts: readonly string[];
|
|
21
|
+
}
|
|
22
|
+
/** A sequence of nodes rendered one after another. */
|
|
23
|
+
export interface SeqNode {
|
|
24
|
+
readonly kind: 'seq';
|
|
25
|
+
readonly nodes: readonly SqlNode[];
|
|
26
|
+
}
|
|
27
|
+
/** Any node of the SQL AST. */
|
|
28
|
+
export type SqlNode = TextNode | ParamNode | IdentNode | SeqNode;
|
|
29
|
+
declare const token: unique symbol;
|
|
30
|
+
/**
|
|
31
|
+
* A piece of SQL: an immutable AST node. Created only by the `sql` tag and its helpers, so its text parts are
|
|
32
|
+
* guaranteed to come from source code. Compile it with `compile()`.
|
|
33
|
+
*/
|
|
34
|
+
export declare class SqlFragment {
|
|
35
|
+
/** The fragment's AST. */
|
|
36
|
+
readonly node: SqlNode;
|
|
37
|
+
/** @internal Use the `sql` tag instead. */
|
|
38
|
+
constructor(key: typeof token, node: SqlNode);
|
|
39
|
+
}
|
|
40
|
+
/** @internal */
|
|
41
|
+
export declare function fragment(node: SqlNode): SqlFragment;
|
|
42
|
+
/** True when `value` is a {@link SqlFragment} created by this package (forgeries are rejected). */
|
|
43
|
+
export declare function isSql(value: unknown): value is SqlFragment;
|
|
44
|
+
/**
|
|
45
|
+
* Walks the AST depth-first in rendering order, calling `visitor` for every node (parents before children).
|
|
46
|
+
* Used, for example, to find every table a query touches (RFC 0005 §7.7).
|
|
47
|
+
*/
|
|
48
|
+
export declare function visit(root: SqlFragment | SqlNode, visitor: (node: SqlNode) => void): void;
|
|
49
|
+
export {};
|
package/dist/sql/ast.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SQL AST shared by every Shutro front-end (the `sql` tag now; the typed builder and domains later, RFC 0005 §6).
|
|
3
|
+
* Nodes are immutable. Text nodes can only come from template-literal strings written in source code.
|
|
4
|
+
*/
|
|
5
|
+
const token = Symbol('SqlFragment');
|
|
6
|
+
/**
|
|
7
|
+
* Every fragment this module created. `instanceof` alone can be fooled with `Object.create(SqlFragment.prototype)`,
|
|
8
|
+
* which would let arbitrary text through as SQL, so authenticity is checked here.
|
|
9
|
+
*/
|
|
10
|
+
const genuine = new WeakSet();
|
|
11
|
+
/**
|
|
12
|
+
* A piece of SQL: an immutable AST node. Created only by the `sql` tag and its helpers, so its text parts are
|
|
13
|
+
* guaranteed to come from source code. Compile it with `compile()`.
|
|
14
|
+
*/
|
|
15
|
+
export class SqlFragment {
|
|
16
|
+
/** The fragment's AST. */
|
|
17
|
+
node;
|
|
18
|
+
/** @internal Use the `sql` tag instead. */
|
|
19
|
+
constructor(key, node) {
|
|
20
|
+
if (key !== token)
|
|
21
|
+
throw new TypeError('SqlFragment is created by the sql tag, not directly.');
|
|
22
|
+
this.node = node;
|
|
23
|
+
Object.freeze(this);
|
|
24
|
+
genuine.add(this);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** @internal */
|
|
28
|
+
export function fragment(node) {
|
|
29
|
+
return new SqlFragment(token, Object.freeze(node));
|
|
30
|
+
}
|
|
31
|
+
/** True when `value` is a {@link SqlFragment} created by this package (forgeries are rejected). */
|
|
32
|
+
export function isSql(value) {
|
|
33
|
+
return typeof value === 'object' && value !== null && genuine.has(value);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Walks the AST depth-first in rendering order, calling `visitor` for every node (parents before children).
|
|
37
|
+
* Used, for example, to find every table a query touches (RFC 0005 §7.7).
|
|
38
|
+
*/
|
|
39
|
+
export function visit(root, visitor) {
|
|
40
|
+
const walk = (node) => {
|
|
41
|
+
visitor(node);
|
|
42
|
+
if (node.kind === 'seq')
|
|
43
|
+
for (const child of node.nodes)
|
|
44
|
+
walk(child);
|
|
45
|
+
};
|
|
46
|
+
walk(isSql(root) ? root.node : root);
|
|
47
|
+
}
|