@venizia/ignis-connectors 0.4.1 → 0.4.2
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/cjs/common/scope-filter.d.ts +1 -1
- package/dist/cjs/common/scope-filter.d.ts.map +1 -1
- package/dist/cjs/common/scope-filter.js +33 -7
- package/dist/cjs/common/scope-filter.js.map +1 -1
- package/dist/cjs/relational/core/repositories/common/scope-write-guard.d.ts +50 -0
- package/dist/cjs/relational/core/repositories/common/scope-write-guard.d.ts.map +1 -0
- package/dist/cjs/relational/core/repositories/common/scope-write-guard.js +248 -0
- package/dist/cjs/relational/core/repositories/common/scope-write-guard.js.map +1 -0
- package/dist/cjs/relational/core/repositories/core/base.d.ts +19 -4
- package/dist/cjs/relational/core/repositories/core/base.d.ts.map +1 -1
- package/dist/cjs/relational/core/repositories/core/base.js +28 -4
- package/dist/cjs/relational/core/repositories/core/base.js.map +1 -1
- package/dist/cjs/relational/core/repositories/core/persistable.d.ts.map +1 -1
- package/dist/cjs/relational/core/repositories/core/persistable.js +6 -1
- package/dist/cjs/relational/core/repositories/core/persistable.js.map +1 -1
- package/dist/cjs/relational/core/repositories/dialect/filter.d.ts +2 -2
- package/dist/cjs/relational/core/repositories/dialect/filter.js +3 -3
- package/dist/cjs/relational/core/repositories/dialect/filter.js.map +1 -1
- package/dist/cjs/relational/core/repositories/sqls/recursive-tree.d.ts +9 -0
- package/dist/cjs/relational/core/repositories/sqls/recursive-tree.d.ts.map +1 -1
- package/dist/cjs/relational/core/repositories/sqls/recursive-tree.js +14 -3
- package/dist/cjs/relational/core/repositories/sqls/recursive-tree.js.map +1 -1
- package/dist/cjs/search/core/controllers/abstract.d.ts +4 -0
- package/dist/cjs/search/core/controllers/abstract.d.ts.map +1 -1
- package/dist/cjs/search/core/controllers/abstract.js +15 -1
- package/dist/cjs/search/core/controllers/abstract.js.map +1 -1
- package/dist/cjs/search/core/controllers/factory.d.ts +14 -0
- package/dist/cjs/search/core/controllers/factory.d.ts.map +1 -1
- package/dist/cjs/search/core/controllers/factory.js +7 -1
- package/dist/cjs/search/core/controllers/factory.js.map +1 -1
- package/dist/cjs/search/core/controllers/scope.d.ts +28 -0
- package/dist/cjs/search/core/controllers/scope.d.ts.map +1 -0
- package/dist/cjs/search/core/controllers/scope.js +68 -0
- package/dist/cjs/search/core/controllers/scope.js.map +1 -0
- package/dist/esm/common/scope-filter.d.ts +1 -1
- package/dist/esm/common/scope-filter.d.ts.map +1 -1
- package/dist/esm/common/scope-filter.js +34 -8
- package/dist/esm/common/scope-filter.js.map +1 -1
- package/dist/esm/relational/core/repositories/common/scope-write-guard.d.ts +50 -0
- package/dist/esm/relational/core/repositories/common/scope-write-guard.d.ts.map +1 -0
- package/dist/esm/relational/core/repositories/common/scope-write-guard.js +244 -0
- package/dist/esm/relational/core/repositories/common/scope-write-guard.js.map +1 -0
- package/dist/esm/relational/core/repositories/core/base.d.ts +19 -4
- package/dist/esm/relational/core/repositories/core/base.d.ts.map +1 -1
- package/dist/esm/relational/core/repositories/core/base.js +28 -4
- package/dist/esm/relational/core/repositories/core/base.js.map +1 -1
- package/dist/esm/relational/core/repositories/core/persistable.d.ts.map +1 -1
- package/dist/esm/relational/core/repositories/core/persistable.js +6 -1
- package/dist/esm/relational/core/repositories/core/persistable.js.map +1 -1
- package/dist/esm/relational/core/repositories/dialect/filter.d.ts +2 -2
- package/dist/esm/relational/core/repositories/dialect/filter.js +3 -3
- package/dist/esm/relational/core/repositories/dialect/filter.js.map +1 -1
- package/dist/esm/relational/core/repositories/sqls/recursive-tree.d.ts +9 -0
- package/dist/esm/relational/core/repositories/sqls/recursive-tree.d.ts.map +1 -1
- package/dist/esm/relational/core/repositories/sqls/recursive-tree.js +15 -4
- package/dist/esm/relational/core/repositories/sqls/recursive-tree.js.map +1 -1
- package/dist/esm/search/core/controllers/abstract.d.ts +4 -0
- package/dist/esm/search/core/controllers/abstract.d.ts.map +1 -1
- package/dist/esm/search/core/controllers/abstract.js +15 -1
- package/dist/esm/search/core/controllers/abstract.js.map +1 -1
- package/dist/esm/search/core/controllers/factory.d.ts +14 -0
- package/dist/esm/search/core/controllers/factory.d.ts.map +1 -1
- package/dist/esm/search/core/controllers/factory.js +7 -1
- package/dist/esm/search/core/controllers/factory.js.map +1 -1
- package/dist/esm/search/core/controllers/scope.d.ts +28 -0
- package/dist/esm/search/core/controllers/scope.d.ts.map +1 -0
- package/dist/esm/search/core/controllers/scope.js +64 -0
- package/dist/esm/search/core/controllers/scope.js.map +1 -0
- package/package.json +6 -6
|
@@ -13,13 +13,18 @@ class SearchControllerFactory extends core_1.BaseHelper {
|
|
|
13
13
|
}
|
|
14
14
|
/** Creates a search controller with two endpoints: `POST {basePath}/search` via `repository.search()`, and `POST {basePath}/multi-search` via `repository.dataSource.multiSearch()`. */
|
|
15
15
|
static defineSearchController(defOpts) {
|
|
16
|
-
const { controller, entity, authenticate, authorize, routes } = defOpts;
|
|
16
|
+
const { controller, entity, authenticate, authorize, routes, scope } = defOpts;
|
|
17
17
|
const { name, basePath = 'unknown_path', isStrict = true } = controller;
|
|
18
18
|
if (!basePath || basePath === 'unknown_path') {
|
|
19
19
|
throw (0, core_1.getError)({
|
|
20
20
|
message: `[defineSearchController] Invalid controller basePath | name: ${name} | basePath: ${basePath}`,
|
|
21
21
|
});
|
|
22
22
|
}
|
|
23
|
+
if (scope && routes?.multiSearch?.enabled !== false) {
|
|
24
|
+
throw (0, core_1.getError)({
|
|
25
|
+
message: `[defineSearchController] A scoped search controller cannot serve multi-search | name: ${name} | set routes.multiSearch.enabled to false`,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
23
28
|
const entityClass = (0, ignis_inversion_1.isClass)(entity) ? entity : entity();
|
|
24
29
|
const entityInstance = new entityClass();
|
|
25
30
|
const selectSchema = entityInstance.getSchema({ type: ignis_kernel_1.SchemaTypes.SELECT });
|
|
@@ -32,6 +37,7 @@ class SearchControllerFactory extends core_1.BaseHelper {
|
|
|
32
37
|
isStrict,
|
|
33
38
|
repository,
|
|
34
39
|
definitions: routeDefinitions,
|
|
40
|
+
searchScope: scope,
|
|
35
41
|
});
|
|
36
42
|
}
|
|
37
43
|
/** Registers the search + multiSearch route handlers, honoring per-route enable flags. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/factory.ts"],"names":[],"mappings":";;;AAEA,wDAAwF;AAKxF,sDAAmE;AACnE,8DAAmD;AAGnD,yCAAsD;
|
|
1
|
+
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../../src/search/core/controllers/factory.ts"],"names":[],"mappings":";;;AAEA,wDAAwF;AAKxF,sDAAmE;AACnE,8DAAmD;AAGnD,yCAAsD;AAEtD,6CAAwD;AAgDxD,wHAAwH;AACxH,MAAa,uBAAwB,SAAQ,iBAAU;IACrD;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,uBAAuB,CAAC,IAAI,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,wLAAwL;IACxL,MAAM,CAAC,sBAAsB,CAO3B,OAA0C;QAC1C,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;QAE/E,MAAM,EAAE,IAAI,EAAE,QAAQ,GAAG,cAAc,EAAE,QAAQ,GAAG,IAAI,EAAE,GAAG,UAAU,CAAC;QACxE,IAAI,CAAC,QAAQ,IAAI,QAAQ,KAAK,cAAc,EAAE,CAAC;YAC7C,MAAM,IAAA,eAAQ,EAAC;gBACb,OAAO,EAAE,gEAAgE,IAAI,gBAAgB,QAAQ,EAAE;aACxG,CAAC,CAAC;QACL,CAAC;QAED,IAAI,KAAK,IAAI,MAAM,EAAE,WAAW,EAAE,OAAO,KAAK,KAAK,EAAE,CAAC;YACpD,MAAM,IAAA,eAAQ,EAAC;gBACb,OAAO,EAAE,yFAAyF,IAAI,4CAA4C;aACnJ,CAAC,CAAC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,CAAC,WAAW,CAAC,EAAE,OAAO,EAAE,CAAC;qBAC1D,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;SACF,CAAC;QAEF,MAAM,CAAC,cAAc,CAAC,eAAe,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;QACpF,IAAA,iDAAkC,EAAC;YACjC,MAAM,EAAE,eAAe;YACvB,WAAW,EAAE,wBAAwB;YACrC,cAAc,EAAE,IAAI;YACpB,cAAc,EAAE,OAAO,CAAC,UAAU,CAAC,IAAI;SACxC,CAAC,CAAC;QACH,OAAO,eAAe,CAAC;IACzB,CAAC;CACF;AArFD,0DAqFC","sourcesContent":["import type { TEntityDataObject } from '@venizia/ignis-kernel';\nimport type { AbstractEntity } from '@venizia/ignis-kernel';\nimport { registerFactoryRepositoryInjection, SchemaTypes } from '@venizia/ignis-kernel';\nimport type { TAuthMode, TAuthStrategy } from '@venizia/ignis-kernel';\nimport type { IAuthorizationSpec } from '@venizia/ignis-kernel';\nimport type { TAnyObjectSchema } from '@venizia/ignis-kernel';\nimport type { TClass, TResolver, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { isClass } from '@venizia/ignis-inversion';\nimport type { Env, Schema } from 'hono';\nimport type { ReadableSearchRepository } from '../repositories/core/readable';\nimport { AbstractSearchController } from './abstract';\nimport type { TSearchScopeResolver } from './scope';\nimport { defineSearchRouteConfigs } from './definition';\n\n/** Per-route enable/disable switches for the generated search controller. */\nexport interface ISearchCustomizableRoutes {\n search?: { enabled?: boolean };\n multiSearch?: { enabled?: boolean };\n}\n\n/** Configuration options for creating a search controller via SearchControllerFactory.defineSearchController. */\nexport interface ISearchControllerOptions<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n> {\n /** Entity class or resolver returning it; its SELECT schema drives the `hits[].document` shape in the generated route's response. */\n entity: TClass<TEntity> | TResolver<TClass<TEntity>>;\n\n repository: {\n name: string; // Repository binding name in the IoC container\n };\n\n controller: {\n name: string;\n basePath: string;\n isStrict?: boolean;\n };\n\n /** Authentication config applied to both generated routes. */\n authenticate?: { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n\n /** Authorization config applied to both generated routes. */\n authorize?: IAuthorizationSpec | IAuthorizationSpec[];\n\n /** Per-route enable/disable configuration. */\n routes?: ISearchCustomizableRoutes;\n\n /**\n * A function of the request context returning the filter this caller may search within. It is\n * ANDed into `input.filter.where` on the server: the client's own `where` can narrow it, never\n * widen or remove it. Fails closed - a scope that is null, undefined or throws refuses the\n * request with 403. Return `ScopeFilters.UNRESTRICTED` to apply none for a trusted caller.\n *\n * `raw` mode and `engineParams` hand the engine its own wire parameters, and a multi-search entry\n * carries a raw `filterBy`; none can take a scope, so a scoped controller refuses `raw` and\n * `engineParams` (400) and must disable the multi-search route (`routes.multiSearch.enabled:\n * false`), which `defineSearchController` requires.\n */\n scope?: TSearchScopeResolver;\n}\n\n/** Factory for generating turnkey search controllers (single-collection + cross-collection) from entity definitions. */\nexport class SearchControllerFactory extends BaseHelper {\n constructor() {\n super({ scope: SearchControllerFactory.name });\n }\n\n /** Creates a search controller with two endpoints: `POST {basePath}/search` via `repository.search()`, and `POST {basePath}/multi-search` via `repository.dataSource.multiSearch()`. */\n static defineSearchController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n >(defOpts: ISearchControllerOptions<TEntity>) {\n const { controller, entity, authenticate, authorize, routes, scope } = defOpts;\n\n const { name, basePath = 'unknown_path', isStrict = true } = controller;\n if (!basePath || basePath === 'unknown_path') {\n throw getError({\n message: `[defineSearchController] Invalid controller basePath | name: ${name} | basePath: ${basePath}`,\n });\n }\n\n if (scope && routes?.multiSearch?.enabled !== false) {\n throw getError({\n message: `[defineSearchController] A scoped search controller cannot serve multi-search | name: ${name} | set routes.multiSearch.enabled to false`,\n });\n }\n\n const entityClass = isClass(entity) ? entity : entity();\n const entityInstance = new entityClass();\n\n const selectSchema = entityInstance.getSchema({ type: SchemaTypes.SELECT });\n const routeDefinitions = defineSearchRouteConfigs({ selectSchema, authenticate, authorize });\n\n const controllerClass = class extends AbstractSearchController<\n TEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject\n > {\n constructor(repository: ReadableSearchRepository<TDataObject>) {\n super({\n scope: name,\n path: basePath,\n isStrict,\n repository,\n definitions: routeDefinitions,\n searchScope: scope as TSearchScopeResolver<RouteEnv> | undefined,\n });\n }\n\n /** Registers the search + multiSearch route handlers, honoring per-route enable flags. */\n override binding(): ValueOrPromise<void> {\n const isEnabled = (routeKey: keyof ISearchCustomizableRoutes) => {\n return routes?.[routeKey]?.enabled !== false;\n };\n\n if (isEnabled('search')) {\n this.defineRoute({\n configs: routeDefinitions.SEARCH,\n handler: async (context) => this.search({ context }),\n });\n }\n\n if (isEnabled('multiSearch')) {\n this.defineRoute({\n configs: routeDefinitions.MULTI_SEARCH,\n handler: async (context) => this.multiSearch({ context }),\n });\n }\n }\n };\n\n Object.defineProperty(controllerClass, 'name', { value: name, configurable: true });\n registerFactoryRepositoryInjection({\n target: controllerClass,\n factoryName: 'defineSearchController',\n controllerName: name,\n repositoryName: defOpts.repository.name,\n });\n return controllerClass;\n }\n}\n"]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ValueOrPromise } from '@venizia/ignis-helpers/common';
|
|
2
|
+
import { ScopeFilters } from '@venizia/ignis-kernel';
|
|
3
|
+
import type { TRouteContext, TWhere } from '@venizia/ignis-kernel';
|
|
4
|
+
import type { Env } from 'hono';
|
|
5
|
+
import type { TSearchInput } from '../repositories/common';
|
|
6
|
+
/**
|
|
7
|
+
* A per-request search scope: the filter the caller is allowed to search within (a merchant, a
|
|
8
|
+
* sharing rule). Return a `where`, `ScopeFilters.UNRESTRICTED` to apply none for this call, or
|
|
9
|
+
* null/undefined when the caller's scope is unknown - which refuses the request.
|
|
10
|
+
*/
|
|
11
|
+
export type TSearchScopeResolver<RouteEnv extends Env = Env> = (opts: {
|
|
12
|
+
context: TRouteContext<RouteEnv>;
|
|
13
|
+
}) => ValueOrPromise<TWhere | typeof ScopeFilters.UNRESTRICTED | null | undefined>;
|
|
14
|
+
/**
|
|
15
|
+
* ANDs the resolved scope into `input.filter.where`, on the server, after the body was validated.
|
|
16
|
+
* The client's own `where` is kept inside the AND, so it can narrow the scope and never widen it.
|
|
17
|
+
*
|
|
18
|
+
* Fails closed:
|
|
19
|
+
* - a scope that is null, undefined, or throws refuses the request (403);
|
|
20
|
+
* - `raw` mode and `engineParams` hand the engine its own wire parameters (`filter_by` among them),
|
|
21
|
+
* which a `where` cannot be ANDed into, so a scoped controller refuses them (400).
|
|
22
|
+
*/
|
|
23
|
+
export declare const applySearchScope: <RouteEnv extends Env = Env>(opts: {
|
|
24
|
+
resolve: TSearchScopeResolver<RouteEnv>;
|
|
25
|
+
context: TRouteContext<RouteEnv>;
|
|
26
|
+
input: TSearchInput;
|
|
27
|
+
}) => Promise<TSearchInput>;
|
|
28
|
+
//# sourceMappingURL=scope.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope.d.ts","sourceRoot":"","sources":["../../../../../src/search/core/controllers/scope.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAChC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAGtE;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,CAAC,QAAQ,SAAS,GAAG,GAAG,GAAG,IAAI,CAAC,IAAI,EAAE;IACpE,OAAO,EAAE,aAAa,CAAC,QAAQ,CAAC,CAAC;CAClC,KAAK,cAAc,CAAC,MAAM,GAAG,OAAO,YAAY,CAAC,YAAY,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;AAUnF;;;;;;;;GAQG;AACH,eAAO,MAAM,gBAAgB,GAAU,QAAQ,SAAS,GAAG,GAAG,GAAG,EAAE,MAAM;IACvE,OAAO,EAAE,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IACxC,OAAO,EAAE,aAAa,CAAC,QAAQ,CAAC,CAAC;IACjC,KAAK,EAAE,YAAY,CAAC;CACrB,KAAG,OAAO,CAAC,YAAY,CAgDvB,CAAC"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.applySearchScope = void 0;
|
|
4
|
+
const common_1 = require("@venizia/ignis-helpers/common");
|
|
5
|
+
const core_1 = require("@venizia/ignis-helpers/core");
|
|
6
|
+
const ignis_kernel_1 = require("@venizia/ignis-kernel");
|
|
7
|
+
const common_2 = require("../repositories/common");
|
|
8
|
+
const refuse = (opts) => {
|
|
9
|
+
return (0, core_1.getError)({
|
|
10
|
+
statusCode: opts.statusCode,
|
|
11
|
+
message: opts.message,
|
|
12
|
+
cause: opts.cause,
|
|
13
|
+
});
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* ANDs the resolved scope into `input.filter.where`, on the server, after the body was validated.
|
|
17
|
+
* The client's own `where` is kept inside the AND, so it can narrow the scope and never widen it.
|
|
18
|
+
*
|
|
19
|
+
* Fails closed:
|
|
20
|
+
* - a scope that is null, undefined, or throws refuses the request (403);
|
|
21
|
+
* - `raw` mode and `engineParams` hand the engine its own wire parameters (`filter_by` among them),
|
|
22
|
+
* which a `where` cannot be ANDed into, so a scoped controller refuses them (400).
|
|
23
|
+
*/
|
|
24
|
+
const applySearchScope = async (opts) => {
|
|
25
|
+
const { resolve, context, input } = opts;
|
|
26
|
+
let scope;
|
|
27
|
+
try {
|
|
28
|
+
scope = await resolve({ context });
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
throw refuse({
|
|
32
|
+
statusCode: common_1.HTTP.ResultCodes.RS_4.Forbidden,
|
|
33
|
+
message: '[search] the search scope could not be resolved for this request',
|
|
34
|
+
cause: error,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
if (scope === ignis_kernel_1.ScopeFilters.UNRESTRICTED) {
|
|
38
|
+
return input;
|
|
39
|
+
}
|
|
40
|
+
if (scope === null || scope === undefined) {
|
|
41
|
+
throw refuse({
|
|
42
|
+
statusCode: common_1.HTTP.ResultCodes.RS_4.Forbidden,
|
|
43
|
+
message: '[search] no search scope for this request',
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
if (input.mode === common_2.SearchModes.RAW) {
|
|
47
|
+
throw refuse({
|
|
48
|
+
statusCode: common_1.HTTP.ResultCodes.RS_4.BadRequest,
|
|
49
|
+
message: "[search] mode 'raw' is not available on a scoped search controller",
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
if (input.engineParams !== undefined) {
|
|
53
|
+
throw refuse({
|
|
54
|
+
statusCode: common_1.HTTP.ResultCodes.RS_4.BadRequest,
|
|
55
|
+
message: '[search] engineParams is not available on a scoped search controller',
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const clientWhere = input.filter?.where;
|
|
59
|
+
return {
|
|
60
|
+
...input,
|
|
61
|
+
filter: {
|
|
62
|
+
...input.filter,
|
|
63
|
+
where: clientWhere ? { and: [scope, clientWhere] } : scope,
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
exports.applySearchScope = applySearchScope;
|
|
68
|
+
//# sourceMappingURL=scope.js.map
|
|
@@ -0,0 +1 @@
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UAAU,EAAE,aAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;YAC5C,OAAO,EAAE,oEAAoE;SAC9E,CAAC,CAAC;IACL,CAAC;IAED,IAAI,KAAK,CAAC,YAAY,KAAK,SAAS,EAAE,CAAC;QACrC,MAAM,MAAM,CAAC;YACX,UAAU,EAAE,aAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;YAC5C,OAAO,EAAE,sEAAsE;SAChF,CAAC,CAAC;IACL,CAAC;IAED,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC;IAExC,OAAO;QACL,GAAG,KAAK;QACR,MAAM,EAAE;YACN,GAAG,KAAK,CAAC,MAAM;YACf,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAAK,EAAE,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK;SAC3D;KACc,CAAC;AACpB,CAAC,CAAC;AApDW,QAAA,gBAAgB,oBAoD3B","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { ScopeFilters } from '@venizia/ignis-kernel';\nimport type { TRouteContext, TWhere } from '@venizia/ignis-kernel';\nimport type { Env } from 'hono';\nimport type { TSearchInput } from '@/search/core/repositories/common';\nimport { SearchModes } from '@/search/core/repositories/common';\n\n/**\n * A per-request search scope: the filter the caller is allowed to search within (a merchant, a\n * sharing rule). Return a `where`, `ScopeFilters.UNRESTRICTED` to apply none for this call, or\n * null/undefined when the caller's scope is unknown - which refuses the request.\n */\nexport type TSearchScopeResolver<RouteEnv extends Env = Env> = (opts: {\n context: TRouteContext<RouteEnv>;\n}) => ValueOrPromise<TWhere | typeof ScopeFilters.UNRESTRICTED | null | undefined>;\n\nconst refuse = (opts: { statusCode: number; message: string; cause?: unknown }) => {\n return getError({\n statusCode: opts.statusCode,\n message: opts.message,\n cause: opts.cause,\n });\n};\n\n/**\n * ANDs the resolved scope into `input.filter.where`, on the server, after the body was validated.\n * The client's own `where` is kept inside the AND, so it can narrow the scope and never widen it.\n *\n * Fails closed:\n * - a scope that is null, undefined, or throws refuses the request (403);\n * - `raw` mode and `engineParams` hand the engine its own wire parameters (`filter_by` among them),\n * which a `where` cannot be ANDed into, so a scoped controller refuses them (400).\n */\nexport const applySearchScope = async <RouteEnv extends Env = Env>(opts: {\n resolve: TSearchScopeResolver<RouteEnv>;\n context: TRouteContext<RouteEnv>;\n input: TSearchInput;\n}): Promise<TSearchInput> => {\n const { resolve, context, input } = opts;\n\n let scope: Awaited<ReturnType<TSearchScopeResolver<RouteEnv>>>;\n try {\n scope = await resolve({ context });\n } catch (error) {\n throw refuse({\n statusCode: HTTP.ResultCodes.RS_4.Forbidden,\n message: '[search] the search scope could not be resolved for this request',\n cause: error,\n });\n }\n\n if (scope === ScopeFilters.UNRESTRICTED) {\n return input;\n }\n\n if (scope === null || scope === undefined) {\n throw refuse({\n statusCode: HTTP.ResultCodes.RS_4.Forbidden,\n message: '[search] no search scope for this request',\n });\n }\n\n if (input.mode === SearchModes.RAW) {\n throw refuse({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: \"[search] mode 'raw' is not available on a scoped search controller\",\n });\n }\n\n if (input.engineParams !== undefined) {\n throw refuse({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: '[search] engineParams is not available on a scoped search controller',\n });\n }\n\n const clientWhere = input.filter?.where;\n\n return {\n ...input,\n filter: {\n ...input.filter,\n where: clientWhere ? { and: [scope, clientWhere] } : scope,\n },\n } as TSearchInput;\n};\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Refuses to boot when `settings.
|
|
2
|
+
* Refuses to boot when `settings.access` is declared where it cannot be honoured. Both cases
|
|
3
3
|
* are silent at runtime and fail in OPPOSITE directions: a search-backed model returns more rows,
|
|
4
4
|
* a context-less one returns none. The caller supplies `asyncContextEnabled` so no application
|
|
5
5
|
* config type reaches into this tier.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scope-filter.d.ts","sourceRoot":"","sources":["../../../src/common/scope-filter.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"scope-filter.d.ts","sourceRoot":"","sources":["../../../src/common/scope-filter.ts"],"names":[],"mappings":"AAMA;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,GAAI,MAAM;IAAE,mBAAmB,EAAE,OAAO,CAAA;CAAE,KAAG,IA2EnF,CAAC"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { resolveValue } from '@venizia/ignis-helpers/common';
|
|
2
2
|
import { getError } from '@venizia/ignis-helpers/core';
|
|
3
|
-
import { MetadataRegistry } from '@venizia/ignis-kernel';
|
|
3
|
+
import { MetadataRegistry, ScopeWriteGuards } from '@venizia/ignis-kernel';
|
|
4
4
|
import { BaseSearchEntity } from '../search/core/models/index.js';
|
|
5
|
+
import { getTableColumns, is, Table } from 'drizzle-orm';
|
|
5
6
|
/**
|
|
6
|
-
* Refuses to boot when `settings.
|
|
7
|
+
* Refuses to boot when `settings.access` is declared where it cannot be honoured. Both cases
|
|
7
8
|
* are silent at runtime and fail in OPPOSITE directions: a search-backed model returns more rows,
|
|
8
9
|
* a context-less one returns none. The caller supplies `asyncContextEnabled` so no application
|
|
9
10
|
* config type reaches into this tier.
|
|
@@ -12,8 +13,9 @@ export const assertScopeFilterSupported = (opts) => {
|
|
|
12
13
|
const models = MetadataRegistry.getInstance().getAllModels();
|
|
13
14
|
const searchBacked = [];
|
|
14
15
|
const withoutAmbientContext = [];
|
|
16
|
+
const invalidWriteGuard = [];
|
|
15
17
|
for (const [name, entry] of models) {
|
|
16
|
-
if (!entry.metadata?.settings?.
|
|
18
|
+
if (!entry.metadata?.settings?.access) {
|
|
17
19
|
continue;
|
|
18
20
|
}
|
|
19
21
|
const modelClass = resolveValue({ value: entry.target });
|
|
@@ -24,24 +26,48 @@ export const assertScopeFilterSupported = (opts) => {
|
|
|
24
26
|
if (!opts.asyncContextEnabled) {
|
|
25
27
|
withoutAmbientContext.push(name);
|
|
26
28
|
}
|
|
29
|
+
const { columns, write } = entry.metadata.settings.access;
|
|
30
|
+
const writeGuard = write?.mode;
|
|
31
|
+
if (writeGuard !== undefined && !ScopeWriteGuards.isValid(writeGuard)) {
|
|
32
|
+
invalidWriteGuard.push(`${name}: write.mode '${String(writeGuard)}' is not reject or assign`);
|
|
33
|
+
}
|
|
34
|
+
if (columns !== undefined) {
|
|
35
|
+
const schema = modelClass.schema;
|
|
36
|
+
const known = is(schema, Table) ? Object.keys(getTableColumns(schema)) : undefined;
|
|
37
|
+
const unknown = columns.filter((column) => known !== undefined && !known.includes(column));
|
|
38
|
+
if (!Array.isArray(columns) || columns.length === 0) {
|
|
39
|
+
invalidWriteGuard.push(`${name}: columns must be a non-empty list of property names`);
|
|
40
|
+
}
|
|
41
|
+
else if (unknown.length > 0) {
|
|
42
|
+
invalidWriteGuard.push(`${name}: columns names ${unknown.join(', ')}, which the model does not have`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
27
45
|
}
|
|
28
46
|
if (searchBacked.length > 0) {
|
|
29
47
|
throw getError({
|
|
30
48
|
message: [
|
|
31
|
-
`[assertScopeFilterSupported] settings.
|
|
49
|
+
`[assertScopeFilterSupported] settings.access on a search-backed model | models: ${searchBacked.join(', ')}`,
|
|
32
50
|
'Search repositories never read this setting, so no row scope is applied.',
|
|
33
51
|
'Unlike the relational path, a missing scope here returns MORE rows rather than none - nothing fails, the result is just wider.',
|
|
34
|
-
'Scope the search query in the application, and remove settings.
|
|
52
|
+
'Scope the search query in the application, and remove settings.access from the model.',
|
|
53
|
+
].join(' | '),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
if (invalidWriteGuard.length > 0) {
|
|
57
|
+
throw getError({
|
|
58
|
+
message: [
|
|
59
|
+
`[assertScopeFilterSupported] invalid settings.access write guard | ${invalidWriteGuard.join(' | ')}`,
|
|
60
|
+
'write.mode is reject or assign; columns, when declared, names properties of the model.',
|
|
35
61
|
].join(' | '),
|
|
36
62
|
});
|
|
37
63
|
}
|
|
38
64
|
if (withoutAmbientContext.length > 0) {
|
|
39
65
|
throw getError({
|
|
40
66
|
message: [
|
|
41
|
-
`[assertScopeFilterSupported] settings.
|
|
42
|
-
'
|
|
67
|
+
`[assertScopeFilterSupported] settings.access declared while asyncContext.enable is false | models: ${withoutAmbientContext.join(', ')}`,
|
|
68
|
+
'access.resolve() takes no arguments, so the ambient request context is its only input.',
|
|
43
69
|
'With no context store every resolve() returns undefined, onMissing denies by default, and EVERY query on these models matches zero rows - with nothing naming the flag as the cause.',
|
|
44
|
-
'Set asyncContext.enable to true, or remove settings.
|
|
70
|
+
'Set asyncContext.enable to true, or remove settings.access.',
|
|
45
71
|
].join(' | '),
|
|
46
72
|
});
|
|
47
73
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scope-filter.js","sourceRoot":"","sources":["../../../src/common/scope-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"scope-filter.js","sourceRoot":"","sources":["../../../src/common/scope-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEzD;;;;;GAKG;AACH,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AAC,EAAE,CAAC;QACrC,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE;gBACP,sGAAsG,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBACxI,wFAAwF;gBACxF,sLAAsL;gBACtL,6DAA6D;aAC9D,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC","sourcesContent":["import { resolveValue } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { MetadataRegistry, ScopeWriteGuards } from '@venizia/ignis-kernel';\nimport { BaseSearchEntity } from '@/search/core/models';\nimport { getTableColumns, is, Table } from 'drizzle-orm';\n\n/**\n * Refuses to boot when `settings.access` is declared where it cannot be honoured. Both cases\n * are silent at runtime and fail in OPPOSITE directions: a search-backed model returns more rows,\n * a context-less one returns none. The caller supplies `asyncContextEnabled` so no application\n * config type reaches into this tier.\n */\nexport const assertScopeFilterSupported = (opts: { asyncContextEnabled: boolean }): void => {\n const models = MetadataRegistry.getInstance().getAllModels();\n\n const searchBacked: string[] = [];\n const withoutAmbientContext: string[] = [];\n const invalidWriteGuard: string[] = [];\n\n for (const [name, entry] of models) {\n if (!entry.metadata?.settings?.access) {\n continue;\n }\n\n const modelClass = resolveValue({ value: entry.target });\n\n if (modelClass === BaseSearchEntity || modelClass.prototype instanceof BaseSearchEntity) {\n searchBacked.push(name);\n continue;\n }\n\n if (!opts.asyncContextEnabled) {\n withoutAmbientContext.push(name);\n }\n\n const { columns, write } = entry.metadata.settings.access;\n const writeGuard = write?.mode;\n\n if (writeGuard !== undefined && !ScopeWriteGuards.isValid(writeGuard)) {\n invalidWriteGuard.push(`${name}: write.mode '${String(writeGuard)}' is not reject or assign`);\n }\n\n if (columns !== undefined) {\n const schema = (modelClass as { schema?: unknown }).schema;\n const known = is(schema, Table) ? Object.keys(getTableColumns(schema)) : undefined;\n const unknown = columns.filter((column) => known !== undefined && !known.includes(column));\n\n if (!Array.isArray(columns) || columns.length === 0) {\n invalidWriteGuard.push(`${name}: columns must be a non-empty list of property names`);\n } else if (unknown.length > 0) {\n invalidWriteGuard.push(\n `${name}: columns names ${unknown.join(', ')}, which the model does not have`,\n );\n }\n }\n }\n\n if (searchBacked.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] settings.access on a search-backed model | models: ${searchBacked.join(', ')}`,\n 'Search repositories never read this setting, so no row scope is applied.',\n 'Unlike the relational path, a missing scope here returns MORE rows rather than none - nothing fails, the result is just wider.',\n 'Scope the search query in the application, and remove settings.access from the model.',\n ].join(' | '),\n });\n }\n\n if (invalidWriteGuard.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] invalid settings.access write guard | ${invalidWriteGuard.join(' | ')}`,\n 'write.mode is reject or assign; columns, when declared, names properties of the model.',\n ].join(' | '),\n });\n }\n\n if (withoutAmbientContext.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] settings.access declared while asyncContext.enable is false | models: ${withoutAmbientContext.join(', ')}`,\n 'access.resolve() takes no arguments, so the ambient request context is its only input.',\n 'With no context store every resolve() returns undefined, onMissing denies by default, and EVERY query on these models matches zero rows - with nothing naming the flag as the cause.',\n 'Set asyncContext.enable to true, or remove settings.access.',\n ].join(' | '),\n });\n }\n};\n"]}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { IModelAccessSettings, TWhere } from '@venizia/ignis-kernel';
|
|
2
|
+
/** The allowed values per scope column, each normalised so `1` and `'1'` and equal dates compare equal. */
|
|
3
|
+
type TConstraints = Map<string, Set<string | null>>;
|
|
4
|
+
type TExtraction = {
|
|
5
|
+
isVerifiable: true;
|
|
6
|
+
constraints: TConstraints;
|
|
7
|
+
} | {
|
|
8
|
+
isVerifiable: false;
|
|
9
|
+
reason: string;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The write side of `@model` settings.access. The resolved scope is a `where`; the guard reads
|
|
13
|
+
* from it the columns it constrains and the values it allows, and holds every written row to them.
|
|
14
|
+
*
|
|
15
|
+
* Only shapes that can be checked are read: a column equal to a scalar or `null`, `{ eq }`, `{ inq }`
|
|
16
|
+
* (or `in`), an array, `and` of those, and an `or` whose branches all constrain the same column. Anything
|
|
17
|
+
* else - an `or` over several columns, ranges, `like`, a nested path - makes
|
|
18
|
+
* the scope unverifiable, and the write is refused with its own message instead of being skipped.
|
|
19
|
+
*/
|
|
20
|
+
export declare class ScopeWriteGuard {
|
|
21
|
+
static extractConstraints(opts: {
|
|
22
|
+
where: TWhere;
|
|
23
|
+
}): TExtraction;
|
|
24
|
+
/** Adds the where's constraints to `constraints`; returns the reason it cannot be verified, if any. */
|
|
25
|
+
private static collect;
|
|
26
|
+
/**
|
|
27
|
+
* An `or` is checkable only when every branch constrains the same single column with a scalar,
|
|
28
|
+
* `null`, `eq`, `in` or `inq`: the allowed values are then the union of the branches. This is the
|
|
29
|
+
* shared-rows scope, `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }`. Any other `or`
|
|
30
|
+
* (several columns, ranges, nested `and` or `or`) cannot be checked.
|
|
31
|
+
*/
|
|
32
|
+
private static unionOfBranches;
|
|
33
|
+
/** The values one column's condition allows, or a string naming why it cannot be checked. */
|
|
34
|
+
private static allowedValues;
|
|
35
|
+
/**
|
|
36
|
+
* Holds `rows` to the scope `settings.resolve()` returns now. Returns the rows to write: the same
|
|
37
|
+
* objects when nothing changes, copies with the scope columns filled in for `assign`. Throws, and
|
|
38
|
+
* so writes nothing, when any row is outside the scope.
|
|
39
|
+
*/
|
|
40
|
+
static apply<Row extends Record<string, unknown>>(opts: {
|
|
41
|
+
settings: IModelAccessSettings;
|
|
42
|
+
model: string;
|
|
43
|
+
rows: Row[];
|
|
44
|
+
operation: 'create' | 'update';
|
|
45
|
+
}): Row[];
|
|
46
|
+
/** Names the model and the column, never a value: the caller may be a request. */
|
|
47
|
+
private static denied;
|
|
48
|
+
}
|
|
49
|
+
export {};
|
|
50
|
+
//# sourceMappingURL=scope-write-guard.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope-write-guard.d.ts","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/common/scope-write-guard.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAK1E,2GAA2G;AAC3G,KAAK,YAAY,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC;AAEpD,KAAK,WAAW,GACZ;IAAE,YAAY,EAAE,IAAI,CAAC;IAAC,WAAW,EAAE,YAAY,CAAA;CAAE,GACjD;IAAE,YAAY,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAwB5C;;;;;;;;GAQG;AACH,qBAAa,eAAe;IAC1B,MAAM,CAAC,kBAAkB,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,WAAW;IAY/D,uGAAuG;IACvG,OAAO,CAAC,MAAM,CAAC,OAAO;IAuDtB;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,eAAe;IAuC9B,6FAA6F;IAC7F,OAAO,CAAC,MAAM,CAAC,aAAa;IAyC5B;;;;OAIG;IACH,MAAM,CAAC,KAAK,CAAC,GAAG,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,EAAE;QACtD,QAAQ,EAAE,oBAAoB,CAAC;QAC/B,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,GAAG,EAAE,CAAC;QACZ,SAAS,EAAE,QAAQ,GAAG,QAAQ,CAAC;KAChC,GAAG,GAAG,EAAE;IAkGT,kFAAkF;IAClF,OAAO,CAAC,MAAM,CAAC,MAAM;CAkBtB"}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { getError } from '@venizia/ignis-helpers/core';
|
|
2
|
+
import { QueryOperators, RepositoryErrorCodes, ScopeFilterMissingBehaviors, ScopeFilters, ScopeWriteGuards, } from '@venizia/ignis-kernel';
|
|
3
|
+
import { HTTP } from '@venizia/ignis-helpers/common';
|
|
4
|
+
const WRITE_DENIED_STATUS = HTTP.ResultCodes.RS_4.Forbidden;
|
|
5
|
+
const isScalar = (value) => {
|
|
6
|
+
return (value === null ||
|
|
7
|
+
value instanceof Date ||
|
|
8
|
+
['string', 'number', 'bigint', 'boolean'].includes(typeof value));
|
|
9
|
+
};
|
|
10
|
+
const normalise = (value) => {
|
|
11
|
+
if (value === null) {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
return value instanceof Date ? value.toISOString() : String(value);
|
|
15
|
+
};
|
|
16
|
+
const intersect = (opts) => {
|
|
17
|
+
return new Set([...opts.left].filter((value) => opts.right.has(value)));
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The write side of `@model` settings.access. The resolved scope is a `where`; the guard reads
|
|
21
|
+
* from it the columns it constrains and the values it allows, and holds every written row to them.
|
|
22
|
+
*
|
|
23
|
+
* Only shapes that can be checked are read: a column equal to a scalar or `null`, `{ eq }`, `{ inq }`
|
|
24
|
+
* (or `in`), an array, `and` of those, and an `or` whose branches all constrain the same column. Anything
|
|
25
|
+
* else - an `or` over several columns, ranges, `like`, a nested path - makes
|
|
26
|
+
* the scope unverifiable, and the write is refused with its own message instead of being skipped.
|
|
27
|
+
*/
|
|
28
|
+
export class ScopeWriteGuard {
|
|
29
|
+
static extractConstraints(opts) {
|
|
30
|
+
const constraints = new Map();
|
|
31
|
+
const reason = ScopeWriteGuard.collect({
|
|
32
|
+
where: opts.where,
|
|
33
|
+
constraints,
|
|
34
|
+
});
|
|
35
|
+
return reason === undefined
|
|
36
|
+
? { isVerifiable: true, constraints }
|
|
37
|
+
: { isVerifiable: false, reason };
|
|
38
|
+
}
|
|
39
|
+
/** Adds the where's constraints to `constraints`; returns the reason it cannot be verified, if any. */
|
|
40
|
+
static collect(opts) {
|
|
41
|
+
const { where, constraints } = opts;
|
|
42
|
+
for (const [key, value] of Object.entries(where)) {
|
|
43
|
+
if (key === 'and') {
|
|
44
|
+
if (!Array.isArray(value)) {
|
|
45
|
+
return "'and' is not a list";
|
|
46
|
+
}
|
|
47
|
+
for (const part of value) {
|
|
48
|
+
const reason = ScopeWriteGuard.collect({
|
|
49
|
+
where: part,
|
|
50
|
+
constraints,
|
|
51
|
+
});
|
|
52
|
+
if (reason !== undefined) {
|
|
53
|
+
return reason;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (key === 'or') {
|
|
59
|
+
const union = ScopeWriteGuard.unionOfBranches({ branches: value });
|
|
60
|
+
if (typeof union === 'string') {
|
|
61
|
+
return union;
|
|
62
|
+
}
|
|
63
|
+
const existing = constraints.get(union.column);
|
|
64
|
+
constraints.set(union.column, existing ? intersect({ left: existing, right: union.allowed }) : union.allowed);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (key.includes('.')) {
|
|
68
|
+
return `the nested path '${key}' cannot be checked on a write`;
|
|
69
|
+
}
|
|
70
|
+
const allowed = ScopeWriteGuard.allowedValues({ value });
|
|
71
|
+
if (typeof allowed === 'string') {
|
|
72
|
+
return `column '${key}': ${allowed}`;
|
|
73
|
+
}
|
|
74
|
+
const existing = constraints.get(key);
|
|
75
|
+
constraints.set(key, existing ? intersect({ left: existing, right: allowed }) : allowed);
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* An `or` is checkable only when every branch constrains the same single column with a scalar,
|
|
81
|
+
* `null`, `eq`, `in` or `inq`: the allowed values are then the union of the branches. This is the
|
|
82
|
+
* shared-rows scope, `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }`. Any other `or`
|
|
83
|
+
* (several columns, ranges, nested `and` or `or`) cannot be checked.
|
|
84
|
+
*/
|
|
85
|
+
static unionOfBranches(opts) {
|
|
86
|
+
const { branches } = opts;
|
|
87
|
+
if (!Array.isArray(branches) || branches.length === 0) {
|
|
88
|
+
return "'or' is not a list";
|
|
89
|
+
}
|
|
90
|
+
let column;
|
|
91
|
+
const allowed = new Set();
|
|
92
|
+
for (const branch of branches) {
|
|
93
|
+
const entries = Object.entries((branch ?? {}));
|
|
94
|
+
if (entries.length !== 1) {
|
|
95
|
+
return "an 'or' branch with several conditions cannot be checked on a write";
|
|
96
|
+
}
|
|
97
|
+
const [key, value] = entries[0];
|
|
98
|
+
if (key === 'and' || key === 'or' || key.includes('.')) {
|
|
99
|
+
return `an 'or' branch over '${key}' cannot be checked on a write`;
|
|
100
|
+
}
|
|
101
|
+
if (column !== undefined && column !== key) {
|
|
102
|
+
return "an 'or' over different columns cannot be checked on a write";
|
|
103
|
+
}
|
|
104
|
+
column = key;
|
|
105
|
+
const values = ScopeWriteGuard.allowedValues({ value });
|
|
106
|
+
if (typeof values === 'string') {
|
|
107
|
+
return `column '${key}': ${values}`;
|
|
108
|
+
}
|
|
109
|
+
values.forEach((entry) => allowed.add(entry));
|
|
110
|
+
}
|
|
111
|
+
return { column: column, allowed };
|
|
112
|
+
}
|
|
113
|
+
/** The values one column's condition allows, or a string naming why it cannot be checked. */
|
|
114
|
+
static allowedValues(opts) {
|
|
115
|
+
const { value } = opts;
|
|
116
|
+
if (isScalar(value)) {
|
|
117
|
+
return new Set([normalise(value)]);
|
|
118
|
+
}
|
|
119
|
+
if (Array.isArray(value)) {
|
|
120
|
+
return value.every(isScalar)
|
|
121
|
+
? new Set(value.map(normalise))
|
|
122
|
+
: 'a list with a non-scalar entry';
|
|
123
|
+
}
|
|
124
|
+
if (typeof value !== 'object' || value === undefined) {
|
|
125
|
+
return 'an unsupported condition';
|
|
126
|
+
}
|
|
127
|
+
const operators = Object.keys(value);
|
|
128
|
+
if (operators.length !== 1) {
|
|
129
|
+
return `a condition with ${operators.length} operators cannot be checked on a write`;
|
|
130
|
+
}
|
|
131
|
+
const [operator] = operators;
|
|
132
|
+
const operand = value[operator];
|
|
133
|
+
if (operator === QueryOperators.EQ && isScalar(operand)) {
|
|
134
|
+
return new Set([normalise(operand)]);
|
|
135
|
+
}
|
|
136
|
+
if ((operator === QueryOperators.INQ || operator === QueryOperators.IN) &&
|
|
137
|
+
Array.isArray(operand)) {
|
|
138
|
+
return operand.every(isScalar)
|
|
139
|
+
? new Set(operand.map(normalise))
|
|
140
|
+
: 'a list with a non-scalar entry';
|
|
141
|
+
}
|
|
142
|
+
return `the operator '${operator}' cannot be checked on a write`;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Holds `rows` to the scope `settings.resolve()` returns now. Returns the rows to write: the same
|
|
146
|
+
* objects when nothing changes, copies with the scope columns filled in for `assign`. Throws, and
|
|
147
|
+
* so writes nothing, when any row is outside the scope.
|
|
148
|
+
*/
|
|
149
|
+
static apply(opts) {
|
|
150
|
+
const { settings, model, rows, operation } = opts;
|
|
151
|
+
const scope = settings.resolve();
|
|
152
|
+
if (scope === ScopeFilters.UNRESTRICTED) {
|
|
153
|
+
return rows;
|
|
154
|
+
}
|
|
155
|
+
if (scope === null || scope === undefined) {
|
|
156
|
+
// An update is already confined by the scoped `where`, which under `deny` matches no row; the
|
|
157
|
+
// guard adds nothing there. A create has no such `where`, so an unresolved scope refuses it.
|
|
158
|
+
if (settings.onMissing === ScopeFilterMissingBehaviors.ALLOW || operation === 'update') {
|
|
159
|
+
return rows;
|
|
160
|
+
}
|
|
161
|
+
throw ScopeWriteGuard.denied({
|
|
162
|
+
model,
|
|
163
|
+
operation,
|
|
164
|
+
detail: 'no scope could be resolved for this caller',
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
const extraction = ScopeWriteGuard.extractConstraints({ where: scope });
|
|
168
|
+
if (!extraction.isVerifiable) {
|
|
169
|
+
throw ScopeWriteGuard.denied({
|
|
170
|
+
model,
|
|
171
|
+
operation,
|
|
172
|
+
detail: `the resolved scope cannot be verified on a write | ${extraction.reason}`,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
const { constraints } = extraction;
|
|
176
|
+
const declared = settings.columns;
|
|
177
|
+
if (declared) {
|
|
178
|
+
const undeclared = [...constraints.keys()].find((column) => !declared.includes(column));
|
|
179
|
+
if (undeclared !== undefined) {
|
|
180
|
+
throw ScopeWriteGuard.denied({
|
|
181
|
+
model,
|
|
182
|
+
operation,
|
|
183
|
+
detail: `the resolved scope constrains column '${undeclared}', which access.columns does not declare`,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const isAssign = settings.write?.mode === ScopeWriteGuards.ASSIGN && operation === 'create';
|
|
188
|
+
const sharedRows = settings.write?.sharedRows === true;
|
|
189
|
+
return rows.map((row) => {
|
|
190
|
+
let result = row;
|
|
191
|
+
for (const [column, allowed] of constraints) {
|
|
192
|
+
const value = row[column];
|
|
193
|
+
if (value === undefined) {
|
|
194
|
+
if (operation === 'update') {
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
// `assign` first: stamping gives the row an owner, which is safer than leaving it shared.
|
|
198
|
+
const only = allowed.size === 1 ? [...allowed][0] : undefined;
|
|
199
|
+
if (isAssign && only !== undefined && only !== null) {
|
|
200
|
+
result = { ...result, [column]: only };
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
// Absent means the database default, usually `null`, so it is held to the `null` rule.
|
|
204
|
+
if (sharedRows) {
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
throw ScopeWriteGuard.denied({
|
|
208
|
+
model,
|
|
209
|
+
operation,
|
|
210
|
+
column,
|
|
211
|
+
detail: 'the scope column is missing',
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
const normalised = isScalar(value) ? normalise(value) : undefined;
|
|
215
|
+
// A `null` branch in the scope lets this caller READ shared rows. Writing one (or moving a
|
|
216
|
+
// row into the shared set) is a separate permission: only `sharedRows` grants it.
|
|
217
|
+
const isOutside = normalised === null ? !sharedRows : !allowed.has(normalised);
|
|
218
|
+
if (normalised === undefined || isOutside) {
|
|
219
|
+
throw ScopeWriteGuard.denied({
|
|
220
|
+
model,
|
|
221
|
+
operation,
|
|
222
|
+
column,
|
|
223
|
+
detail: 'the value is outside the resolved scope',
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return result;
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** Names the model and the column, never a value: the caller may be a request. */
|
|
231
|
+
static denied(opts) {
|
|
232
|
+
const { model, operation, column, detail } = opts;
|
|
233
|
+
return getError({
|
|
234
|
+
statusCode: WRITE_DENIED_STATUS,
|
|
235
|
+
messageCode: RepositoryErrorCodes.SCOPE_WRITE_DENIED,
|
|
236
|
+
message: [
|
|
237
|
+
`[${operation}] write refused by the access scope | entity: ${model}`,
|
|
238
|
+
...(column ? [`column: ${column}`] : []),
|
|
239
|
+
detail,
|
|
240
|
+
].join(' | '),
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
//# sourceMappingURL=scope-write-guard.js.map
|