@coopenomics/extension-sdk 2026.12.1 → 2026.12.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.
@@ -14,6 +14,10 @@
14
14
  * (`events.chain`, `events.core` в `coopenomics.ports`)
15
15
  * TIMEZONE — часовой пояс кооператива, как у ядра узла
16
16
  * (по умолчанию Europe/Moscow)
17
+ * APP_PACKAGE_ID / APP_PORTS_URL / APP_PORTS_TOKEN / APP_PORTS_INBOUND_TOKEN —
18
+ * порты приложений (01.12.2026): имя пакета, вход
19
+ * посредника оркестратора, исходящий и входящий токены
20
+ * APP_SECRETS_KEY — ключ шифрования секретных настроек приложения
17
21
  *
18
22
  * Расширение читает их через `loadExtensionConfig()` на bootstrap; падает
19
23
  * сразу же если обязательное поле не задано — fail-fast, чтобы orchestrator
@@ -42,6 +46,16 @@ export interface ExtensionConfig {
42
46
  eventsStreamPrefix: string;
43
47
  /** Темы шины, заявленные приложением (`EVENTS_TOPICS`, через запятую). */
44
48
  eventsTopics: string[];
49
+ /** Имя пакета приложения (`APP_PACKAGE_ID`), например `@voskhod/dadata`. */
50
+ packageId?: string;
51
+ /** Вход посредника портов приложений (`APP_PORTS_URL`). */
52
+ appPortsUrl?: string;
53
+ /** Токен вызова портов других приложений (`APP_PORTS_TOKEN`). */
54
+ appPortsToken?: string;
55
+ /** Токен, которым посредник входит в это приложение (`APP_PORTS_INBOUND_TOKEN`). */
56
+ appPortsInboundToken?: string;
57
+ /** Ключ шифрования секретных настроек, base64 32 байт (`APP_SECRETS_KEY`). */
58
+ appSecretsKey?: string;
45
59
  }
46
60
  export declare class ExtensionConfigError extends Error {
47
61
  constructor(message: string);
@@ -36,5 +36,10 @@ function loadExtensionConfig(env = process.env) {
36
36
  eventsRedisUrl: env.EVENTS_REDIS_URL || undefined,
37
37
  eventsStreamPrefix: env.EVENTS_STREAM_PREFIX || '',
38
38
  eventsTopics: (env.EVENTS_TOPICS || '').split(',').map((topic) => topic.trim()).filter(Boolean),
39
+ packageId: env.APP_PACKAGE_ID || undefined,
40
+ appPortsUrl: env.APP_PORTS_URL || undefined,
41
+ appPortsToken: env.APP_PORTS_TOKEN || undefined,
42
+ appPortsInboundToken: env.APP_PORTS_INBOUND_TOKEN || undefined,
43
+ appSecretsKey: env.APP_SECRETS_KEY || undefined,
39
44
  };
40
45
  }
package/dist/index.d.ts CHANGED
@@ -36,3 +36,6 @@ export { ExtensionPortsModule, LIVE_FEED_PORT, REMOTE_PORT_METHODS, REMOTE_PORT_
36
36
  export { runAppMigrations, applyAppMigrations, readAppMigrations, migrationChecksum, AppMigrationError, type AppMigrationsOptions, type AppMigrationFile, type MigrationConnection, } from './database/app-migrations';
37
37
  export { BusReader, MemoryCursorStore, BUS_GAP_EVENT, parseBusEntry, type BusEvent, type BusGap, type BusCursorStore, type BusRedis, type BusReaderOptions, type StreamEntry, } from './events/bus-reader';
38
38
  export { ExtensionEventsModule, ExtensionEventsService, PostgresCursorStore, type ExtensionEventsOptions, } from './events/extension-events.module';
39
+ export { AppPortsClient, AppPortError, appPort, type AppPortsClientOptions } from './ports/app-ports.client';
40
+ export { AppPortsProviderModule, AppPortsProviderController, AppPortRefusal, type AppPortProvision, type AppPortsProviderOptions, } from './ports/app-ports.provider';
41
+ export { AppSecrets, AppSecretsError } from './secrets/app-secrets';
package/dist/index.js CHANGED
@@ -23,7 +23,7 @@
23
23
  * и Architecture v3 в blago.
24
24
  */
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.PostgresCursorStore = exports.ExtensionEventsService = exports.ExtensionEventsModule = exports.parseBusEntry = exports.BUS_GAP_EVENT = exports.MemoryCursorStore = exports.BusReader = exports.AppMigrationError = exports.migrationChecksum = exports.readAppMigrations = exports.applyAppMigrations = exports.runAppMigrations = exports.remotePort = exports.REMOTE_PORT_TOKENS = exports.REMOTE_PORT_METHODS = exports.LIVE_FEED_PORT = exports.ExtensionPortsModule = exports.CorePortError = exports.CorePortsClient = exports.ExtensionAccessGuard = exports.ExtensionConfigError = exports.loadExtensionConfig = exports.HealthController = exports.SharedAccount = exports.SharedCooperative = exports.SharedCooperator = exports.ExtensionJwtAuthGuard = exports.ExtensionJwtStrategy = exports.ExtensionAuthModule = exports.ExtensionFederationModule = void 0;
26
+ exports.AppSecretsError = exports.AppSecrets = exports.AppPortRefusal = exports.AppPortsProviderController = exports.AppPortsProviderModule = exports.appPort = exports.AppPortError = exports.AppPortsClient = exports.PostgresCursorStore = exports.ExtensionEventsService = exports.ExtensionEventsModule = exports.parseBusEntry = exports.BUS_GAP_EVENT = exports.MemoryCursorStore = exports.BusReader = exports.AppMigrationError = exports.migrationChecksum = exports.readAppMigrations = exports.applyAppMigrations = exports.runAppMigrations = exports.remotePort = exports.REMOTE_PORT_TOKENS = exports.REMOTE_PORT_METHODS = exports.LIVE_FEED_PORT = exports.ExtensionPortsModule = exports.CorePortError = exports.CorePortsClient = exports.ExtensionAccessGuard = exports.ExtensionConfigError = exports.loadExtensionConfig = exports.HealthController = exports.SharedAccount = exports.SharedCooperative = exports.SharedCooperator = exports.ExtensionJwtAuthGuard = exports.ExtensionJwtStrategy = exports.ExtensionAuthModule = exports.ExtensionFederationModule = void 0;
27
27
  var federation_module_1 = require("./federation/federation.module");
28
28
  Object.defineProperty(exports, "ExtensionFederationModule", { enumerable: true, get: function () { return federation_module_1.ExtensionFederationModule; } });
29
29
  var extension_auth_module_1 = require("./auth/extension-auth.module");
@@ -69,3 +69,15 @@ var extension_events_module_1 = require("./events/extension-events.module");
69
69
  Object.defineProperty(exports, "ExtensionEventsModule", { enumerable: true, get: function () { return extension_events_module_1.ExtensionEventsModule; } });
70
70
  Object.defineProperty(exports, "ExtensionEventsService", { enumerable: true, get: function () { return extension_events_module_1.ExtensionEventsService; } });
71
71
  Object.defineProperty(exports, "PostgresCursorStore", { enumerable: true, get: function () { return extension_events_module_1.PostgresCursorStore; } });
72
+ // Порты приложений и секретные настройки (01.12.2026).
73
+ var app_ports_client_1 = require("./ports/app-ports.client");
74
+ Object.defineProperty(exports, "AppPortsClient", { enumerable: true, get: function () { return app_ports_client_1.AppPortsClient; } });
75
+ Object.defineProperty(exports, "AppPortError", { enumerable: true, get: function () { return app_ports_client_1.AppPortError; } });
76
+ Object.defineProperty(exports, "appPort", { enumerable: true, get: function () { return app_ports_client_1.appPort; } });
77
+ var app_ports_provider_1 = require("./ports/app-ports.provider");
78
+ Object.defineProperty(exports, "AppPortsProviderModule", { enumerable: true, get: function () { return app_ports_provider_1.AppPortsProviderModule; } });
79
+ Object.defineProperty(exports, "AppPortsProviderController", { enumerable: true, get: function () { return app_ports_provider_1.AppPortsProviderController; } });
80
+ Object.defineProperty(exports, "AppPortRefusal", { enumerable: true, get: function () { return app_ports_provider_1.AppPortRefusal; } });
81
+ var app_secrets_1 = require("./secrets/app-secrets");
82
+ Object.defineProperty(exports, "AppSecrets", { enumerable: true, get: function () { return app_secrets_1.AppSecrets; } });
83
+ Object.defineProperty(exports, "AppSecretsError", { enumerable: true, get: function () { return app_secrets_1.AppSecretsError; } });
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Клиент портов приложений (01.12.2026): приложение вызывает порт другого
3
+ * приложения через посредника оркестратора (`POST /v1/app-ports/:port/:method`
4
+ * на входе core-ports). Формат — как у портов ядра: тело `{ args }`, ответ
5
+ * `{ result }`, отказ `{ code, message, params }`.
6
+ *
7
+ * Порт должен стоять в манифесте приложения (`coopenomics.uses`), иначе
8
+ * посредник отказывает с кодом `APP_PORT_NOT_DECLARED`. Поставщика нет или
9
+ * он выключен — `APP_PORT_NOT_CONNECTED`: приложение работает без этой связи.
10
+ *
11
+ * ```ts
12
+ * const client = new AppPortsClient({ baseUrl: cfg.appPortsUrl, token: cfg.appPortsToken, packageId: cfg.packageId });
13
+ * const rooms = appPort<IMatrixRoomMessagingPort>(client, 'matrix-room-messaging', ['send', 'ensureRoom']);
14
+ * await rooms.send(roomId, text);
15
+ * ```
16
+ */
17
+ /** Отказ порта приложения: статус и код посредника либо поставщика. */
18
+ export declare class AppPortError extends Error {
19
+ /** HTTP-статус; 0 — посредник не ответил. */
20
+ readonly status: number;
21
+ /** Код отказа (`APP_PORT_NOT_CONNECTED`, `APP_PORT_NOT_DECLARED`, код поставщика). */
22
+ readonly code: string;
23
+ readonly params: Record<string, unknown>;
24
+ constructor(
25
+ /** HTTP-статус; 0 — посредник не ответил. */
26
+ status: number,
27
+ /** Код отказа (`APP_PORT_NOT_CONNECTED`, `APP_PORT_NOT_DECLARED`, код поставщика). */
28
+ code: string, message: string, params?: Record<string, unknown>);
29
+ /** Поставщика порта на узле нет или он выключен — связь недоступна, это не сбой. */
30
+ get notConnected(): boolean;
31
+ }
32
+ export interface AppPortsClientOptions {
33
+ /** Вход посредника (`APP_PORTS_URL`), например `http://core-ports:8090`. */
34
+ baseUrl: string;
35
+ /** Исходящий токен приложения (`APP_PORTS_TOKEN`). */
36
+ token: string;
37
+ /** Имя пакета приложения (`APP_PACKAGE_ID`). */
38
+ packageId: string;
39
+ /** Предел ожидания вызова, мс; по умолчанию 30 с. */
40
+ timeoutMs?: number;
41
+ /** Подмена fetch в тестах. */
42
+ fetchFn?: typeof fetch;
43
+ }
44
+ export declare class AppPortsClient {
45
+ private readonly options;
46
+ private readonly baseUrl;
47
+ private readonly timeoutMs;
48
+ private readonly fetchFn;
49
+ constructor(options: AppPortsClientOptions);
50
+ /**
51
+ * Вызвать метод порта другого приложения. Повторов нет: метод может менять
52
+ * состояние поставщика, а повтор хуже отказа.
53
+ *
54
+ * @throws AppPortError
55
+ */
56
+ call<T = unknown>(port: string, method: string, args: unknown[]): Promise<T>;
57
+ }
58
+ /**
59
+ * Объект порта другого приложения: каждый метод из списка — вызов через
60
+ * посредника. Список методов явный: Nest и `JSON.stringify` спрашивают у
61
+ * объекта служебные свойства (`then`, `toJSON`), и сетевой вызов на них
62
+ * ронял бы приложение.
63
+ */
64
+ export declare function appPort<T extends object>(client: AppPortsClient, port: string, methods: readonly string[]): T;
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ /**
3
+ * Клиент портов приложений (01.12.2026): приложение вызывает порт другого
4
+ * приложения через посредника оркестратора (`POST /v1/app-ports/:port/:method`
5
+ * на входе core-ports). Формат — как у портов ядра: тело `{ args }`, ответ
6
+ * `{ result }`, отказ `{ code, message, params }`.
7
+ *
8
+ * Порт должен стоять в манифесте приложения (`coopenomics.uses`), иначе
9
+ * посредник отказывает с кодом `APP_PORT_NOT_DECLARED`. Поставщика нет или
10
+ * он выключен — `APP_PORT_NOT_CONNECTED`: приложение работает без этой связи.
11
+ *
12
+ * ```ts
13
+ * const client = new AppPortsClient({ baseUrl: cfg.appPortsUrl, token: cfg.appPortsToken, packageId: cfg.packageId });
14
+ * const rooms = appPort<IMatrixRoomMessagingPort>(client, 'matrix-room-messaging', ['send', 'ensureRoom']);
15
+ * await rooms.send(roomId, text);
16
+ * ```
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.AppPortsClient = exports.AppPortError = void 0;
20
+ exports.appPort = appPort;
21
+ /** Отказ порта приложения: статус и код посредника либо поставщика. */
22
+ class AppPortError extends Error {
23
+ status;
24
+ code;
25
+ params;
26
+ constructor(
27
+ /** HTTP-статус; 0 — посредник не ответил. */
28
+ status,
29
+ /** Код отказа (`APP_PORT_NOT_CONNECTED`, `APP_PORT_NOT_DECLARED`, код поставщика). */
30
+ code, message, params = {}) {
31
+ super(message);
32
+ this.status = status;
33
+ this.code = code;
34
+ this.params = params;
35
+ this.name = 'AppPortError';
36
+ }
37
+ /** Поставщика порта на узле нет или он выключен — связь недоступна, это не сбой. */
38
+ get notConnected() {
39
+ return this.code === 'APP_PORT_NOT_CONNECTED';
40
+ }
41
+ }
42
+ exports.AppPortError = AppPortError;
43
+ class AppPortsClient {
44
+ options;
45
+ baseUrl;
46
+ timeoutMs;
47
+ fetchFn;
48
+ constructor(options) {
49
+ this.options = options;
50
+ this.baseUrl = options.baseUrl.replace(/\/+$/, '');
51
+ this.timeoutMs = options.timeoutMs ?? 30_000;
52
+ this.fetchFn = options.fetchFn ?? fetch;
53
+ }
54
+ /**
55
+ * Вызвать метод порта другого приложения. Повторов нет: метод может менять
56
+ * состояние поставщика, а повтор хуже отказа.
57
+ *
58
+ * @throws AppPortError
59
+ */
60
+ async call(port, method, args) {
61
+ let res;
62
+ try {
63
+ res = await this.fetchFn(`${this.baseUrl}/v1/app-ports/${port}/${method}`, {
64
+ method: 'POST',
65
+ headers: {
66
+ 'content-type': 'application/json',
67
+ authorization: `Bearer ${this.options.token}`,
68
+ 'x-app-package': this.options.packageId,
69
+ },
70
+ body: JSON.stringify({ args }),
71
+ signal: AbortSignal.timeout(this.timeoutMs),
72
+ });
73
+ }
74
+ catch (e) {
75
+ throw new AppPortError(0, 'APP_PORTS_UNREACHABLE', `посредник портов не ответил на ${port}.${method}: ${e instanceof Error ? e.message : String(e)}`);
76
+ }
77
+ const text = await res.text();
78
+ let body = null;
79
+ try {
80
+ body = text ? JSON.parse(text) : null;
81
+ }
82
+ catch {
83
+ body = null;
84
+ }
85
+ if (!res.ok) {
86
+ throw new AppPortError(res.status, typeof body?.code === 'string' ? body.code : 'APP_PORT_FAILED', typeof body?.message === 'string' ? body.message : `посредник ответил ${res.status} на ${port}.${method}`, body?.params && typeof body.params === 'object' ? body.params : {});
87
+ }
88
+ return (body?.result ?? null);
89
+ }
90
+ }
91
+ exports.AppPortsClient = AppPortsClient;
92
+ /**
93
+ * Объект порта другого приложения: каждый метод из списка — вызов через
94
+ * посредника. Список методов явный: Nest и `JSON.stringify` спрашивают у
95
+ * объекта служебные свойства (`then`, `toJSON`), и сетевой вызов на них
96
+ * ронял бы приложение.
97
+ */
98
+ function appPort(client, port, methods) {
99
+ const target = {};
100
+ for (const method of methods) {
101
+ target[method] = (...args) => client.call(port, method, args);
102
+ }
103
+ return Object.freeze(target);
104
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Порты, которые приложение даёт ядру и другим приложениям (01.12.2026).
3
+ *
4
+ * Посредник оркестратора вызывает приложение-поставщика по адресу
5
+ * `POST /app-ports/:port/:method` с входящим токеном приложения
6
+ * (`APP_PORTS_INBOUND_TOKEN`). Модуль сверяет токен, находит реализацию порта
7
+ * и вызывает только перечисленные методы: имя метода берётся из адреса, и
8
+ * без списка вызов дотянулся бы до любого метода объекта.
9
+ *
10
+ * Порт объявляется и в манифесте пакета (`coopenomics.provides`): без этого
11
+ * посредник не знает, что приложение — поставщик.
12
+ *
13
+ * ```ts
14
+ * AppPortsProviderModule.forRoot({
15
+ * inboundToken: cfg.appPortsInboundToken,
16
+ * ports: [{ port: 'organization-lookup', methods: ['countries', 'findByInn'], provider: LookupService }],
17
+ * })
18
+ * ```
19
+ */
20
+ import { type DynamicModule, type Type } from '@nestjs/common';
21
+ import { ModuleRef } from '@nestjs/core';
22
+ export interface AppPortProvision {
23
+ /** Имя порта, как в манифесте (`coopenomics.provides`). */
24
+ port: string;
25
+ /** Методы, открытые посреднику. */
26
+ methods: readonly string[];
27
+ /**
28
+ * Класс реализации. Он остаётся провайдером своего модуля приложения со
29
+ * всеми зависимостями; модуль находит его по классу во всём приложении.
30
+ */
31
+ provider: Type<object>;
32
+ }
33
+ export interface AppPortsProviderOptions {
34
+ /** Входящий токен приложения (`APP_PORTS_INBOUND_TOKEN`); не задан — порты закрыты. */
35
+ inboundToken?: string;
36
+ ports: AppPortProvision[];
37
+ }
38
+ /** Отказ реализации порта, который посредник передаст вызывающему с кодом. */
39
+ export declare class AppPortRefusal extends Error {
40
+ readonly status: number;
41
+ readonly code: string;
42
+ readonly params: Record<string, unknown>;
43
+ constructor(status: number, code: string, message: string, params?: Record<string, unknown>);
44
+ }
45
+ export declare class AppPortsProviderController {
46
+ private readonly options;
47
+ private readonly moduleRef;
48
+ constructor(options: AppPortsProviderOptions, moduleRef: ModuleRef);
49
+ call(port: string, method: string, body: {
50
+ args?: unknown;
51
+ }, authorization?: string): Promise<{
52
+ result: unknown;
53
+ }>;
54
+ }
55
+ export declare class AppPortsProviderModule {
56
+ static forRoot(options: AppPortsProviderOptions): DynamicModule;
57
+ }
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var AppPortsProviderModule_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.AppPortsProviderModule = exports.AppPortsProviderController = exports.AppPortRefusal = void 0;
17
+ /**
18
+ * Порты, которые приложение даёт ядру и другим приложениям (01.12.2026).
19
+ *
20
+ * Посредник оркестратора вызывает приложение-поставщика по адресу
21
+ * `POST /app-ports/:port/:method` с входящим токеном приложения
22
+ * (`APP_PORTS_INBOUND_TOKEN`). Модуль сверяет токен, находит реализацию порта
23
+ * и вызывает только перечисленные методы: имя метода берётся из адреса, и
24
+ * без списка вызов дотянулся бы до любого метода объекта.
25
+ *
26
+ * Порт объявляется и в манифесте пакета (`coopenomics.provides`): без этого
27
+ * посредник не знает, что приложение — поставщик.
28
+ *
29
+ * ```ts
30
+ * AppPortsProviderModule.forRoot({
31
+ * inboundToken: cfg.appPortsInboundToken,
32
+ * ports: [{ port: 'organization-lookup', methods: ['countries', 'findByInn'], provider: LookupService }],
33
+ * })
34
+ * ```
35
+ */
36
+ const common_1 = require("@nestjs/common");
37
+ const core_1 = require("@nestjs/core");
38
+ const node_crypto_1 = require("node:crypto");
39
+ /** Отказ реализации порта, который посредник передаст вызывающему с кодом. */
40
+ class AppPortRefusal extends Error {
41
+ status;
42
+ code;
43
+ params;
44
+ constructor(status, code, message, params = {}) {
45
+ super(message);
46
+ this.status = status;
47
+ this.code = code;
48
+ this.params = params;
49
+ this.name = 'AppPortRefusal';
50
+ }
51
+ }
52
+ exports.AppPortRefusal = AppPortRefusal;
53
+ const APP_PORTS_PROVIDER_OPTIONS = Symbol('ExtensionSdk.AppPortsProviderOptions');
54
+ function sameToken(presented, expected) {
55
+ const a = Buffer.from(presented);
56
+ const b = Buffer.from(expected);
57
+ return a.length === b.length && (0, node_crypto_1.timingSafeEqual)(a, b);
58
+ }
59
+ let AppPortsProviderController = class AppPortsProviderController {
60
+ options;
61
+ moduleRef;
62
+ constructor(options, moduleRef) {
63
+ this.options = options;
64
+ this.moduleRef = moduleRef;
65
+ }
66
+ async call(port, method, body, authorization) {
67
+ const expected = this.options.inboundToken;
68
+ const presented = (authorization ?? '').replace(/^Bearer\s+/i, '');
69
+ if (!expected || !presented || !sameToken(presented, expected)) {
70
+ throw refusal(new AppPortRefusal(401, 'APP_PORT_UNAUTHORIZED', 'вызов порта не от посредника узла'));
71
+ }
72
+ const provision = this.options.ports.find((p) => p.port === port);
73
+ if (!provision || !provision.methods.includes(method)) {
74
+ throw refusal(new AppPortRefusal(404, 'APP_PORT_METHOD_UNKNOWN', `приложение не даёт ${port}.${method}`));
75
+ }
76
+ const impl = this.moduleRef.get(provision.provider, { strict: false });
77
+ const fn = impl[method];
78
+ if (typeof fn !== 'function') {
79
+ throw refusal(new AppPortRefusal(404, 'APP_PORT_METHOD_UNKNOWN', `приложение не даёт ${port}.${method}`));
80
+ }
81
+ const args = Array.isArray(body?.args) ? body.args : [];
82
+ try {
83
+ return { result: (await fn.apply(impl, args)) ?? null };
84
+ }
85
+ catch (e) {
86
+ throw refusal(e);
87
+ }
88
+ }
89
+ };
90
+ exports.AppPortsProviderController = AppPortsProviderController;
91
+ __decorate([
92
+ (0, common_1.Post)(':port/:method'),
93
+ (0, common_1.HttpCode)(200),
94
+ __param(0, (0, common_1.Param)('port')),
95
+ __param(1, (0, common_1.Param)('method')),
96
+ __param(2, (0, common_1.Body)()),
97
+ __param(3, (0, common_1.Headers)('authorization')),
98
+ __metadata("design:type", Function),
99
+ __metadata("design:paramtypes", [String, String, Object, String]),
100
+ __metadata("design:returntype", Promise)
101
+ ], AppPortsProviderController.prototype, "call", null);
102
+ exports.AppPortsProviderController = AppPortsProviderController = __decorate([
103
+ (0, common_1.Controller)('app-ports'),
104
+ __param(0, (0, common_1.Inject)(APP_PORTS_PROVIDER_OPTIONS)),
105
+ __param(1, (0, common_1.Inject)(core_1.ModuleRef)),
106
+ __metadata("design:paramtypes", [Object, core_1.ModuleRef])
107
+ ], AppPortsProviderController);
108
+ /** Отказ — телом `{ code, message, params }`, как отказы портов ядра. */
109
+ function refusal(e) {
110
+ if (e instanceof AppPortRefusal)
111
+ return new common_1.HttpException({ code: e.code, message: e.message, params: e.params }, e.status);
112
+ const message = e instanceof Error ? e.message : String(e);
113
+ return new common_1.HttpException({ code: 'APP_PORT_PROVIDER_FAILED', message, params: {} }, 500);
114
+ }
115
+ let AppPortsProviderModule = AppPortsProviderModule_1 = class AppPortsProviderModule {
116
+ static forRoot(options) {
117
+ const providers = [{ provide: APP_PORTS_PROVIDER_OPTIONS, useValue: options }];
118
+ return { module: AppPortsProviderModule_1, controllers: [AppPortsProviderController], providers };
119
+ }
120
+ };
121
+ exports.AppPortsProviderModule = AppPortsProviderModule;
122
+ exports.AppPortsProviderModule = AppPortsProviderModule = AppPortsProviderModule_1 = __decorate([
123
+ (0, common_1.Module)({})
124
+ ], AppPortsProviderModule);
@@ -0,0 +1,17 @@
1
+ export declare class AppSecretsError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ export declare class AppSecrets {
5
+ private readonly key;
6
+ constructor(keyBase64: string | undefined);
7
+ /** Зашифровать значение для записи в базу: `v1:<iv>:<tag>:<шифротекст>` в base64. */
8
+ seal(plain: string): string;
9
+ /**
10
+ * Расшифровать значение из базы.
11
+ *
12
+ * @throws AppSecretsError — чужой формат, другой ключ или подменённый шифротекст.
13
+ */
14
+ open(sealed: string): string;
15
+ /** Маска для страницы настроек: последние четыре знака; короткое значение — только «задан». */
16
+ static mask(plain: string | null | undefined): string | null;
17
+ }
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AppSecrets = exports.AppSecretsError = void 0;
4
+ /**
5
+ * Секретные настройки приложения (01.12.2026): ключи внешних сервисов
6
+ * (DaData, банк, платёжный шлюз) приложение хранит в своей базе только
7
+ * шифротекстом.
8
+ *
9
+ * Ключ шифрования (`APP_SECRETS_KEY`, 32 байта в base64) выдаёт оркестратор
10
+ * при установке: он выведен из секрета узла и имени пакета, у каждого
11
+ * приложения свой и не меняется после переустановки. Шифр — AES-256-GCM:
12
+ * подмена шифротекста в базе обнаруживается при расшифровке.
13
+ *
14
+ * Страница настроек значение секрета обратно не показывает — только
15
+ * `mask()`: «задан, оканчивается на …1234».
16
+ *
17
+ * ```ts
18
+ * const secrets = new AppSecrets(cfg.appSecretsKey);
19
+ * row.api_key = secrets.seal(input.apiKey); // в базу
20
+ * const apiKey = secrets.open(row.api_key); // для вызова сервиса
21
+ * ```
22
+ */
23
+ const node_crypto_1 = require("node:crypto");
24
+ /** Метка формата шифротекста: при смене шифра старые значения читаются по метке. */
25
+ const FORMAT = 'v1';
26
+ class AppSecretsError extends Error {
27
+ constructor(message) {
28
+ super(message);
29
+ this.name = 'AppSecretsError';
30
+ }
31
+ }
32
+ exports.AppSecretsError = AppSecretsError;
33
+ class AppSecrets {
34
+ key;
35
+ constructor(keyBase64) {
36
+ if (!keyBase64)
37
+ throw new AppSecretsError('ключ секретов приложения не задан (APP_SECRETS_KEY): узел не выдал его при установке');
38
+ this.key = Buffer.from(keyBase64, 'base64');
39
+ if (this.key.length !== 32)
40
+ throw new AppSecretsError('ключ секретов приложения должен быть 32 байта');
41
+ }
42
+ /** Зашифровать значение для записи в базу: `v1:<iv>:<tag>:<шифротекст>` в base64. */
43
+ seal(plain) {
44
+ const iv = (0, node_crypto_1.randomBytes)(12);
45
+ const cipher = (0, node_crypto_1.createCipheriv)('aes-256-gcm', this.key, iv);
46
+ const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
47
+ return [FORMAT, iv.toString('base64'), cipher.getAuthTag().toString('base64'), data.toString('base64')].join(':');
48
+ }
49
+ /**
50
+ * Расшифровать значение из базы.
51
+ *
52
+ * @throws AppSecretsError — чужой формат, другой ключ или подменённый шифротекст.
53
+ */
54
+ open(sealed) {
55
+ const [format, iv, tag, data] = sealed.split(':');
56
+ if (format !== FORMAT || !iv || !tag || data === undefined)
57
+ throw new AppSecretsError('значение не зашифровано ключом приложения');
58
+ try {
59
+ const decipher = (0, node_crypto_1.createDecipheriv)('aes-256-gcm', this.key, Buffer.from(iv, 'base64'));
60
+ decipher.setAuthTag(Buffer.from(tag, 'base64'));
61
+ return Buffer.concat([decipher.update(Buffer.from(data, 'base64')), decipher.final()]).toString('utf8');
62
+ }
63
+ catch {
64
+ throw new AppSecretsError('секрет не расшифрован: другой ключ узла или значение изменено');
65
+ }
66
+ }
67
+ /** Маска для страницы настроек: последние четыре знака; короткое значение — только «задан». */
68
+ static mask(plain) {
69
+ if (!plain)
70
+ return null;
71
+ return plain.length > 8 ? `…${plain.slice(-4)}` : '…';
72
+ }
73
+ }
74
+ exports.AppSecrets = AppSecrets;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coopenomics/extension-sdk",
3
- "version": "2026.12.1",
3
+ "version": "2026.12.2",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -69,5 +69,5 @@
69
69
  "typescript": "^5.4.0",
70
70
  "unbuild": "^2.0.0"
71
71
  },
72
- "gitHead": "404b3d1f9bd49f2cc9b0425401c61a69dc115744"
72
+ "gitHead": "7e51e53092c0df79c8d2f240cd678bb465162aca"
73
73
  }