@kinotic-ai/core 5.0.0-beta.17 → 5.0.0-beta.19

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/index.cjs CHANGED
@@ -66,6 +66,7 @@ var exports_src = {};
66
66
  __export(exports_src, {
67
67
  validateZone: () => validateZone,
68
68
  validateLabel: () => validateLabel,
69
+ serviceContractOf: () => serviceContractOf,
69
70
  scopeOptionalMethodNames: () => scopeOptionalMethodNames,
70
71
  receivesContext: () => receivesContext,
71
72
  isAdvertised: () => isAdvertised,
@@ -109,6 +110,8 @@ __export(exports_src, {
109
110
  ChainedCredentialsResolver: () => ChainedCredentialsResolver,
110
111
  BearerCredentialsResolver: () => BearerCredentialsResolver,
111
112
  BasicCredentialsResolver: () => BasicCredentialsResolver,
113
+ AuthzResource: () => AuthzResource,
114
+ AuthzCheck: () => AuthzCheck,
112
115
  AuthorizationException: () => AuthorizationException,
113
116
  AbstractIterablePage: () => AbstractIterablePage
114
117
  });
@@ -1180,6 +1183,8 @@ var versionRegistry = new WeakMap;
1180
1183
  var zonesRegistry = new WeakMap;
1181
1184
  var advertisedRegistry = new WeakMap;
1182
1185
  var contextMarkedFunctions = new WeakSet;
1186
+ var authzResourceRegistry = new WeakMap;
1187
+ var authzCheckRegistry = new WeakMap;
1183
1188
  function findInConstructorChain(registry, constructor) {
1184
1189
  let current = constructor;
1185
1190
  while (current) {
@@ -1270,6 +1275,101 @@ function resolveEffectiveZone(constructor) {
1270
1275
  }
1271
1276
  return effectiveZone;
1272
1277
  }
1278
+ function AuthzResource(declaration) {
1279
+ const resource = typeof declaration === "string" ? { value: declaration } : declaration;
1280
+ if (!resource.value) {
1281
+ throw new Error("AuthzResource must name the resource type");
1282
+ }
1283
+ return function(value, _context) {
1284
+ authzResourceRegistry.set(value, resource);
1285
+ };
1286
+ }
1287
+ function AuthzCheck(declaration) {
1288
+ return function(value, _context) {
1289
+ authzCheckRegistry.set(value, declaration);
1290
+ };
1291
+ }
1292
+ function serviceContractOf(serviceInstance, serviceIdentifier) {
1293
+ const resource = findInConstructorChain(authzResourceRegistry, serviceInstance.constructor);
1294
+ let ret = null;
1295
+ if (resource) {
1296
+ if (!serviceIdentifier.zone) {
1297
+ throw new Error(`${serviceIdentifier.qualifiedName()} declares a resource but no zone; a checked service is addressed in a zone`);
1298
+ }
1299
+ const functions = [];
1300
+ const seen = new Set;
1301
+ let proto = Object.getPrototypeOf(serviceInstance);
1302
+ while (proto && proto !== Object.prototype) {
1303
+ for (const key of Object.getOwnPropertyNames(proto)) {
1304
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1305
+ if (typeof descriptor?.value === "function" && key !== "constructor" && !seen.has(key)) {
1306
+ seen.add(key);
1307
+ const method = descriptor.value;
1308
+ const parameters = parameterNames(method);
1309
+ if (contextMarkedFunctions.has(method)) {
1310
+ parameters.pop();
1311
+ }
1312
+ functions.push({ name: key, parameters, check: authzCheckRegistry.get(method) ?? null });
1313
+ }
1314
+ }
1315
+ proto = Object.getPrototypeOf(proto);
1316
+ }
1317
+ ret = {
1318
+ namespace: serviceIdentifier.namespace,
1319
+ name: serviceIdentifier.name,
1320
+ version: serviceIdentifier.version ?? null,
1321
+ zone: serviceIdentifier.zone,
1322
+ resource,
1323
+ functions
1324
+ };
1325
+ }
1326
+ return ret;
1327
+ }
1328
+ function parameterNames(method) {
1329
+ const source = method.toString().replace(/\/\*[\s\S]*?\*\//g, "");
1330
+ let depth = 0;
1331
+ let start = -1;
1332
+ let end = -1;
1333
+ for (let i = 0;i < source.length && end < 0; i++) {
1334
+ const c = source[i];
1335
+ if (c === "(") {
1336
+ if (depth === 0 && start < 0) {
1337
+ start = i + 1;
1338
+ }
1339
+ depth++;
1340
+ } else if (c === ")") {
1341
+ depth--;
1342
+ if (depth === 0 && start >= 0) {
1343
+ end = i;
1344
+ }
1345
+ }
1346
+ }
1347
+ const ret = [];
1348
+ if (start >= 0 && end >= 0) {
1349
+ let nested = 0;
1350
+ let current = "";
1351
+ const parts = [];
1352
+ for (const c of source.substring(start, end)) {
1353
+ if ("([{".includes(c)) {
1354
+ nested++;
1355
+ } else if (")]}".includes(c)) {
1356
+ nested--;
1357
+ }
1358
+ if (c === "," && nested === 0) {
1359
+ parts.push(current);
1360
+ current = "";
1361
+ } else {
1362
+ current += c;
1363
+ }
1364
+ }
1365
+ parts.push(current);
1366
+ parts.map((part) => (part.split("=")[0] ?? "").trim()).filter((part) => part.length > 0).forEach((part, index) => {
1367
+ const name = part.replace(/^\.\.\./, "");
1368
+ ret.push(/^[A-Za-z_$][\w$]*$/.test(name) ? name : `arg${index}`);
1369
+ });
1370
+ }
1371
+ return ret;
1372
+ }
1273
1373
  function Publish(namespace, name, advertise = false) {
1274
1374
  return function(value, _context) {
1275
1375
  advertisedRegistry.set(value, advertise);
@@ -1297,7 +1397,7 @@ var import_api2 = __toESM(require("@opentelemetry/api"));
1297
1397
  // packages/core/package.json
1298
1398
  var package_default = {
1299
1399
  name: "@kinotic-ai/core",
1300
- version: "5.0.0-beta.17",
1400
+ version: "5.0.0-beta.19",
1301
1401
  type: "module",
1302
1402
  files: [
1303
1403
  "dist"
@@ -1356,8 +1456,8 @@ var package_default = {
1356
1456
  "@vitest/coverage-v8": "^4.1.4",
1357
1457
  "@vitest/runner": "^4.1.4",
1358
1458
  "@vitest/ui": "^4.1.4",
1359
- allure: "^3.14.3",
1360
- "allure-vitest": "^3.10.2",
1459
+ allure: "^3.19.1",
1460
+ "allure-vitest": "^3.13.0",
1361
1461
  dotenv: "^17.4.1",
1362
1462
  "properties-file": "^4.0.0",
1363
1463
  testcontainers: "^11.14.0",
@@ -1756,10 +1856,13 @@ class TextEventFactory {
1756
1856
  return event;
1757
1857
  }
1758
1858
  }
1859
+ var SERVICE_CONTRACT_SERVICE = "app-api~org.kinotic.app.api.services.ServiceContractService";
1860
+ var APPLICATION_ZONE = /^app\.[^.]+\.([^.]+)(\.|$)/;
1759
1861
 
1760
1862
  class ServiceRegistry {
1761
1863
  _eventBus;
1762
1864
  supervisors = new Map;
1865
+ contracts = new Map;
1763
1866
  contextInterceptor = null;
1764
1867
  debugLogger = import_debug3.default("kinotic:serviceRegistry");
1765
1868
  constructor(eventBus) {
@@ -1781,9 +1884,16 @@ class ServiceRegistry {
1781
1884
  const criString = serviceIdentifier.cri().raw();
1782
1885
  if (!this.supervisors.has(criString)) {
1783
1886
  this.debugLogger(`Registering service for CRI: ${criString}`);
1887
+ const contract = serviceContractOf(service, serviceIdentifier);
1784
1888
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1785
1889
  this.supervisors.set(criString, supervisor);
1786
1890
  supervisor.start();
1891
+ if (contract) {
1892
+ this.contracts.set(criString, contract);
1893
+ if (this.eventBus.isConnected()) {
1894
+ this.publishContract(contract).catch((error) => this.debugLogger(`Failed to publish the contract of ${criString}`, error));
1895
+ }
1896
+ }
1787
1897
  }
1788
1898
  }
1789
1899
  unRegister(serviceIdentifier) {
@@ -1793,6 +1903,22 @@ class ServiceRegistry {
1793
1903
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1794
1904
  supervisor.stop();
1795
1905
  this.supervisors.delete(criString);
1906
+ this.contracts.delete(criString);
1907
+ }
1908
+ }
1909
+ async publishContracts() {
1910
+ for (const contract of this.contracts.values()) {
1911
+ await this.publishContract(contract);
1912
+ }
1913
+ }
1914
+ registeredContracts() {
1915
+ return this.contracts;
1916
+ }
1917
+ async publishContract(contract) {
1918
+ const application = APPLICATION_ZONE.exec(contract.zone);
1919
+ if (application) {
1920
+ this.debugLogger(`Publishing the contract of ${contract.zone}~${contract.namespace}.${contract.name}`);
1921
+ await this.serviceProxy(SERVICE_CONTRACT_SERVICE).invoke("register", [application[1], contract]);
1796
1922
  }
1797
1923
  }
1798
1924
  registerContextInterceptor(interceptor) {
@@ -1886,8 +2012,10 @@ class KinoticSingleton {
1886
2012
  this._eventBus = eventBus;
1887
2013
  this.serviceRegistry.eventBus = eventBus;
1888
2014
  }
1889
- connect(options) {
1890
- return this._eventBus.connect(Util.resolveConnectOptions(options));
2015
+ async connect(options) {
2016
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
2017
+ await this.serviceRegistry.publishContracts();
2018
+ return ret;
1891
2019
  }
1892
2020
  disconnect(force) {
1893
2021
  return this._eventBus.disconnect(force);
package/dist/index.d.cts CHANGED
@@ -648,6 +648,70 @@ interface IServiceRegistry {
648
648
  registerContextInterceptor<T extends ServiceContext>(interceptor: ContextInterceptor<T> | null): void;
649
649
  }
650
650
  /**
651
+ * A role a service declares for its resource type, named `<type>.<level>`, bundling permissions of the type.
652
+ */
653
+ interface AuthzRoleDeclaration {
654
+ /** The role's id, `<type>.<level>` with a lowercase identifier as the level. */
655
+ id: string;
656
+ /** The short names of the type's permissions the role bundles, such as `can_generate`. */
657
+ permissions: string[];
658
+ }
659
+ /**
660
+ * What a service declares about the resource its functions act on, as {@link AuthzResource} declares it.
661
+ */
662
+ interface AuthzResourceDeclaration {
663
+ /** The resource type, a lowercase identifier such as `report`. */
664
+ value: string;
665
+ /** The type the resource sits under, such as `tenant` or `application`; absent for a root type. */
666
+ parent?: string | null;
667
+ /** The id template every function is checked on, such as `{@applicationId}`, when the service acts on one object. */
668
+ objectId?: string | null;
669
+ /** The permission every function of the service needs, when they all need the same one. */
670
+ permission?: string | null;
671
+ /** The roles the service declares for its type. */
672
+ roles?: AuthzRoleDeclaration[] | null;
673
+ }
674
+ /**
675
+ * What a function declares about its check, as {@link AuthzCheck} declares it; whatever is left out is derived
676
+ * from the function's name and parameters.
677
+ */
678
+ interface AuthzCheckDeclaration {
679
+ /** The short permission name, such as `can_generate`. */
680
+ permission?: string | null;
681
+ /** The type of the object the check is made on, when it is not the service's own. */
682
+ resource?: string | null;
683
+ /** The id template of the object, over the function's parameters and the caller's scope, such as `{reportId}`. */
684
+ objectId?: string | null;
685
+ /** Short names of permissions this one implies. */
686
+ implies?: string[] | null;
687
+ /** True for a function any caller the zone admits may call, which carries no check. */
688
+ zoneOnly?: boolean;
689
+ /** True for a check that must answer from the stored relationships rather than the engine's caches. */
690
+ consistent?: boolean;
691
+ }
692
+ /**
693
+ * One function of a service's contract: its name, the names of the parameters a request carries, in order,
694
+ * and what it declares about its check.
695
+ */
696
+ interface FunctionContract {
697
+ name: string;
698
+ parameters: string[];
699
+ check?: AuthzCheckDeclaration | null;
700
+ }
701
+ /**
702
+ * The contract of a service a runtime publishes, as the platform's directory stores it: where the service is
703
+ * addressed, the resource it declares and its functions. The platform derives each function's check from it,
704
+ * generates the application's authorization model with it, and checks every request to the service against it.
705
+ */
706
+ interface ServiceContract {
707
+ namespace: string | null;
708
+ name: string;
709
+ version: string | null;
710
+ zone: string;
711
+ resource: AuthzResourceDeclaration;
712
+ functions: FunctionContract[];
713
+ }
714
+ /**
651
715
  * An implementation of a {@link IEventFactory} which uses JSON content
652
716
  */
653
717
  declare class JsonEventFactory implements IEventFactory {
@@ -659,12 +723,10 @@ declare class JsonEventFactory implements IEventFactory {
659
723
  declare class TextEventFactory implements IEventFactory {
660
724
  create(cri: string, args: any[] | null | undefined): IEvent;
661
725
  }
662
- /**
663
- * The default implementation of {@link IServiceRegistry}
664
- */
665
726
  declare class ServiceRegistry implements IServiceRegistry {
666
727
  private _eventBus;
667
728
  private supervisors;
729
+ private contracts;
668
730
  private contextInterceptor;
669
731
  private debugLogger;
670
732
  constructor(eventBus: IEventBus);
@@ -673,6 +735,17 @@ declare class ServiceRegistry implements IServiceRegistry {
673
735
  serviceProxy(serviceIdentifier: string): IServiceProxy;
674
736
  register(serviceIdentifier: ServiceIdentifier, service: any): void;
675
737
  unRegister(serviceIdentifier: ServiceIdentifier): void;
738
+ /**
739
+ * Publishes the contract of every checked service registered so far to the platform's directory, so the
740
+ * platform checks requests to them; a contract the platform refuses fails the publication. The contract of
741
+ * a service registered later is published as it registers.
742
+ */
743
+ publishContracts(): Promise<void>;
744
+ /**
745
+ * The contracts of the checked services registered, by the CRI each is registered under.
746
+ */
747
+ registeredContracts(): ReadonlyMap<string, ServiceContract>;
748
+ private publishContract;
676
749
  registerContextInterceptor<T extends ServiceContext>(interceptor: ContextInterceptor<T> | null): void;
677
750
  }
678
751
  /**
@@ -740,8 +813,9 @@ declare class KinoticSingleton implements IKinotic {
740
813
  get eventBus(): IEventBus;
741
814
  set eventBus(eventBus: IEventBus);
742
815
  /**
743
- * Connects to a Kinotic server. Every option is optional: absent server fields and
744
- * credentials resolve from the environment — see {@link ConnectOptions}.
816
+ * Connects to a Kinotic server and publishes the contracts of the checked services registered so far.
817
+ * Every option is optional: absent server fields and credentials resolve from the environment — see
818
+ * {@link ConnectOptions}.
745
819
  * @param options overrides for the resolved connection, or nothing to resolve everything
746
820
  * @return Promise containing the result of the initial connection attempt
747
821
  */
@@ -820,6 +894,34 @@ declare function Context(value: Function, _context: ClassMethodDecoratorContext)
820
894
  */
821
895
  declare function receivesContext(serviceInstance: object, methodName: string): boolean;
822
896
  /**
897
+ * Declares the resource a service's functions act on, which puts the service's contract in the platform's
898
+ * directory when its instance registers, so every request to it is checked. The check of each function is
899
+ * derived by the platform from the function's name and parameters, as it is for the platform's own services:
900
+ * a `find`, `get`, `count`, `search` or `list` function needs `can_view`, a `save`, `update` or `set` function
901
+ * `can_edit`, a `delete` or `remove` function `can_delete`, and a `create` function `can_edit` on the parent,
902
+ * each on the object a parameter named `id` or `<type>Id` names, or on the parent when none does. A function
903
+ * the derivation cannot read declares its check with {@link AuthzCheck}.
904
+ * @param declaration the resource type, or the type with its parent, object, permission and roles
905
+ */
906
+ declare function AuthzResource(declaration: AuthzResourceDeclaration | string): (value: Function, _context: ClassDecoratorContext<any>) => void;
907
+ /**
908
+ * Declares the check of a function of an {@link AuthzResource} service: a permission of its own, such as
909
+ * `can_generate`, another object than the derived one, the permissions it implies, a consistent answer, or
910
+ * that any caller the zone admits may call it (`zoneOnly`).
911
+ * @param declaration what the derivation cannot read from the function's name and parameters
912
+ */
913
+ declare function AuthzCheck(declaration: AuthzCheckDeclaration): (value: Function, _context: ClassMethodDecoratorContext) => void;
914
+ /**
915
+ * The contract of a service instance registered under the identifier, or null for a class declaring no
916
+ * {@link AuthzResource}: its functions are the methods of its prototype chain, each with the names of the
917
+ * parameters a request carries, read from the method's source, less the context a {@link Context} method
918
+ * takes last. A runtime whose build renames parameters publishes names a check's template cannot reference,
919
+ * which the platform refuses at registration.
920
+ * @param serviceInstance the registered instance
921
+ * @param serviceIdentifier how it is addressed, which the contract names
922
+ */
923
+ declare function serviceContractOf(serviceInstance: object, serviceIdentifier: ServiceIdentifier): ServiceContract | null;
924
+ /**
823
925
  * Registers each instance of the decorated class with the Kinotic ServiceRegistry.
824
926
  * The service name defaults to the class name; {@link Version}, {@link Scope}, and {@link Zone}
825
927
  * on the same class refine the registration.
@@ -1423,7 +1525,7 @@ declare class ParticipantConstants {
1423
1525
  static readonly PARTICIPANT_TYPE_DELEGATE: string;
1424
1526
  /** A non-human caller with its own credential — a platform daemon or an external API client. */
1425
1527
  static readonly PARTICIPANT_TYPE_MACHINE: string;
1426
- /** The clientId TestSecurityService (clienttest profile) maps to the ANONYMOUS role in core package tests. */
1528
+ /** The clientId the test server's TestSecurityService maps to the ANONYMOUS role in core package tests. */
1427
1529
  static readonly CLI_PARTICIPANT_ID: string;
1428
1530
  }
1429
- export { validateZone, validateLabel, scopeOptionalMethodNames, receivesContext, isAdvertised, createCRI, buildServerUrl, buildBrokerUrl, Zone, WebSocketFactory, Version, TextEventFactory, Sort, SessionKeepAliveMode, SessionCredentialsResolver, ServiceRegistry, ServiceIdentifier, ServiceContext, ServerInfo, ScopeOptional, Scope, RpcError, ResolvedCredentials, Publish, ParticipantConstants, Participant, Pageable, Page, Order, OffsetPageable, NullHandling, KinoticSingleton, KinoticPlugin, Kinotic, JsonEventFactory, IterablePage, Identifiable, IWebSocket, IServiceRegistry, IServiceProxy, IParticipant, IKinotic, IEventFactory, IEventBus, IEvent, IEditableDataSource, IDataSource, ICrudServiceProxyFactory, ICrudServiceProxy, FunctionalIterablePage, EventConstants, EventBus, Event, EnvCredentialsResolver, Direction, DefaultCRI, DataSourceUtils, CursorPageable, CrudServiceProxyFactory, CrudServiceProxy, CredentialsResolver, ContextInterceptor, Context, ConnectedInfo, ConnectOptions, ChainedCredentialsResolver, CRI, BearerCredentialsResolver, BasicCredentialsResolver, AuthorizationException, AbstractIterablePage };
1531
+ export { validateZone, validateLabel, serviceContractOf, scopeOptionalMethodNames, receivesContext, isAdvertised, createCRI, buildServerUrl, buildBrokerUrl, Zone, WebSocketFactory, Version, TextEventFactory, Sort, SessionKeepAliveMode, SessionCredentialsResolver, ServiceRegistry, ServiceIdentifier, ServiceContract, ServiceContext, ServerInfo, ScopeOptional, Scope, RpcError, ResolvedCredentials, Publish, ParticipantConstants, Participant, Pageable, Page, Order, OffsetPageable, NullHandling, KinoticSingleton, KinoticPlugin, Kinotic, JsonEventFactory, IterablePage, Identifiable, IWebSocket, IServiceRegistry, IServiceProxy, IParticipant, IKinotic, IEventFactory, IEventBus, IEvent, IEditableDataSource, IDataSource, ICrudServiceProxyFactory, ICrudServiceProxy, FunctionalIterablePage, FunctionContract, EventConstants, EventBus, Event, EnvCredentialsResolver, Direction, DefaultCRI, DataSourceUtils, CursorPageable, CrudServiceProxyFactory, CrudServiceProxy, CredentialsResolver, ContextInterceptor, Context, ConnectedInfo, ConnectOptions, ChainedCredentialsResolver, CRI, BearerCredentialsResolver, BasicCredentialsResolver, AuthzRoleDeclaration, AuthzResourceDeclaration, AuthzResource, AuthzCheckDeclaration, AuthzCheck, AuthorizationException, AbstractIterablePage };
package/dist/index.d.ts CHANGED
@@ -648,6 +648,70 @@ interface IServiceRegistry {
648
648
  registerContextInterceptor<T extends ServiceContext>(interceptor: ContextInterceptor<T> | null): void;
649
649
  }
650
650
  /**
651
+ * A role a service declares for its resource type, named `<type>.<level>`, bundling permissions of the type.
652
+ */
653
+ interface AuthzRoleDeclaration {
654
+ /** The role's id, `<type>.<level>` with a lowercase identifier as the level. */
655
+ id: string;
656
+ /** The short names of the type's permissions the role bundles, such as `can_generate`. */
657
+ permissions: string[];
658
+ }
659
+ /**
660
+ * What a service declares about the resource its functions act on, as {@link AuthzResource} declares it.
661
+ */
662
+ interface AuthzResourceDeclaration {
663
+ /** The resource type, a lowercase identifier such as `report`. */
664
+ value: string;
665
+ /** The type the resource sits under, such as `tenant` or `application`; absent for a root type. */
666
+ parent?: string | null;
667
+ /** The id template every function is checked on, such as `{@applicationId}`, when the service acts on one object. */
668
+ objectId?: string | null;
669
+ /** The permission every function of the service needs, when they all need the same one. */
670
+ permission?: string | null;
671
+ /** The roles the service declares for its type. */
672
+ roles?: AuthzRoleDeclaration[] | null;
673
+ }
674
+ /**
675
+ * What a function declares about its check, as {@link AuthzCheck} declares it; whatever is left out is derived
676
+ * from the function's name and parameters.
677
+ */
678
+ interface AuthzCheckDeclaration {
679
+ /** The short permission name, such as `can_generate`. */
680
+ permission?: string | null;
681
+ /** The type of the object the check is made on, when it is not the service's own. */
682
+ resource?: string | null;
683
+ /** The id template of the object, over the function's parameters and the caller's scope, such as `{reportId}`. */
684
+ objectId?: string | null;
685
+ /** Short names of permissions this one implies. */
686
+ implies?: string[] | null;
687
+ /** True for a function any caller the zone admits may call, which carries no check. */
688
+ zoneOnly?: boolean;
689
+ /** True for a check that must answer from the stored relationships rather than the engine's caches. */
690
+ consistent?: boolean;
691
+ }
692
+ /**
693
+ * One function of a service's contract: its name, the names of the parameters a request carries, in order,
694
+ * and what it declares about its check.
695
+ */
696
+ interface FunctionContract {
697
+ name: string;
698
+ parameters: string[];
699
+ check?: AuthzCheckDeclaration | null;
700
+ }
701
+ /**
702
+ * The contract of a service a runtime publishes, as the platform's directory stores it: where the service is
703
+ * addressed, the resource it declares and its functions. The platform derives each function's check from it,
704
+ * generates the application's authorization model with it, and checks every request to the service against it.
705
+ */
706
+ interface ServiceContract {
707
+ namespace: string | null;
708
+ name: string;
709
+ version: string | null;
710
+ zone: string;
711
+ resource: AuthzResourceDeclaration;
712
+ functions: FunctionContract[];
713
+ }
714
+ /**
651
715
  * An implementation of a {@link IEventFactory} which uses JSON content
652
716
  */
653
717
  declare class JsonEventFactory implements IEventFactory {
@@ -659,12 +723,10 @@ declare class JsonEventFactory implements IEventFactory {
659
723
  declare class TextEventFactory implements IEventFactory {
660
724
  create(cri: string, args: any[] | null | undefined): IEvent;
661
725
  }
662
- /**
663
- * The default implementation of {@link IServiceRegistry}
664
- */
665
726
  declare class ServiceRegistry implements IServiceRegistry {
666
727
  private _eventBus;
667
728
  private supervisors;
729
+ private contracts;
668
730
  private contextInterceptor;
669
731
  private debugLogger;
670
732
  constructor(eventBus: IEventBus);
@@ -673,6 +735,17 @@ declare class ServiceRegistry implements IServiceRegistry {
673
735
  serviceProxy(serviceIdentifier: string): IServiceProxy;
674
736
  register(serviceIdentifier: ServiceIdentifier, service: any): void;
675
737
  unRegister(serviceIdentifier: ServiceIdentifier): void;
738
+ /**
739
+ * Publishes the contract of every checked service registered so far to the platform's directory, so the
740
+ * platform checks requests to them; a contract the platform refuses fails the publication. The contract of
741
+ * a service registered later is published as it registers.
742
+ */
743
+ publishContracts(): Promise<void>;
744
+ /**
745
+ * The contracts of the checked services registered, by the CRI each is registered under.
746
+ */
747
+ registeredContracts(): ReadonlyMap<string, ServiceContract>;
748
+ private publishContract;
676
749
  registerContextInterceptor<T extends ServiceContext>(interceptor: ContextInterceptor<T> | null): void;
677
750
  }
678
751
  /**
@@ -740,8 +813,9 @@ declare class KinoticSingleton implements IKinotic {
740
813
  get eventBus(): IEventBus;
741
814
  set eventBus(eventBus: IEventBus);
742
815
  /**
743
- * Connects to a Kinotic server. Every option is optional: absent server fields and
744
- * credentials resolve from the environment — see {@link ConnectOptions}.
816
+ * Connects to a Kinotic server and publishes the contracts of the checked services registered so far.
817
+ * Every option is optional: absent server fields and credentials resolve from the environment — see
818
+ * {@link ConnectOptions}.
745
819
  * @param options overrides for the resolved connection, or nothing to resolve everything
746
820
  * @return Promise containing the result of the initial connection attempt
747
821
  */
@@ -820,6 +894,34 @@ declare function Context(value: Function, _context: ClassMethodDecoratorContext)
820
894
  */
821
895
  declare function receivesContext(serviceInstance: object, methodName: string): boolean;
822
896
  /**
897
+ * Declares the resource a service's functions act on, which puts the service's contract in the platform's
898
+ * directory when its instance registers, so every request to it is checked. The check of each function is
899
+ * derived by the platform from the function's name and parameters, as it is for the platform's own services:
900
+ * a `find`, `get`, `count`, `search` or `list` function needs `can_view`, a `save`, `update` or `set` function
901
+ * `can_edit`, a `delete` or `remove` function `can_delete`, and a `create` function `can_edit` on the parent,
902
+ * each on the object a parameter named `id` or `<type>Id` names, or on the parent when none does. A function
903
+ * the derivation cannot read declares its check with {@link AuthzCheck}.
904
+ * @param declaration the resource type, or the type with its parent, object, permission and roles
905
+ */
906
+ declare function AuthzResource(declaration: AuthzResourceDeclaration | string): (value: Function, _context: ClassDecoratorContext<any>) => void;
907
+ /**
908
+ * Declares the check of a function of an {@link AuthzResource} service: a permission of its own, such as
909
+ * `can_generate`, another object than the derived one, the permissions it implies, a consistent answer, or
910
+ * that any caller the zone admits may call it (`zoneOnly`).
911
+ * @param declaration what the derivation cannot read from the function's name and parameters
912
+ */
913
+ declare function AuthzCheck(declaration: AuthzCheckDeclaration): (value: Function, _context: ClassMethodDecoratorContext) => void;
914
+ /**
915
+ * The contract of a service instance registered under the identifier, or null for a class declaring no
916
+ * {@link AuthzResource}: its functions are the methods of its prototype chain, each with the names of the
917
+ * parameters a request carries, read from the method's source, less the context a {@link Context} method
918
+ * takes last. A runtime whose build renames parameters publishes names a check's template cannot reference,
919
+ * which the platform refuses at registration.
920
+ * @param serviceInstance the registered instance
921
+ * @param serviceIdentifier how it is addressed, which the contract names
922
+ */
923
+ declare function serviceContractOf(serviceInstance: object, serviceIdentifier: ServiceIdentifier): ServiceContract | null;
924
+ /**
823
925
  * Registers each instance of the decorated class with the Kinotic ServiceRegistry.
824
926
  * The service name defaults to the class name; {@link Version}, {@link Scope}, and {@link Zone}
825
927
  * on the same class refine the registration.
@@ -1423,7 +1525,7 @@ declare class ParticipantConstants {
1423
1525
  static readonly PARTICIPANT_TYPE_DELEGATE: string;
1424
1526
  /** A non-human caller with its own credential — a platform daemon or an external API client. */
1425
1527
  static readonly PARTICIPANT_TYPE_MACHINE: string;
1426
- /** The clientId TestSecurityService (clienttest profile) maps to the ANONYMOUS role in core package tests. */
1528
+ /** The clientId the test server's TestSecurityService maps to the ANONYMOUS role in core package tests. */
1427
1529
  static readonly CLI_PARTICIPANT_ID: string;
1428
1530
  }
1429
- export { validateZone, validateLabel, scopeOptionalMethodNames, receivesContext, isAdvertised, createCRI, buildServerUrl, buildBrokerUrl, Zone, WebSocketFactory, Version, TextEventFactory, Sort, SessionKeepAliveMode, SessionCredentialsResolver, ServiceRegistry, ServiceIdentifier, ServiceContext, ServerInfo, ScopeOptional, Scope, RpcError, ResolvedCredentials, Publish, ParticipantConstants, Participant, Pageable, Page, Order, OffsetPageable, NullHandling, KinoticSingleton, KinoticPlugin, Kinotic, JsonEventFactory, IterablePage, Identifiable, IWebSocket, IServiceRegistry, IServiceProxy, IParticipant, IKinotic, IEventFactory, IEventBus, IEvent, IEditableDataSource, IDataSource, ICrudServiceProxyFactory, ICrudServiceProxy, FunctionalIterablePage, EventConstants, EventBus, Event, EnvCredentialsResolver, Direction, DefaultCRI, DataSourceUtils, CursorPageable, CrudServiceProxyFactory, CrudServiceProxy, CredentialsResolver, ContextInterceptor, Context, ConnectedInfo, ConnectOptions, ChainedCredentialsResolver, CRI, BearerCredentialsResolver, BasicCredentialsResolver, AuthorizationException, AbstractIterablePage };
1531
+ export { validateZone, validateLabel, serviceContractOf, scopeOptionalMethodNames, receivesContext, isAdvertised, createCRI, buildServerUrl, buildBrokerUrl, Zone, WebSocketFactory, Version, TextEventFactory, Sort, SessionKeepAliveMode, SessionCredentialsResolver, ServiceRegistry, ServiceIdentifier, ServiceContract, ServiceContext, ServerInfo, ScopeOptional, Scope, RpcError, ResolvedCredentials, Publish, ParticipantConstants, Participant, Pageable, Page, Order, OffsetPageable, NullHandling, KinoticSingleton, KinoticPlugin, Kinotic, JsonEventFactory, IterablePage, Identifiable, IWebSocket, IServiceRegistry, IServiceProxy, IParticipant, IKinotic, IEventFactory, IEventBus, IEvent, IEditableDataSource, IDataSource, ICrudServiceProxyFactory, ICrudServiceProxy, FunctionalIterablePage, FunctionContract, EventConstants, EventBus, Event, EnvCredentialsResolver, Direction, DefaultCRI, DataSourceUtils, CursorPageable, CrudServiceProxyFactory, CrudServiceProxy, CredentialsResolver, ContextInterceptor, Context, ConnectedInfo, ConnectOptions, ChainedCredentialsResolver, CRI, BearerCredentialsResolver, BasicCredentialsResolver, AuthzRoleDeclaration, AuthzResourceDeclaration, AuthzResource, AuthzCheckDeclaration, AuthzCheck, AuthorizationException, AbstractIterablePage };
package/dist/index.js CHANGED
@@ -1064,6 +1064,8 @@ var versionRegistry = new WeakMap;
1064
1064
  var zonesRegistry = new WeakMap;
1065
1065
  var advertisedRegistry = new WeakMap;
1066
1066
  var contextMarkedFunctions = new WeakSet;
1067
+ var authzResourceRegistry = new WeakMap;
1068
+ var authzCheckRegistry = new WeakMap;
1067
1069
  function findInConstructorChain(registry, constructor) {
1068
1070
  let current = constructor;
1069
1071
  while (current) {
@@ -1154,6 +1156,101 @@ function resolveEffectiveZone(constructor) {
1154
1156
  }
1155
1157
  return effectiveZone;
1156
1158
  }
1159
+ function AuthzResource(declaration) {
1160
+ const resource = typeof declaration === "string" ? { value: declaration } : declaration;
1161
+ if (!resource.value) {
1162
+ throw new Error("AuthzResource must name the resource type");
1163
+ }
1164
+ return function(value, _context) {
1165
+ authzResourceRegistry.set(value, resource);
1166
+ };
1167
+ }
1168
+ function AuthzCheck(declaration) {
1169
+ return function(value, _context) {
1170
+ authzCheckRegistry.set(value, declaration);
1171
+ };
1172
+ }
1173
+ function serviceContractOf(serviceInstance, serviceIdentifier) {
1174
+ const resource = findInConstructorChain(authzResourceRegistry, serviceInstance.constructor);
1175
+ let ret = null;
1176
+ if (resource) {
1177
+ if (!serviceIdentifier.zone) {
1178
+ throw new Error(`${serviceIdentifier.qualifiedName()} declares a resource but no zone; a checked service is addressed in a zone`);
1179
+ }
1180
+ const functions = [];
1181
+ const seen = new Set;
1182
+ let proto = Object.getPrototypeOf(serviceInstance);
1183
+ while (proto && proto !== Object.prototype) {
1184
+ for (const key of Object.getOwnPropertyNames(proto)) {
1185
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1186
+ if (typeof descriptor?.value === "function" && key !== "constructor" && !seen.has(key)) {
1187
+ seen.add(key);
1188
+ const method = descriptor.value;
1189
+ const parameters = parameterNames(method);
1190
+ if (contextMarkedFunctions.has(method)) {
1191
+ parameters.pop();
1192
+ }
1193
+ functions.push({ name: key, parameters, check: authzCheckRegistry.get(method) ?? null });
1194
+ }
1195
+ }
1196
+ proto = Object.getPrototypeOf(proto);
1197
+ }
1198
+ ret = {
1199
+ namespace: serviceIdentifier.namespace,
1200
+ name: serviceIdentifier.name,
1201
+ version: serviceIdentifier.version ?? null,
1202
+ zone: serviceIdentifier.zone,
1203
+ resource,
1204
+ functions
1205
+ };
1206
+ }
1207
+ return ret;
1208
+ }
1209
+ function parameterNames(method) {
1210
+ const source = method.toString().replace(/\/\*[\s\S]*?\*\//g, "");
1211
+ let depth = 0;
1212
+ let start = -1;
1213
+ let end = -1;
1214
+ for (let i = 0;i < source.length && end < 0; i++) {
1215
+ const c = source[i];
1216
+ if (c === "(") {
1217
+ if (depth === 0 && start < 0) {
1218
+ start = i + 1;
1219
+ }
1220
+ depth++;
1221
+ } else if (c === ")") {
1222
+ depth--;
1223
+ if (depth === 0 && start >= 0) {
1224
+ end = i;
1225
+ }
1226
+ }
1227
+ }
1228
+ const ret = [];
1229
+ if (start >= 0 && end >= 0) {
1230
+ let nested = 0;
1231
+ let current = "";
1232
+ const parts = [];
1233
+ for (const c of source.substring(start, end)) {
1234
+ if ("([{".includes(c)) {
1235
+ nested++;
1236
+ } else if (")]}".includes(c)) {
1237
+ nested--;
1238
+ }
1239
+ if (c === "," && nested === 0) {
1240
+ parts.push(current);
1241
+ current = "";
1242
+ } else {
1243
+ current += c;
1244
+ }
1245
+ }
1246
+ parts.push(current);
1247
+ parts.map((part) => (part.split("=")[0] ?? "").trim()).filter((part) => part.length > 0).forEach((part, index) => {
1248
+ const name = part.replace(/^\.\.\./, "");
1249
+ ret.push(/^[A-Za-z_$][\w$]*$/.test(name) ? name : `arg${index}`);
1250
+ });
1251
+ }
1252
+ return ret;
1253
+ }
1157
1254
  function Publish(namespace, name, advertise = false) {
1158
1255
  return function(value, _context) {
1159
1256
  advertisedRegistry.set(value, advertise);
@@ -1181,7 +1278,7 @@ import opentelemetry, { context as context2, propagation as propagation2, trace,
1181
1278
  // packages/core/package.json
1182
1279
  var package_default = {
1183
1280
  name: "@kinotic-ai/core",
1184
- version: "5.0.0-beta.17",
1281
+ version: "5.0.0-beta.19",
1185
1282
  type: "module",
1186
1283
  files: [
1187
1284
  "dist"
@@ -1240,8 +1337,8 @@ var package_default = {
1240
1337
  "@vitest/coverage-v8": "^4.1.4",
1241
1338
  "@vitest/runner": "^4.1.4",
1242
1339
  "@vitest/ui": "^4.1.4",
1243
- allure: "^3.14.3",
1244
- "allure-vitest": "^3.10.2",
1340
+ allure: "^3.19.1",
1341
+ "allure-vitest": "^3.13.0",
1245
1342
  dotenv: "^17.4.1",
1246
1343
  "properties-file": "^4.0.0",
1247
1344
  testcontainers: "^11.14.0",
@@ -1643,10 +1740,13 @@ class TextEventFactory {
1643
1740
  return event;
1644
1741
  }
1645
1742
  }
1743
+ var SERVICE_CONTRACT_SERVICE = "app-api~org.kinotic.app.api.services.ServiceContractService";
1744
+ var APPLICATION_ZONE = /^app\.[^.]+\.([^.]+)(\.|$)/;
1646
1745
 
1647
1746
  class ServiceRegistry {
1648
1747
  _eventBus;
1649
1748
  supervisors = new Map;
1749
+ contracts = new Map;
1650
1750
  contextInterceptor = null;
1651
1751
  debugLogger = debug3("kinotic:serviceRegistry");
1652
1752
  constructor(eventBus) {
@@ -1668,9 +1768,16 @@ class ServiceRegistry {
1668
1768
  const criString = serviceIdentifier.cri().raw();
1669
1769
  if (!this.supervisors.has(criString)) {
1670
1770
  this.debugLogger(`Registering service for CRI: ${criString}`);
1771
+ const contract = serviceContractOf(service, serviceIdentifier);
1671
1772
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1672
1773
  this.supervisors.set(criString, supervisor);
1673
1774
  supervisor.start();
1775
+ if (contract) {
1776
+ this.contracts.set(criString, contract);
1777
+ if (this.eventBus.isConnected()) {
1778
+ this.publishContract(contract).catch((error) => this.debugLogger(`Failed to publish the contract of ${criString}`, error));
1779
+ }
1780
+ }
1674
1781
  }
1675
1782
  }
1676
1783
  unRegister(serviceIdentifier) {
@@ -1680,6 +1787,22 @@ class ServiceRegistry {
1680
1787
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1681
1788
  supervisor.stop();
1682
1789
  this.supervisors.delete(criString);
1790
+ this.contracts.delete(criString);
1791
+ }
1792
+ }
1793
+ async publishContracts() {
1794
+ for (const contract of this.contracts.values()) {
1795
+ await this.publishContract(contract);
1796
+ }
1797
+ }
1798
+ registeredContracts() {
1799
+ return this.contracts;
1800
+ }
1801
+ async publishContract(contract) {
1802
+ const application = APPLICATION_ZONE.exec(contract.zone);
1803
+ if (application) {
1804
+ this.debugLogger(`Publishing the contract of ${contract.zone}~${contract.namespace}.${contract.name}`);
1805
+ await this.serviceProxy(SERVICE_CONTRACT_SERVICE).invoke("register", [application[1], contract]);
1683
1806
  }
1684
1807
  }
1685
1808
  registerContextInterceptor(interceptor) {
@@ -1773,8 +1896,10 @@ class KinoticSingleton {
1773
1896
  this._eventBus = eventBus;
1774
1897
  this.serviceRegistry.eventBus = eventBus;
1775
1898
  }
1776
- connect(options) {
1777
- return this._eventBus.connect(Util.resolveConnectOptions(options));
1899
+ async connect(options) {
1900
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
1901
+ await this.serviceRegistry.publishContracts();
1902
+ return ret;
1778
1903
  }
1779
1904
  disconnect(force) {
1780
1905
  return this._eventBus.disconnect(force);
@@ -2043,6 +2168,7 @@ class ParticipantConstants {
2043
2168
  export {
2044
2169
  validateZone,
2045
2170
  validateLabel,
2171
+ serviceContractOf,
2046
2172
  scopeOptionalMethodNames,
2047
2173
  receivesContext,
2048
2174
  isAdvertised,
@@ -2086,6 +2212,8 @@ export {
2086
2212
  ChainedCredentialsResolver,
2087
2213
  BearerCredentialsResolver,
2088
2214
  BasicCredentialsResolver,
2215
+ AuthzResource,
2216
+ AuthzCheck,
2089
2217
  AuthorizationException,
2090
2218
  AbstractIterablePage
2091
2219
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinotic-ai/core",
3
- "version": "5.0.0-beta.17",
3
+ "version": "5.0.0-beta.19",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"
@@ -59,8 +59,8 @@
59
59
  "@vitest/coverage-v8": "^4.1.4",
60
60
  "@vitest/runner": "^4.1.4",
61
61
  "@vitest/ui": "^4.1.4",
62
- "allure": "^3.14.3",
63
- "allure-vitest": "^3.10.2",
62
+ "allure": "^3.19.1",
63
+ "allure-vitest": "^3.13.0",
64
64
  "dotenv": "^17.4.1",
65
65
  "properties-file": "^4.0.0",
66
66
  "testcontainers": "^11.14.0",