uql-orm 0.114.4 → 0.115.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/dist/cockroachdb/cockroachDialect.d.ts +2 -0
- package/dist/cockroachdb/cockroachDialect.js +5 -0
- package/dist/d1/d1Querier.d.ts +2 -4
- package/dist/d1/d1Querier.js +0 -4
- package/dist/d1/d1SqliteDialect.js +1 -1
- package/dist/dialect/abstractDialect.d.ts +17 -8
- package/dist/dialect/abstractDialect.js +30 -16
- package/dist/dialect/abstractSqlDialect.d.ts +11 -2
- package/dist/dialect/abstractSqlDialect.js +17 -2
- package/dist/dialect/mysqlLikeSqlDialect.js +2 -0
- package/dist/dialect/operators.d.ts +2 -2
- package/dist/dialect/pgLikeSqlDialect.d.ts +8 -1
- package/dist/dialect/pgLikeSqlDialect.js +20 -0
- package/dist/entity/columnOptionsBuilder.d.ts +2 -1
- package/dist/entity/columnOptionsBuilder.js +3 -0
- package/dist/entity/metadata/definedFixture/author.d.ts +1 -1
- package/dist/entity/metadata/definedFixture/book.d.ts +2 -2
- package/dist/entity/metadata/definedFixture/folder.d.ts +1 -1
- package/dist/entity/metadata/definition.js +69 -30
- package/dist/http/api.d.ts +1 -1
- package/dist/http/wireQuery.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/migrate/ddl/tableDdl.d.ts +5 -0
- package/dist/migrate/ddl/tableDdl.js +9 -0
- package/dist/migrate/drift/driftDetector.js +2 -1
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +3 -1
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +7 -1
- package/dist/migrate/introspection/postgresIntrospector.d.ts +3 -1
- package/dist/migrate/introspection/postgresIntrospector.js +14 -1
- package/dist/migrate/introspection/tableSchemaAST.js +1 -0
- package/dist/migrate/policySql.d.ts +12 -0
- package/dist/migrate/policySql.js +74 -0
- package/dist/migrate/schemaChange.js +1 -0
- package/dist/migrate/schemaGenerator.d.ts +2 -0
- package/dist/migrate/schemaGenerator.js +37 -11
- package/dist/mongodb/mongoDialect.js +3 -1
- package/dist/mongodb/mongodbQuerier.d.ts +0 -2
- package/dist/mongodb/mongodbQuerier.js +0 -4
- package/dist/mssql/mssqlDialect.js +2 -0
- package/dist/neon/neonQuerier.d.ts +1 -2
- package/dist/nestjs/uqlContextInterceptor.d.ts +1 -1
- package/dist/nestjs/uqlContextInterceptor.js +1 -1
- package/dist/nestjs/uqlModule.d.ts +2 -2
- package/dist/nestjs/uqlModule.js +1 -1
- package/dist/querier/abstractQuerier.d.ts +31 -4
- package/dist/querier/abstractQuerier.js +120 -52
- package/dist/querier/abstractQuerierPool.js +2 -0
- package/dist/querier/abstractSqlQuerier.d.ts +16 -6
- package/dist/querier/abstractSqlQuerier.js +66 -6
- package/dist/querier/queryError.js +1 -0
- package/dist/schema/schemaAST.js +1 -0
- package/dist/schema/schemaASTBuilder.d.ts +3 -1
- package/dist/schema/schemaASTBuilder.js +1 -0
- package/dist/schema/schemaASTDiffer.js +4 -2
- package/dist/schema/types.d.ts +12 -4
- package/dist/sqlite/bindValues.d.ts +1 -1
- package/dist/sqlite/hranaQuerier.d.ts +2 -2
- package/dist/sqlite/sqliteDialect.js +2 -0
- package/dist/turso/tursoSessionQuerier.d.ts +2 -2
- package/dist/type/column.d.ts +10 -0
- package/dist/type/definedEntity.d.ts +9 -4
- package/dist/type/dialect.d.ts +13 -0
- package/dist/type/entity.d.ts +10 -0
- package/dist/type/index.d.ts +1 -0
- package/dist/type/index.js +1 -0
- package/dist/type/migration.d.ts +5 -1
- package/dist/type/policy.d.ts +91 -0
- package/dist/type/policy.js +1 -0
- package/dist/type/querier.d.ts +14 -0
- package/dist/type/querierPool.d.ts +2 -2
- package/dist/type/query.d.ts +18 -31
- package/dist/type/query.js +2 -0
- package/dist/util/contextRefs.d.ts +6 -0
- package/dist/util/contextRefs.js +5 -0
- package/dist/util/dialect.util.d.ts +10 -11
- package/dist/util/dialect.util.js +70 -56
- package/dist/util/fieldOption.util.js +1 -0
- package/dist/util/policy.util.d.ts +100 -0
- package/dist/util/policy.util.js +234 -0
- package/dist/util/uqlError.d.ts +2 -5
- package/dist/util/uqlError.js +2 -5
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +23 -13
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { getContext } from '../context/context.js';
|
|
2
|
-
import { QuerySql, resolveAggregateOp, } from '../type/index.js';
|
|
2
|
+
import { QuerySql, PAST_POLICIES, resolveAggregateOp, } from '../type/index.js';
|
|
3
3
|
import { DEFAULT_VECTOR_DISTANCE, VECTOR_INDEX_TYPES } from '../type/vector.js';
|
|
4
4
|
import { defaultReadKeys, fieldKeys, isDatabaseWritten, isWrittenOn, jsonKey, jsonPathKeys, } from './field.util.js';
|
|
5
5
|
import { withDeleted } from './filters.util.js';
|
|
6
6
|
import { entityName, getKeys, omitKeys, hasKeys, isJsonScalar, isOperatorObject, isPlainObject, isRecord, someKey, } from './object.util.js';
|
|
7
|
+
import { asWhere, conjuncts, policyCheck, policyScope, withContextValues } from './policy.util.js';
|
|
7
8
|
import { assertNoUndefined, whereAnd } from './query.util.js';
|
|
8
9
|
import { UqlSecurityError, UqlUsageError } from './uqlError.js';
|
|
9
10
|
/** The keys of `payload` a write persists as columns. */
|
|
@@ -404,20 +405,17 @@ export function fieldUpdateOf(key, value) {
|
|
|
404
405
|
return value.$inc === undefined ? ['$mul', value.$mul] : ['$inc', value.$inc];
|
|
405
406
|
}
|
|
406
407
|
/**
|
|
407
|
-
* `$where` with the entity's active filters merged in,
|
|
408
|
-
* filter yields to a `$where` on its key; a
|
|
408
|
+
* `$where` with the entity's active filters merged in, then ANDed with the rows its policies let the statement reach
|
|
409
|
+
* under the ambient {@link UqlContext}. A filter yields to a `$where` on its key; a policy yields to nothing.
|
|
409
410
|
*/
|
|
410
411
|
export function applyFilters(meta, whereMap, opts) {
|
|
411
|
-
if (!meta.filters) {
|
|
412
|
+
if (!meta.filters && !meta.policies?.length) {
|
|
412
413
|
return whereMap;
|
|
413
414
|
}
|
|
414
415
|
const result = { ...whereMap };
|
|
415
|
-
for (const [name, filter] of Object.entries(meta.filters)) {
|
|
416
|
+
for (const [name, filter] of Object.entries(meta.filters ?? {})) {
|
|
416
417
|
const active = opts?.filters !== false && (opts?.filters?.[name] ?? filter.default !== false);
|
|
417
|
-
|
|
418
|
-
continue;
|
|
419
|
-
}
|
|
420
|
-
const condition = resolveFilter(meta, name, filter) ?? {};
|
|
418
|
+
const condition = (active && filterCondition(filter)) || {};
|
|
421
419
|
for (const key of getKeys(condition)) {
|
|
422
420
|
if (result[key] === undefined) {
|
|
423
421
|
result[key] = condition[key];
|
|
@@ -425,63 +423,79 @@ export function applyFilters(meta, whereMap, opts) {
|
|
|
425
423
|
}
|
|
426
424
|
}
|
|
427
425
|
const merged = result;
|
|
428
|
-
const
|
|
429
|
-
return
|
|
430
|
-
}
|
|
431
|
-
/**
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
delete: ['read', 'delete'],
|
|
437
|
-
};
|
|
426
|
+
const scope = opts?.[PAST_POLICIES] ? undefined : policyScope(meta, opts?.access ?? 'read', getContext());
|
|
427
|
+
return scope === undefined || scope === true ? merged : whereAnd(merged, conjuncts(asWhere(meta, scope)));
|
|
428
|
+
}
|
|
429
|
+
/** A filter's condition under the ambient context, `undefined` where it reads what the context lacks, which skips it. */
|
|
430
|
+
function filterCondition(filter) {
|
|
431
|
+
const context = getContext();
|
|
432
|
+
return typeof filter.where === 'function' ? filter.where(context) : withContextValues(filter.where, context);
|
|
433
|
+
}
|
|
438
434
|
/**
|
|
439
|
-
*
|
|
440
|
-
*
|
|
435
|
+
* Holds rows an insert or an update writes to the entity's policies under the ambient context, before the write: a
|
|
436
|
+
* field the check pins to one value is filled into an inserted row leaving it out, and refused where a row sets
|
|
437
|
+
* another. See architecture/row-level-security.md.
|
|
441
438
|
*/
|
|
442
|
-
export function
|
|
443
|
-
|
|
444
|
-
const holds = filter.security && (!filter.ops || filter.ops.some((op) => accesses.includes(op)));
|
|
445
|
-
const condition = holds ? resolveFilter(meta, name, filter) : undefined;
|
|
446
|
-
return condition && hasKeys(condition) ? [[name, condition]] : [];
|
|
447
|
-
});
|
|
448
|
-
}
|
|
449
|
-
/** A filter's condition, `undefined` where it resolves to nothing and may skip; throws where it may not. */
|
|
450
|
-
function resolveFilter(meta, name, filter) {
|
|
451
|
-
const condition = typeof filter.where === 'function' ? filter.where(getContext()) : filter.where;
|
|
452
|
-
const onMissing = filter.onMissing ?? (filter.security ? 'throw' : 'skip');
|
|
453
|
-
if (condition === undefined && onMissing === 'throw') {
|
|
454
|
-
throw new UqlSecurityError(`filter '${name}' on '${entityName(meta)}' could not resolve (missing context)`);
|
|
455
|
-
}
|
|
456
|
-
return condition;
|
|
439
|
+
export function pinWrite(meta, rows, write) {
|
|
440
|
+
pinRows(meta, rows, write, getContext());
|
|
457
441
|
}
|
|
458
442
|
/**
|
|
459
|
-
*
|
|
460
|
-
*
|
|
461
|
-
* A condition other than field equalities refuses the write, having nothing a row can be checked against.
|
|
462
|
-
* See architecture/security-filter-writes.md.
|
|
443
|
+
* {@link pinWrite}, answering what the rows themselves cannot settle as the check the written rows must hold once
|
|
444
|
+
* written, which the querier reads back inside the write's transaction.
|
|
463
445
|
*/
|
|
464
446
|
export function guardWrite(meta, rows, write) {
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
447
|
+
const context = getContext();
|
|
448
|
+
const pins = pinRows(meta, rows, write, context);
|
|
449
|
+
if (!pins) {
|
|
450
|
+
return undefined;
|
|
451
|
+
}
|
|
452
|
+
const { check, pinned, rest } = pins;
|
|
453
|
+
const scope = write === 'update' ? policyScope(meta, 'update', context) : undefined;
|
|
454
|
+
const held = typeof scope === 'object' ? pinnedFields(meta, scope).pinned : [];
|
|
455
|
+
const settles = ([key, value]) => write === 'insert' ||
|
|
456
|
+
rows.every((row) => row[key] !== undefined) ||
|
|
457
|
+
held.some(([at, holds]) => at === key && holds === value);
|
|
458
|
+
return !rest && pinned.every(settles) ? undefined : check;
|
|
459
|
+
}
|
|
460
|
+
/** The check `rows` are written under, the fields it pins filled and refused: none where it lets every row be. */
|
|
461
|
+
function pinRows(meta, rows, write, context) {
|
|
462
|
+
const check = policyCheck(meta, write, context);
|
|
463
|
+
if (check === undefined || check === true) {
|
|
464
|
+
return undefined;
|
|
465
|
+
}
|
|
466
|
+
if (check === false) {
|
|
467
|
+
throw new UqlSecurityError(`no policy of '${entityName(meta)}' lets this context ${write} a row`);
|
|
468
|
+
}
|
|
469
|
+
const { pinned, rest } = pinnedFields(meta, check);
|
|
470
|
+
for (const [key, value] of pinned) {
|
|
471
|
+
for (const row of rows) {
|
|
472
|
+
if (row[key] === undefined) {
|
|
473
|
+
if (write === 'insert') {
|
|
474
|
+
row[key] = value;
|
|
481
475
|
}
|
|
482
476
|
}
|
|
477
|
+
else if (row[key] !== value) {
|
|
478
|
+
throw new UqlSecurityError(`'${entityName(meta)}' row sets '${key}' where its policies do not let it`);
|
|
479
|
+
}
|
|
483
480
|
}
|
|
484
481
|
}
|
|
482
|
+
return { check, pinned, rest };
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* The fields `where` pins to one value, each a top-level equality it ANDs, and whether anything else is left of it:
|
|
486
|
+
* an operator, a list, a relation, SQL or an `$or`, which only the database answers for a row.
|
|
487
|
+
*/
|
|
488
|
+
function pinnedFields(meta, where) {
|
|
489
|
+
const entries = conjuncts(where).flatMap((part) => Object.entries(part));
|
|
490
|
+
const pinned = entries.filter((entry) => {
|
|
491
|
+
const [key, value] = entry;
|
|
492
|
+
return !!meta.fields[key] && isScalarValue(value);
|
|
493
|
+
});
|
|
494
|
+
return { pinned, rest: pinned.length < entries.length };
|
|
495
|
+
}
|
|
496
|
+
/** A value a field is compared to as it is: no operator map, list or SQL. */
|
|
497
|
+
function isScalarValue(value) {
|
|
498
|
+
return !(value instanceof QuerySql) && !Array.isArray(value) && !isOperatorObject(value) && value !== null;
|
|
485
499
|
}
|
|
486
500
|
/**
|
|
487
501
|
* The `$size` of a relation condition, `{ comments: { $size: { $gte: 2 } } }`, or `undefined` where it
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { type AbstractType, type ContextKeyRef, type EntityAccess, type EntityMeta, type FieldKey, type FieldMeta, type Policy, type PolicyMeta, type PolicyMode, type PolicyWhere, type QueryWhere, type ScopedAccess, type UqlContext } from '../type/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* What the querier does to hold statements to the policies, under each {@link PolicyMode}: whether it ANDs their
|
|
4
|
+
* scope in (`scopes`), fills and refuses pinned fields (`guards`), reads written rows back against a check (`checks`),
|
|
5
|
+
* and leaves the rest to the database, which it binds the context for (`database`).
|
|
6
|
+
*/
|
|
7
|
+
export type PolicyEnforcement = {
|
|
8
|
+
readonly scopes: boolean;
|
|
9
|
+
readonly guards: boolean;
|
|
10
|
+
readonly checks: boolean;
|
|
11
|
+
readonly database: boolean;
|
|
12
|
+
};
|
|
13
|
+
/** How a pool built with `{ policies: mode }` holds its statements to the policies, the querier's way where unset. */
|
|
14
|
+
export declare function enforcementOf(mode: PolicyMode | undefined): PolicyEnforcement;
|
|
15
|
+
/** Every statement a policy holds where it names none. */
|
|
16
|
+
export declare const POLICY_OPS: readonly EntityAccess[];
|
|
17
|
+
/** A declared policy as metadata keeps it, its effect read off the key holding its predicate. */
|
|
18
|
+
export declare function policyMeta<E>({ allow, must, ops, ...rest }: Policy<E>): PolicyMeta<E> | undefined;
|
|
19
|
+
/** `value` with each `{ $context }` ref replaced by what `onRef` answers, every other node copied as it was. */
|
|
20
|
+
export declare function mapContextRefs(value: unknown, onRef: (ref: ContextKeyRef) => unknown): unknown;
|
|
21
|
+
/** The context keys `value` reads, in the order met. */
|
|
22
|
+
export declare function contextKeys(value: unknown): Set<string>;
|
|
23
|
+
/**
|
|
24
|
+
* `where` with each context key it reads replaced by the value `context` holds, `undefined` where it holds none for
|
|
25
|
+
* one: a filter reading what the context lacks is skipped, where a policy reaching no row is not.
|
|
26
|
+
*/
|
|
27
|
+
export declare function withContextValues<E>(where: PolicyWhere<E>, context: UqlContext | undefined): QueryWhere<E> | undefined;
|
|
28
|
+
/** A predicate once its context is read: a `$where`, or what it reduced to, every row or none. */
|
|
29
|
+
export type BoundWhere<E> = QueryWhere<E> | boolean;
|
|
30
|
+
/** `bound` as a `$where` of `meta`: `{}` for every row, {@link noRows} for none. */
|
|
31
|
+
export declare function asWhere<E>(meta: EntityMeta<E>, bound: BoundWhere<E>): QueryWhere<E>;
|
|
32
|
+
/** The predicates `where` ANDs: its `$and`'s where that is all it holds and none is SQL, else itself. */
|
|
33
|
+
export declare function conjuncts<E>(where: QueryWhere<E>): QueryWhere<E>[];
|
|
34
|
+
/**
|
|
35
|
+
* What a context key a policy compares `field` against reads as: its value, {@link MISSING} where the context holds
|
|
36
|
+
* none, or SQL reading it in the database. `field` is `undefined` where the key names no field of the entity.
|
|
37
|
+
*/
|
|
38
|
+
export type ContextRead = (ref: ContextKeyRef, field: FieldMeta | undefined) => unknown;
|
|
39
|
+
/** Reads each key off `context`: an absent key and a null alike are {@link MISSING}, which matches nothing. */
|
|
40
|
+
export declare function fromContext(context: UqlContext | undefined): (ref: ContextKeyRef) => unknown;
|
|
41
|
+
/**
|
|
42
|
+
* `where` with each context key it reads replaced by what `read` answers, the way the database reads a policy: a
|
|
43
|
+
* comparison against a {@link MISSING} key is SQL's unknown, never true, whatever negates it. `positive` is whether
|
|
44
|
+
* the predicate counts where it stands (`false` under a `$not`); a relation's subquery restarts it.
|
|
45
|
+
*/
|
|
46
|
+
export declare function bindContext<E>(meta: EntityMeta<E>, where: PolicyWhere<E>, read: ContextRead, positive?: boolean): BoundWhere<E>;
|
|
47
|
+
/** The database setting a context key is bound to for the policies the database holds. */
|
|
48
|
+
export declare function contextSetting(key: string): string;
|
|
49
|
+
/** A context key a policy may read, which names a database setting as it is. */
|
|
50
|
+
export declare const POLICY_CONTEXT_KEY: RegExp;
|
|
51
|
+
/**
|
|
52
|
+
* The keys of `context` a database binds for the policies it holds, each with its value as text: a scalar or a date,
|
|
53
|
+
* under a key a policy may read. Any other is left unbound, which a policy reads as NULL.
|
|
54
|
+
*/
|
|
55
|
+
export declare function contextEntries(context: UqlContext | undefined): [string, string][];
|
|
56
|
+
/** The context of a transaction that bound none yet, or whose binding a savepoint's rollback undid. */
|
|
57
|
+
declare const UNBOUND: unique symbol;
|
|
58
|
+
/** What a transaction bound for the database's policies: the context it last bound, and every key it bound so far. */
|
|
59
|
+
export type BoundContext = {
|
|
60
|
+
readonly context: UqlContext | undefined | typeof UNBOUND;
|
|
61
|
+
readonly keys: readonly string[];
|
|
62
|
+
};
|
|
63
|
+
export declare const NOTHING_BOUND: BoundContext;
|
|
64
|
+
/** `bound` after a savepoint's rollback, which may bring back any key bound before it: the next statement binds again. */
|
|
65
|
+
export declare function unsettled(bound: BoundContext): BoundContext;
|
|
66
|
+
/**
|
|
67
|
+
* What binds `context` over `bound`: its entries, each key the transaction bound that it lacks set empty, and what is
|
|
68
|
+
* bound once they are sent. No entry where `context` is the one bound.
|
|
69
|
+
*/
|
|
70
|
+
export declare function nextBinding(bound: BoundContext, context: UqlContext | undefined): {
|
|
71
|
+
entries: [string, string][];
|
|
72
|
+
bound: BoundContext;
|
|
73
|
+
};
|
|
74
|
+
/** The name of the policy a `tenant()` column registers, and of the `allow` an entity declaring none is given. */
|
|
75
|
+
export declare const TENANT_POLICY = "tenant";
|
|
76
|
+
export declare const EVERY_ROW_POLICY = "everyRow";
|
|
77
|
+
/** The `must` holding each row of `meta` to the tenant `key` stores, read off context key `contextKey`. */
|
|
78
|
+
export declare function tenantPolicy<E>(key: FieldKey<E>, contextKey: string): PolicyMeta<E>;
|
|
79
|
+
/**
|
|
80
|
+
* The policies holding `meta`: its own, and where none of them is an `allow`, one reaching every row, so its `must`s
|
|
81
|
+
* alone narrow what it reaches. An entity declaring an `allow` reaches no row in a statement none of them holds.
|
|
82
|
+
*/
|
|
83
|
+
export declare function policiesOf<E>(policies: readonly PolicyMeta<E>[]): readonly PolicyMeta<E>[];
|
|
84
|
+
/**
|
|
85
|
+
* The rows a statement doing `access` may reach under `context`, `undefined` for an entity with no policies. An update
|
|
86
|
+
* and a delete are held to the `read` policies too, as Postgres holds them.
|
|
87
|
+
*/
|
|
88
|
+
export declare function policyScope<E>(meta: EntityMeta<E>, access: ScopedAccess, context: UqlContext | undefined): BoundWhere<E> | undefined;
|
|
89
|
+
/** What a row an insert or an update writes must hold under `context`, `undefined` for an entity with no policies. */
|
|
90
|
+
export declare function policyCheck<E>(meta: EntityMeta<E>, access: 'insert' | 'update', context: UqlContext | undefined): BoundWhere<E> | undefined;
|
|
91
|
+
/**
|
|
92
|
+
* What `entity`'s policies hold a statement doing `access` to under `context`, the ambient one where unset: `where`,
|
|
93
|
+
* the rows it reaches (`{}` for every one), and `check`, what a row it writes must hold. Neither for an entity with no
|
|
94
|
+
* policies. What the querier ANDs in, so it answers why a read under a context reaches no row.
|
|
95
|
+
*/
|
|
96
|
+
export declare function explainPolicies<E>(entity: AbstractType<E>, access: EntityAccess, context?: UqlContext | undefined): {
|
|
97
|
+
readonly where?: QueryWhere<E>;
|
|
98
|
+
readonly check?: QueryWhere<E>;
|
|
99
|
+
};
|
|
100
|
+
export {};
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { getContext } from '../context/context.js';
|
|
2
|
+
import { GROUP_OPS, groupClauses, isGroupOp } from '../dialect/operators.js';
|
|
3
|
+
import { getMeta } from '../entity/metadata/definition.js';
|
|
4
|
+
import { QuerySql, } from '../type/index.js';
|
|
5
|
+
import { utcTimestamp } from './date.js';
|
|
6
|
+
import { isPlainObject } from './object.util.js';
|
|
7
|
+
import { whereAnd, whereAnyOf, whereWith } from './query.util.js';
|
|
8
|
+
const ENFORCEMENT = {
|
|
9
|
+
app: { scopes: true, guards: true, checks: true, database: false },
|
|
10
|
+
native: { scopes: false, guards: true, checks: false, database: true },
|
|
11
|
+
off: { scopes: false, guards: false, checks: false, database: false },
|
|
12
|
+
};
|
|
13
|
+
/** How a pool built with `{ policies: mode }` holds its statements to the policies, the querier's way where unset. */
|
|
14
|
+
export function enforcementOf(mode) {
|
|
15
|
+
return ENFORCEMENT[mode === false ? 'off' : (mode ?? 'app')];
|
|
16
|
+
}
|
|
17
|
+
/** Every statement a policy holds where it names none. */
|
|
18
|
+
export const POLICY_OPS = ['read', 'insert', 'update', 'delete'];
|
|
19
|
+
/** A declared policy as metadata keeps it, its effect read off the key holding its predicate. */
|
|
20
|
+
export function policyMeta({ allow, must, ops = POLICY_OPS, ...rest }) {
|
|
21
|
+
const where = allow ?? must;
|
|
22
|
+
return where && { effect: allow === undefined ? 'must' : 'allow', ops, where, ...rest };
|
|
23
|
+
}
|
|
24
|
+
/** Whether `value` reads a context key, `{ $context: 'tenantId' }`, and nothing else. */
|
|
25
|
+
function isContextRef(value) {
|
|
26
|
+
return isPlainObject(value) && typeof value['$context'] === 'string' && Object.keys(value).length === 1;
|
|
27
|
+
}
|
|
28
|
+
/** `value` with each `{ $context }` ref replaced by what `onRef` answers, every other node copied as it was. */
|
|
29
|
+
export function mapContextRefs(value, onRef) {
|
|
30
|
+
if (isContextRef(value)) {
|
|
31
|
+
return onRef(value);
|
|
32
|
+
}
|
|
33
|
+
if (Array.isArray(value)) {
|
|
34
|
+
return value.map((item) => mapContextRefs(item, onRef));
|
|
35
|
+
}
|
|
36
|
+
return isPlainObject(value)
|
|
37
|
+
? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mapContextRefs(item, onRef)]))
|
|
38
|
+
: value;
|
|
39
|
+
}
|
|
40
|
+
/** The context keys `value` reads, in the order met. */
|
|
41
|
+
export function contextKeys(value) {
|
|
42
|
+
const keys = new Set();
|
|
43
|
+
mapContextRefs(value, (ref) => keys.add(ref.$context));
|
|
44
|
+
return keys;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* `where` with each context key it reads replaced by the value `context` holds, `undefined` where it holds none for
|
|
48
|
+
* one: a filter reading what the context lacks is skipped, where a policy reaching no row is not.
|
|
49
|
+
*/
|
|
50
|
+
export function withContextValues(where, context) {
|
|
51
|
+
const bound = bindField(where, fromContext(context));
|
|
52
|
+
return bound === MISSING ? undefined : bound;
|
|
53
|
+
}
|
|
54
|
+
/** No row of `meta`: `$where` has no false, and an empty `$or` reads as no condition at all. */
|
|
55
|
+
function noRows(meta) {
|
|
56
|
+
return whereWith(meta.ids[0], { $in: [] });
|
|
57
|
+
}
|
|
58
|
+
/** `bound` as a `$where` of `meta`: `{}` for every row, {@link noRows} for none. */
|
|
59
|
+
export function asWhere(meta, bound) {
|
|
60
|
+
return bound === true ? {} : bound === false ? noRows(meta) : bound;
|
|
61
|
+
}
|
|
62
|
+
/** Every one of `parts`, as one predicate, an `$and` among them spliced in. */
|
|
63
|
+
function andBound(parts) {
|
|
64
|
+
if (parts.includes(false)) {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
const kept = parts.filter((part) => part !== true).flatMap(conjuncts);
|
|
68
|
+
return kept.length === 0 ? true : kept.length === 1 ? kept[0] : whereAnd(undefined, kept);
|
|
69
|
+
}
|
|
70
|
+
/** The predicates `where` ANDs: its `$and`'s where that is all it holds and none is SQL, else itself. */
|
|
71
|
+
export function conjuncts(where) {
|
|
72
|
+
const parts = Object.keys(where).length === 1 ? where.$and : undefined;
|
|
73
|
+
return parts?.every((part) => !(part instanceof QuerySql)) ? [...parts] : [where];
|
|
74
|
+
}
|
|
75
|
+
/** Any one of `parts`, as one predicate. */
|
|
76
|
+
function orBound(parts) {
|
|
77
|
+
if (parts.includes(true)) {
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
const kept = parts.filter((part) => part !== false);
|
|
81
|
+
return kept.length === 0 ? false : kept.length === 1 ? kept[0] : whereAnyOf(kept);
|
|
82
|
+
}
|
|
83
|
+
/** Not `bound`. */
|
|
84
|
+
function notBound(bound) {
|
|
85
|
+
return typeof bound === 'boolean' ? !bound : { $not: [bound] };
|
|
86
|
+
}
|
|
87
|
+
/** What a context key reads as where the context holds none. */
|
|
88
|
+
const MISSING = Symbol('missing');
|
|
89
|
+
/** Reads each key off `context`: an absent key and a null alike are {@link MISSING}, which matches nothing. */
|
|
90
|
+
export function fromContext(context) {
|
|
91
|
+
return (ref) => context?.[ref.$context] ?? MISSING;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* `where` with each context key it reads replaced by what `read` answers, the way the database reads a policy: a
|
|
95
|
+
* comparison against a {@link MISSING} key is SQL's unknown, never true, whatever negates it. `positive` is whether
|
|
96
|
+
* the predicate counts where it stands (`false` under a `$not`); a relation's subquery restarts it.
|
|
97
|
+
*/
|
|
98
|
+
export function bindContext(meta, where, read, positive = true) {
|
|
99
|
+
if (!contextKeys(where).size) {
|
|
100
|
+
return Object.keys(where).length === 0 || where;
|
|
101
|
+
}
|
|
102
|
+
const parts = Object.entries(where).map(([key, value]) => {
|
|
103
|
+
if (isGroupOp(key)) {
|
|
104
|
+
const { join, negate } = GROUP_OPS[key];
|
|
105
|
+
const clauses = groupClauses(key, value).map((item) => item instanceof QuerySql ? whereAnd(undefined, [item]) : bindContext(meta, item, read, positive !== negate));
|
|
106
|
+
const group = join === '$and' ? andBound(clauses) : orBound(clauses);
|
|
107
|
+
return negate ? notBound(group) : group;
|
|
108
|
+
}
|
|
109
|
+
const relation = meta.relations[key];
|
|
110
|
+
if (relation) {
|
|
111
|
+
const bound = bindContext(getMeta(relation.entity()), value, read);
|
|
112
|
+
return bound === false ? false : { [key]: bound === true ? {} : bound };
|
|
113
|
+
}
|
|
114
|
+
const field = bindField(value, (ref) => read(ref, meta.fields[key]));
|
|
115
|
+
return field === MISSING ? !positive : { [key]: field };
|
|
116
|
+
});
|
|
117
|
+
return andBound(parts);
|
|
118
|
+
}
|
|
119
|
+
/** One field's condition with its context read, or {@link MISSING} where a key it compares against is absent. */
|
|
120
|
+
function bindField(value, read) {
|
|
121
|
+
let missing = false;
|
|
122
|
+
const bound = mapContextRefs(value, (ref) => {
|
|
123
|
+
const held = read(ref);
|
|
124
|
+
missing ||= held === MISSING;
|
|
125
|
+
return held;
|
|
126
|
+
});
|
|
127
|
+
return missing ? MISSING : bound;
|
|
128
|
+
}
|
|
129
|
+
/** The database setting a context key is bound to for the policies the database holds. */
|
|
130
|
+
export function contextSetting(key) {
|
|
131
|
+
return `uql.${key}`;
|
|
132
|
+
}
|
|
133
|
+
/** A context key a policy may read, which names a database setting as it is. */
|
|
134
|
+
export const POLICY_CONTEXT_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
135
|
+
/**
|
|
136
|
+
* The keys of `context` a database binds for the policies it holds, each with its value as text: a scalar or a date,
|
|
137
|
+
* under a key a policy may read. Any other is left unbound, which a policy reads as NULL.
|
|
138
|
+
*/
|
|
139
|
+
export function contextEntries(context) {
|
|
140
|
+
return Object.entries(context ?? {}).flatMap(([key, value]) => {
|
|
141
|
+
if (!POLICY_CONTEXT_KEY.test(key)) {
|
|
142
|
+
return [];
|
|
143
|
+
}
|
|
144
|
+
if (value instanceof Date) {
|
|
145
|
+
return [[key, utcTimestamp(value)]];
|
|
146
|
+
}
|
|
147
|
+
const scalar = typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint' || typeof value === 'boolean';
|
|
148
|
+
return scalar ? [[key, String(value)]] : [];
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/** The context of a transaction that bound none yet, or whose binding a savepoint's rollback undid. */
|
|
152
|
+
const UNBOUND = Symbol('unbound');
|
|
153
|
+
export const NOTHING_BOUND = { context: UNBOUND, keys: [] };
|
|
154
|
+
/** `bound` after a savepoint's rollback, which may bring back any key bound before it: the next statement binds again. */
|
|
155
|
+
export function unsettled(bound) {
|
|
156
|
+
return { context: UNBOUND, keys: bound.keys };
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* What binds `context` over `bound`: its entries, each key the transaction bound that it lacks set empty, and what is
|
|
160
|
+
* bound once they are sent. No entry where `context` is the one bound.
|
|
161
|
+
*/
|
|
162
|
+
export function nextBinding(bound, context) {
|
|
163
|
+
if (bound.context === context) {
|
|
164
|
+
return { entries: [], bound };
|
|
165
|
+
}
|
|
166
|
+
const entries = contextEntries(context);
|
|
167
|
+
const keys = entries.map(([key]) => key);
|
|
168
|
+
const stale = bound.keys.filter((key) => !keys.includes(key));
|
|
169
|
+
return {
|
|
170
|
+
entries: [...entries, ...stale.map((key) => [key, ''])],
|
|
171
|
+
bound: { context, keys: [...keys, ...stale] },
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/** Whether `context` holds every key `when` names at its value, or at one of them where it lists several. */
|
|
175
|
+
function holdsWhen(when, context) {
|
|
176
|
+
return Object.entries(when ?? {}).every(([key, value]) => Array.isArray(value) ? value.includes(context?.[key]) : context?.[key] === value);
|
|
177
|
+
}
|
|
178
|
+
/** The name of the policy a `tenant()` column registers, and of the `allow` an entity declaring none is given. */
|
|
179
|
+
export const TENANT_POLICY = 'tenant';
|
|
180
|
+
export const EVERY_ROW_POLICY = 'everyRow';
|
|
181
|
+
/** The `must` holding each row of `meta` to the tenant `key` stores, read off context key `contextKey`. */
|
|
182
|
+
export function tenantPolicy(key, contextKey) {
|
|
183
|
+
return { effect: 'must', ops: POLICY_OPS, where: whereWith(key, { $context: contextKey }), name: TENANT_POLICY };
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The policies holding `meta`: its own, and where none of them is an `allow`, one reaching every row, so its `must`s
|
|
187
|
+
* alone narrow what it reaches. An entity declaring an `allow` reaches no row in a statement none of them holds.
|
|
188
|
+
*/
|
|
189
|
+
export function policiesOf(policies) {
|
|
190
|
+
return policies.some((policy) => policy.effect === 'allow')
|
|
191
|
+
? policies
|
|
192
|
+
: [...policies, { effect: 'allow', ops: POLICY_OPS, where: {}, name: EVERY_ROW_POLICY }];
|
|
193
|
+
}
|
|
194
|
+
/** The rows the `allow`s holding `access` reach and every `must` holds, each policy read by `pick`. */
|
|
195
|
+
function joined(meta, declared, access, context, pick) {
|
|
196
|
+
const policies = policiesOf(declared).filter((policy) => policy.ops.includes(access) && holdsWhen(policy.when, context));
|
|
197
|
+
const read = fromContext(context);
|
|
198
|
+
const bound = (policy) => bindContext(meta, pick(policy), read);
|
|
199
|
+
const allows = orBound(policies.filter((policy) => policy.effect === 'allow').map(bound));
|
|
200
|
+
return andBound([...policies.filter((policy) => policy.effect === 'must').map(bound), allows]);
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* The rows a statement doing `access` may reach under `context`, `undefined` for an entity with no policies. An update
|
|
204
|
+
* and a delete are held to the `read` policies too, as Postgres holds them.
|
|
205
|
+
*/
|
|
206
|
+
export function policyScope(meta, access, context) {
|
|
207
|
+
const { policies } = meta;
|
|
208
|
+
if (!policies?.length) {
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
const read = joined(meta, policies, 'read', context, (policy) => policy.where);
|
|
212
|
+
return access === 'read' ? read : andBound([read, joined(meta, policies, access, context, (policy) => policy.where)]);
|
|
213
|
+
}
|
|
214
|
+
/** What a row an insert or an update writes must hold under `context`, `undefined` for an entity with no policies. */
|
|
215
|
+
export function policyCheck(meta, access, context) {
|
|
216
|
+
const { policies } = meta;
|
|
217
|
+
return policies?.length
|
|
218
|
+
? joined(meta, policies, access, context, (policy) => policy.check ?? policy.where)
|
|
219
|
+
: undefined;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* What `entity`'s policies hold a statement doing `access` to under `context`, the ambient one where unset: `where`,
|
|
223
|
+
* the rows it reaches (`{}` for every one), and `check`, what a row it writes must hold. Neither for an entity with no
|
|
224
|
+
* policies. What the querier ANDs in, so it answers why a read under a context reaches no row.
|
|
225
|
+
*/
|
|
226
|
+
export function explainPolicies(entity, access, context = getContext()) {
|
|
227
|
+
const meta = getMeta(entity);
|
|
228
|
+
const scope = access === 'insert' ? undefined : policyScope(meta, access, context);
|
|
229
|
+
const check = access === 'insert' || access === 'update' ? policyCheck(meta, access, context) : undefined;
|
|
230
|
+
return {
|
|
231
|
+
...(scope === undefined ? {} : { where: asWhere(meta, scope) }),
|
|
232
|
+
...(check === undefined ? {} : { check: asWhere(meta, check) }),
|
|
233
|
+
};
|
|
234
|
+
}
|
package/dist/util/uqlError.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers
|
|
3
3
|
* with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization
|
|
4
4
|
* failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
|
|
5
|
-
* caller's own mistake, which running it again will not fix. `security` is
|
|
5
|
+
* caller's own mistake, which running it again will not fix. `security` is access refused: see {@link UqlSecurityError}.
|
|
6
6
|
*/
|
|
7
7
|
export declare const QUERY_ERROR_KINDS: readonly ['uniqueViolation', 'foreignKeyViolation', 'notNullViolation', 'checkViolation', 'optimisticLock', 'retryable', 'usage', 'security'];
|
|
8
8
|
export type QueryErrorKind = (typeof QUERY_ERROR_KINDS)[number];
|
|
@@ -46,10 +46,7 @@ export declare class UqlRequestError extends UqlError {
|
|
|
46
46
|
readonly kind = "usage";
|
|
47
47
|
constructor(message: string, status: number, opts?: UqlErrorOptions);
|
|
48
48
|
}
|
|
49
|
-
/**
|
|
50
|
-
* Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
|
|
51
|
-
* Fails the statement closed.
|
|
52
|
-
*/
|
|
49
|
+
/** Thrown where access is refused: the policies refuse a write, or an API exposes nothing a call names. */
|
|
53
50
|
export declare class UqlSecurityError extends UqlError {
|
|
54
51
|
name: string;
|
|
55
52
|
readonly kind = "security";
|
package/dist/util/uqlError.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers
|
|
3
3
|
* with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization
|
|
4
4
|
* failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
|
|
5
|
-
* caller's own mistake, which running it again will not fix. `security` is
|
|
5
|
+
* caller's own mistake, which running it again will not fix. `security` is access refused: see {@link UqlSecurityError}.
|
|
6
6
|
*/
|
|
7
7
|
export const QUERY_ERROR_KINDS = [
|
|
8
8
|
'uniqueViolation',
|
|
@@ -54,10 +54,7 @@ export class UqlRequestError extends UqlError {
|
|
|
54
54
|
this.status = status;
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
-
/**
|
|
58
|
-
* Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
|
|
59
|
-
* Fails the statement closed.
|
|
60
|
-
*/
|
|
57
|
+
/** Thrown where access is refused: the policies refuse a write, or an API exposes nothing a call names. */
|
|
61
58
|
export class UqlSecurityError extends UqlError {
|
|
62
59
|
name = 'UqlSecurityError';
|
|
63
60
|
kind = 'security';
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"homepage": "https://uql-orm.dev",
|
|
4
4
|
"description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.115.0",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=22.18"
|