@coopenomics/extension-sdk 2026.12.1 → 2026.12.3-dev.10

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.
Files changed (113) hide show
  1. package/README.md +29 -0
  2. package/dist/app/app-error.d.ts +31 -0
  3. package/dist/app/app-error.js +49 -0
  4. package/dist/app/app-logger.d.ts +29 -0
  5. package/dist/app/app-logger.js +54 -0
  6. package/dist/app/app-messages.d.ts +11 -0
  7. package/dist/app/app-messages.js +16 -0
  8. package/dist/app/app-platform.module.d.ts +19 -0
  9. package/dist/app/app-platform.module.js +35 -0
  10. package/dist/app/app-rights.d.ts +73 -0
  11. package/dist/app/app-rights.js +116 -0
  12. package/dist/config/extension-config.d.ts +14 -0
  13. package/dist/config/extension-config.js +5 -0
  14. package/dist/database/app-database.module.d.ts +39 -0
  15. package/dist/database/app-database.module.js +101 -0
  16. package/dist/database/index.d.ts +2 -0
  17. package/dist/database/index.js +11 -0
  18. package/dist/database/legacy-import.d.ts +61 -0
  19. package/dist/database/legacy-import.js +153 -0
  20. package/dist/database/live-changes.plugin.d.ts +50 -0
  21. package/dist/database/live-changes.plugin.js +119 -0
  22. package/dist/graphql/account-type.enum.d.ts +18 -0
  23. package/dist/graphql/account-type.enum.js +24 -0
  24. package/dist/graphql/certificates.dto.d.ts +70 -0
  25. package/dist/graphql/certificates.dto.js +200 -0
  26. package/dist/graphql/document-aggregate.dto.d.ts +16 -0
  27. package/dist/graphql/document-aggregate.dto.js +54 -0
  28. package/dist/graphql/generate-document-input.dto.d.ts +16 -0
  29. package/dist/graphql/generate-document-input.dto.js +34 -0
  30. package/dist/graphql/generate-document-options-input.dto.d.ts +5 -0
  31. package/dist/graphql/generate-document-options-input.dto.js +30 -0
  32. package/dist/graphql/generate-meta-document-input.dto.d.ts +14 -0
  33. package/dist/graphql/generate-meta-document-input.dto.js +100 -0
  34. package/dist/graphql/generated-document.dto.d.ts +21 -0
  35. package/dist/graphql/generated-document.dto.js +64 -0
  36. package/dist/graphql/index.d.ts +39 -0
  37. package/dist/graphql/index.js +70 -0
  38. package/dist/graphql/lang-type.enum.d.ts +4 -0
  39. package/dist/graphql/lang-type.enum.js +13 -0
  40. package/dist/graphql/meta-document-input.dto.d.ts +15 -0
  41. package/dist/graphql/meta-document-input.dto.js +103 -0
  42. package/dist/graphql/pagination.dto.d.ts +41 -0
  43. package/dist/graphql/pagination.dto.js +110 -0
  44. package/dist/graphql/print-subgraph.d.ts +14 -0
  45. package/dist/graphql/print-subgraph.js +65 -0
  46. package/dist/graphql/signed-digital-document-input.dto.d.ts +31 -0
  47. package/dist/graphql/signed-digital-document-input.dto.js +133 -0
  48. package/dist/graphql/signed-digital-document.dto.d.ts +34 -0
  49. package/dist/graphql/signed-digital-document.dto.js +136 -0
  50. package/dist/graphql/signer-certificate.resolver.d.ts +23 -0
  51. package/dist/graphql/signer-certificate.resolver.js +70 -0
  52. package/dist/graphql/subgraph-sdl.d.ts +54 -0
  53. package/dist/graphql/subgraph-sdl.js +125 -0
  54. package/dist/graphql/transaction.dto.d.ts +12 -0
  55. package/dist/graphql/transaction.dto.js +70 -0
  56. package/dist/graphql/user-certificate.union.d.ts +8 -0
  57. package/dist/graphql/user-certificate.union.js +25 -0
  58. package/dist/graphql/validation-message.d.ts +12 -0
  59. package/dist/graphql/validation-message.js +12 -0
  60. package/dist/index.d.ts +11 -1
  61. package/dist/index.js +50 -1
  62. package/dist/ports/app-ports.client.d.ts +64 -0
  63. package/dist/ports/app-ports.client.js +104 -0
  64. package/dist/ports/app-ports.provider.d.ts +57 -0
  65. package/dist/ports/app-ports.provider.js +124 -0
  66. package/dist/ports/core-ports.client.js +13 -1
  67. package/dist/ports/extension-ports.module.d.ts +67 -0
  68. package/dist/ports/extension-ports.module.js +133 -4
  69. package/dist/ports/integration-settings.d.ts +17 -0
  70. package/dist/ports/integration-settings.js +6 -0
  71. package/dist/secrets/app-credentials.d.ts +6 -0
  72. package/dist/secrets/app-credentials.js +38 -0
  73. package/dist/secrets/app-secrets.d.ts +17 -0
  74. package/dist/secrets/app-secrets.js +74 -0
  75. package/dist/secrets/index.d.ts +7 -0
  76. package/dist/secrets/index.js +15 -0
  77. package/dist/subgraph-rules/index.d.ts +35 -0
  78. package/dist/subgraph-rules/index.js +211 -0
  79. package/dist/sync/abstract-blockchain-delta.mapper.d.ts +18 -0
  80. package/dist/sync/abstract-blockchain-delta.mapper.js +25 -0
  81. package/dist/sync/abstract-entity-sync.service.d.ts +79 -0
  82. package/dist/sync/abstract-entity-sync.service.js +219 -0
  83. package/dist/sync/audit-logger.d.ts +5 -0
  84. package/dist/sync/audit-logger.js +32 -0
  85. package/dist/sync/base-chain.repository.d.ts +46 -0
  86. package/dist/sync/base-chain.repository.js +127 -0
  87. package/dist/sync/base-database.interface.d.ts +17 -0
  88. package/dist/sync/base-database.interface.js +2 -0
  89. package/dist/sync/base-domain.entity.d.ts +27 -0
  90. package/dist/sync/base-domain.entity.js +52 -0
  91. package/dist/sync/base-output.dto.d.ts +10 -0
  92. package/dist/sync/base-output.dto.js +60 -0
  93. package/dist/sync/blockchain-sync.interface.d.ts +84 -0
  94. package/dist/sync/blockchain-sync.interface.js +2 -0
  95. package/dist/sync/chain-record.d.ts +15 -0
  96. package/dist/sync/chain-record.js +19 -0
  97. package/dist/sync/chain-versioning.service.d.ts +47 -0
  98. package/dist/sync/chain-versioning.service.js +169 -0
  99. package/dist/sync/delta.d.ts +22 -0
  100. package/dist/sync/delta.js +2 -0
  101. package/dist/sync/errors/audit-unknown-status.d.ts +11 -0
  102. package/dist/sync/errors/audit-unknown-status.js +26 -0
  103. package/dist/sync/errors/unsupported-contract-version.error.d.ts +23 -0
  104. package/dist/sync/errors/unsupported-contract-version.error.js +22 -0
  105. package/dist/sync/fork/fork-aware-syncer.interface.d.ts +44 -0
  106. package/dist/sync/fork/fork-aware-syncer.interface.js +22 -0
  107. package/dist/sync/index.d.ts +36 -0
  108. package/dist/sync/index.js +56 -0
  109. package/dist/sync/sync-logger.d.ts +21 -0
  110. package/dist/sync/sync-logger.js +2 -0
  111. package/dist/sync/sync-policy.d.ts +27 -0
  112. package/dist/sync/sync-policy.js +16 -0
  113. package/package.json +55 -3
@@ -7,7 +7,8 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  };
8
8
  var ExtensionPortsModule_1;
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.ExtensionPortsModule = exports.REMOTE_PORT_METHODS = exports.LIVE_FEED_PORT = exports.REMOTE_PORT_TOKENS = void 0;
10
+ exports.ExtensionPortsModule = exports.REMOTE_PORT_DATES = exports.REMOTE_PORT_METHODS = exports.BRANCH_CARD_REMOTE_PORT = exports.POWERS_OF_ATTORNEY_REMOTE_PORT = exports.LIVE_FEED_PORT = exports.REMOTE_PORT_TOKENS = void 0;
11
+ exports.reviveDates = reviveDates;
11
12
  exports.remotePort = remotePort;
12
13
  const common_1 = require("@nestjs/common");
13
14
  const core_ports_client_1 = require("./core-ports.client");
@@ -26,9 +27,39 @@ exports.REMOTE_PORT_TOKENS = {
26
27
  notification: Symbol.for('Innercoop.CorePort.Notification'),
27
28
  userDirectory: Symbol.for('Innercoop.CorePort.UserDirectory'),
28
29
  liveFeed: Symbol.for('Innercoop.CorePort.LiveFeed'),
30
+ extensionConfig: Symbol.for('Innercoop.CorePort.ExtensionConfig'),
31
+ powersOfAttorney: Symbol.for('Innercoop.CorePort.AppPowersOfAttorney'),
32
+ branchCard: Symbol.for('Innercoop.CorePort.AppBranchCard'),
33
+ // Порты «Стола заказов» (03.12.2026, 487-46): ядро открывает их только его пакету.
34
+ agreementCatalog: Symbol.for('Innercoop.CorePort.AgreementCatalog'),
35
+ branch: Symbol.for('Innercoop.CorePort.Branch'),
36
+ cooperativeLogo: Symbol.for('Innercoop.CorePort.CooperativeLogo'),
37
+ council: Symbol.for('Innercoop.CorePort.Council'),
38
+ documentApproval: Symbol.for('Innercoop.CorePort.DocumentApproval'),
39
+ expenseChassis: Symbol.for('Innercoop.CrossPlugin.ExpenseChassis'),
40
+ ledger2History: Symbol.for('Innercoop.CorePort.Ledger2History'),
41
+ organization: Symbol.for('Innercoop.CorePort.Organization'),
42
+ paymentDesk: Symbol.for('Innercoop.CorePort.PaymentDesk'),
43
+ paymentMethod: Symbol.for('Innercoop.CorePort.PaymentMethod'),
44
+ coopAuthorities: Symbol.for('Innercoop.CorePort.PowersOfAttorney'),
45
+ programAgreement: Symbol.for('Innercoop.CorePort.ProgramAgreement'),
46
+ sovietRobot: Symbol.for('Innercoop.CrossPlugin.SovietRobot'),
47
+ userAvatar: Symbol.for('Innercoop.CorePort.UserAvatar'),
48
+ userCertificate: Symbol.for('Innercoop.CorePort.UserCertificate'),
49
+ userData: Symbol.for('Innercoop.CorePort.UserData'),
50
+ userWallet: Symbol.for('Innercoop.CorePort.UserWallet'),
51
+ verification: Symbol.for('Innercoop.CorePort.Verification'),
52
+ // Обёртки ядра без порта innercoop того же вида: приложение строит из них свой адаптер.
53
+ documentData: Symbol.for('Innercoop.AppRemote.DocumentData'),
54
+ fileStorage: Symbol.for('Innercoop.AppRemote.FileStorage'),
55
+ extensionRow: Symbol.for('Innercoop.AppRemote.ExtensionRow'),
29
56
  };
30
57
  /** DI-токен порта живого обновления. */
31
58
  exports.LIVE_FEED_PORT = exports.REMOTE_PORT_TOKENS.liveFeed;
59
+ /** DI-токен реестра доверенностей ядра. */
60
+ exports.POWERS_OF_ATTORNEY_REMOTE_PORT = exports.REMOTE_PORT_TOKENS.powersOfAttorney;
61
+ /** DI-токен карточек участков. */
62
+ exports.BRANCH_CARD_REMOTE_PORT = exports.REMOTE_PORT_TOKENS.branchCard;
32
63
  /**
33
64
  * Методы портов, открытые ядром по сети — зеркало каталога ядра
34
65
  * (`remote-ports.catalog.ts` расширения apps). Объект порта отвечает только
@@ -41,12 +72,107 @@ exports.REMOTE_PORT_METHODS = {
41
72
  cooperativeVars: ['get'],
42
73
  accessToken: ['identify'],
43
74
  account: ['getDisplayName', 'getAccount', 'getAccounts'],
44
- chain: ['transact', 'getSingleRow', 'queryRows'],
75
+ // getAllRows — малые таблицы настроек (487-46: настройки контракта «Стола заказов»).
76
+ chain: ['transact', 'getSingleRow', 'queryRows', 'getAllRows'],
45
77
  // Письмо — только по сценариям писем кооператива; служебный сценарий ядро отклонит.
46
78
  notification: ['notifyUser', 'getDeliveries'],
47
- userDirectory: ['findByRoles'],
79
+ // findBySubject — пайщик по учётке CoopID: «Карта кооператора» сопоставляет уведомление сети (487-41).
80
+ userDirectory: ['findByRoles', 'findBySubject'],
48
81
  liveFeed: ['publish'],
82
+ // Только «установлено ли расширение»: конфиг расширения ядро по сети не отдаёт.
83
+ extensionConfig: ['isEnabled'],
84
+ // Только доверенности типов пакета; номер и срок ведёт ядро (487-43).
85
+ powersOfAttorney: ['nextNumber', 'register', 'resolve', 'list'],
86
+ // Карточку участка ядро сверяет с цепью; список — открытая часть карточек.
87
+ branchCard: ['create', 'list'],
88
+ agreementCatalog: ['getAgreementById'],
89
+ branch: ['getBranch', 'getBranches'],
90
+ cooperativeLogo: ['getLogoUrl', 'remove', 'upload'],
91
+ council: ['ensureProgram', 'getCoagreement', 'getPrograms'],
92
+ documentApproval: ['isStepApproved'],
93
+ expenseChassis: ['attachPlanToProposal', 'listPlans', 'snapshotRequisites', 'validateRequisites'],
94
+ ledger2History: ['getAccounts', 'getHistory', 'getWallets'],
95
+ organization: ['findByUsername'],
96
+ paymentDesk: [
97
+ 'confirmers',
98
+ 'createSystemOutgoingPayment',
99
+ 'declinePayoutRequest',
100
+ 'dropPayoutRequest',
101
+ 'getPayments',
102
+ 'getPayoutRequest',
103
+ 'registerPayoutRequest',
104
+ 'releasePayoutRequest',
105
+ 'setPaymentStatus',
106
+ ],
107
+ paymentMethod: ['get', 'list'],
108
+ coopAuthorities: ['listLapsedAuthorities'],
109
+ programAgreement: ['findProgramSignature', 'signProgramAgreement'],
110
+ sovietRobot: ['isEnabled', 'requestDecision'],
111
+ userAvatar: ['getAvatarUrl'],
112
+ userCertificate: ['getCertificateByUsername'],
113
+ userData: ['get', 'save'],
114
+ userWallet: ['findByUsername', 'findByWallet', 'findByWalletAndUsername'],
115
+ verification: ['checkRequired'],
116
+ // Данные документа по номеру реестра — для генерации ядром.
117
+ documentData: ['saveData'],
118
+ // Хранилище файлов: корзина — точная копия описания из ядра, тело — base64.
119
+ fileStorage: ['put', 'getReadUrl', 'delete', 'head'],
120
+ // Строка своего расширения в таблице extensions (состояние подключения советом).
121
+ extensionRow: ['findByName', 'patchConfig', 'ensure', 'migrate'],
49
122
  };
123
+ const PAYMENT_DATES = ['expired_at', 'completed_at', 'failed_at', 'created_at', 'updated_at'];
124
+ const PAYOUT_DATES = ['created_at', 'decided_at'];
125
+ /**
126
+ * Поля `Date` в ответах портов. По сети дата приходит строкой ISO; объект
127
+ * порта возвращает её `Date`, как порт в монолите, — перенесённый код
128
+ * сравнивает и форматирует даты без правок. Путь: `поле`, `items[].поле`,
129
+ * `[].поле` (ответ — массив).
130
+ */
131
+ exports.REMOTE_PORT_DATES = {
132
+ ledger2History: { getHistory: ['items[].createdAt'] },
133
+ paymentMethod: { get: ['created_at', 'updated_at'], list: ['items[].created_at', 'items[].updated_at'] },
134
+ paymentDesk: {
135
+ getPayments: PAYMENT_DATES.map((f) => `items[].${f}`),
136
+ setPaymentStatus: PAYMENT_DATES,
137
+ createSystemOutgoingPayment: PAYMENT_DATES,
138
+ releasePayoutRequest: PAYMENT_DATES,
139
+ registerPayoutRequest: PAYOUT_DATES,
140
+ getPayoutRequest: PAYOUT_DATES,
141
+ },
142
+ expenseChassis: { listPlans: ['[].dueDate', '[].paidAt'] },
143
+ fileStorage: { head: ['lastModified'] },
144
+ extensionRow: {
145
+ findByName: ['created_at', 'updated_at'],
146
+ patchConfig: ['created_at', 'updated_at'],
147
+ ensure: ['created_at', 'updated_at'],
148
+ migrate: ['created_at', 'updated_at'],
149
+ },
150
+ };
151
+ /** Строка ISO по пути — в `Date`; `null`, пусто и уже `Date` остаются как есть. */
152
+ function reviveDates(value, paths) {
153
+ for (const path of paths)
154
+ reviveAt(value, path.split('.'));
155
+ return value;
156
+ }
157
+ function reviveAt(node, steps) {
158
+ if (node === null || typeof node !== 'object' || steps.length === 0)
159
+ return;
160
+ const [step, ...rest] = steps;
161
+ const many = step.endsWith('[]');
162
+ const field = many ? step.slice(0, -2) : step;
163
+ const target = field === '' ? node : node[field];
164
+ if (many) {
165
+ if (Array.isArray(target))
166
+ for (const item of target)
167
+ reviveAt(item, rest);
168
+ return;
169
+ }
170
+ if (rest.length > 0)
171
+ return reviveAt(target, rest);
172
+ const record = node;
173
+ if (typeof record[field] === 'string' && record[field] !== '')
174
+ record[field] = new Date(record[field]);
175
+ }
50
176
  /**
51
177
  * Объект порта, каждый метод которого — вызов ядра по сети.
52
178
  *
@@ -58,7 +184,10 @@ exports.REMOTE_PORT_METHODS = {
58
184
  function remotePort(client, port) {
59
185
  const target = {};
60
186
  for (const method of exports.REMOTE_PORT_METHODS[port]) {
61
- target[method] = (...args) => client.call(port, method, args);
187
+ const dates = exports.REMOTE_PORT_DATES[port]?.[method];
188
+ target[method] = dates
189
+ ? async (...args) => reviveDates(await client.call(port, method, args), dates)
190
+ : (...args) => client.call(port, method, args);
62
191
  }
63
192
  if (port === 'chain')
64
193
  target.initialize = () => undefined;
@@ -0,0 +1,17 @@
1
+ import type { CorePortsClient } from './core-ports.client';
2
+ /**
3
+ * Ключи и адреса внешних служб контура для приложения каталога
4
+ * (02.12.2026, 487-42).
5
+ *
6
+ * Настройки служб (Matrix, LiveKit, распознавание речи) задаются при
7
+ * развёртывании контура и хранятся в ядре. Приложение получает их портом
8
+ * `integration.<служба>`: порт заявлен в манифесте, председатель согласился,
9
+ * а ядро разрешило службу этому пакету. В остальных случаях — `null`, как
10
+ * при ненастроенной службе: приложение обязано работать без неё.
11
+ *
12
+ * ```ts
13
+ * const matrix = await integrationSettings<MatrixSettings>(client, 'matrix');
14
+ * ```
15
+ */
16
+ export type IntegrationService = 'matrix' | 'livekit' | 'openai' | 'cardcoop_client' | 'geocoder';
17
+ export declare function integrationSettings<T = Record<string, unknown>>(client: CorePortsClient, service: IntegrationService): Promise<T | null>;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.integrationSettings = integrationSettings;
4
+ async function integrationSettings(client, service) {
5
+ return (await client.call(`integration.${service}`, 'get', [])) ?? null;
6
+ }
@@ -0,0 +1,6 @@
1
+ /** Токен, которым приложение вызывает порты других приложений и ядра-поставщика. */
2
+ export declare function appOutboundToken(secret: string, packageId: string): string;
3
+ /** Токен, которым посредник входит в приложение-поставщика. */
4
+ export declare function appInboundToken(secret: string, packageId: string): string;
5
+ /** Ключ шифрования секретов приложения (`APP_SECRETS_KEY`): 32 байта в base64. */
6
+ export declare function appSecretsKey(secret: string, packageId: string): string;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.appOutboundToken = appOutboundToken;
4
+ exports.appInboundToken = appInboundToken;
5
+ exports.appSecretsKey = appSecretsKey;
6
+ /**
7
+ * Учётные данные приложения каталога, выведенные из секрета узла (01.12.2026).
8
+ *
9
+ * Значения не хранятся: каждое выводится из секрета узла (`SERVER_SECRET`) и
10
+ * имени пакета через HMAC-SHA256. Значение одно и то же после переустановки
11
+ * и перезапуска, у каждого приложения своё, а сам секрет узла приложению не
12
+ * передаётся.
13
+ *
14
+ * Формулы живут в одном месте (02.12.2026, 487-49): оркестратор выдаёт по ним
15
+ * токены и ключ приложению, ядро тем же ключом перешифровывает секреты снятого
16
+ * расширения для приложения-наследника. Разойдись формулы — наследник не
17
+ * расшифровал бы перенесённые ключи.
18
+ *
19
+ * - исходящий токен — приложение предъявляет посреднику, вызывая чужой порт;
20
+ * - входящий токен — посредник предъявляет приложению-поставщику;
21
+ * - ключ секретов — приложение шифрует им свои секретные настройки ({@link AppSecrets}).
22
+ */
23
+ const node_crypto_1 = require("node:crypto");
24
+ function derive(secret, label) {
25
+ return (0, node_crypto_1.createHmac)('sha256', secret).update(label).digest();
26
+ }
27
+ /** Токен, которым приложение вызывает порты других приложений и ядра-поставщика. */
28
+ function appOutboundToken(secret, packageId) {
29
+ return `apo_${derive(secret, `app-ports:out:${packageId}`).toString('hex')}`;
30
+ }
31
+ /** Токен, которым посредник входит в приложение-поставщика. */
32
+ function appInboundToken(secret, packageId) {
33
+ return `api_${derive(secret, `app-ports:in:${packageId}`).toString('hex')}`;
34
+ }
35
+ /** Ключ шифрования секретов приложения (`APP_SECRETS_KEY`): 32 байта в base64. */
36
+ function appSecretsKey(secret, packageId) {
37
+ return derive(secret, `app-secrets:${packageId}`).toString('base64');
38
+ }
@@ -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;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Секреты приложения каталога: шифр секретных настроек и учётные данные,
3
+ * выведенные из секрета узла. Подпуть без зависимостей кроме `node:crypto`:
4
+ * его импортируют оркестратор и ядро, не загружая остальной набор.
5
+ */
6
+ export { AppSecrets, AppSecretsError } from './app-secrets';
7
+ export { appInboundToken, appOutboundToken, appSecretsKey } from './app-credentials';
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.appSecretsKey = exports.appOutboundToken = exports.appInboundToken = exports.AppSecretsError = exports.AppSecrets = void 0;
4
+ /**
5
+ * Секреты приложения каталога: шифр секретных настроек и учётные данные,
6
+ * выведенные из секрета узла. Подпуть без зависимостей кроме `node:crypto`:
7
+ * его импортируют оркестратор и ядро, не загружая остальной набор.
8
+ */
9
+ var app_secrets_1 = require("./app-secrets");
10
+ Object.defineProperty(exports, "AppSecrets", { enumerable: true, get: function () { return app_secrets_1.AppSecrets; } });
11
+ Object.defineProperty(exports, "AppSecretsError", { enumerable: true, get: function () { return app_secrets_1.AppSecretsError; } });
12
+ var app_credentials_1 = require("./app-credentials");
13
+ Object.defineProperty(exports, "appInboundToken", { enumerable: true, get: function () { return app_credentials_1.appInboundToken; } });
14
+ Object.defineProperty(exports, "appOutboundToken", { enumerable: true, get: function () { return app_credentials_1.appOutboundToken; } });
15
+ Object.defineProperty(exports, "appSecretsKey", { enumerable: true, get: function () { return app_credentials_1.appSecretsKey; } });
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Общие типы платформы — объявлены в `@coopenomics/extension-sdk/graphql`.
3
+ * Приложение берёт их из SDK без копий; гейт `pnpm check`
4
+ * (`scripts/check-shared-graphql-types.mjs`) держит список равным объявлениям.
5
+ */
6
+ export declare const SHARED_SCHEMA_TYPES: readonly string[];
7
+ export interface AppSchemaPrefix {
8
+ /** Ключ приставки, уникальный в каталоге: `chatcoop`. */
9
+ key: string;
10
+ /** Приставка типов: `Chatcoop`. */
11
+ typePrefix: string;
12
+ /** Приставка полей запросов: `chatcoop`. */
13
+ fieldPrefix: string;
14
+ }
15
+ /**
16
+ * Приставка схемы по имени пакета (`@scope/name`). `null` — из имени ключ не
17
+ * выводится (нет латинских букв в начале).
18
+ */
19
+ export declare function appSchemaPrefix(packageId: string): AppSchemaPrefix | null;
20
+ export interface SubgraphViolation {
21
+ /** Имя типа или `Тип.поле`. */
22
+ subject: string;
23
+ /** Причина — текстом для издателя и для страницы приложения. */
24
+ reason: string;
25
+ }
26
+ /**
27
+ * Нарушения правила в схеме приложения. Пустой список — приложение можно
28
+ * сводить с ядром. Конфликты, которых правило не видит (тип с приставкой,
29
+ * совпавший с типом ядра), находит само сведение.
30
+ */
31
+ export declare function checkAppSubgraph(input: {
32
+ coreSdl: string;
33
+ appSdl: string;
34
+ packageId: string;
35
+ }): SubgraphViolation[];
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SHARED_SCHEMA_TYPES = void 0;
4
+ exports.appSchemaPrefix = appSchemaPrefix;
5
+ exports.checkAppSubgraph = checkAppSubgraph;
6
+ /**
7
+ * Правило схемы приложения каталога: собственные имена — с приставкой
8
+ * приложения, общие имена — только общие типы платформы и в форме ядра.
9
+ *
10
+ * Оркестратор узла сводит подграф ядра и подграфы приложений в одну схему.
11
+ * Два подграфа с одноимённым типом или одноимённым полем запроса либо не
12
+ * сводятся вовсе, либо сводятся с потерей полей: входной тип федерация
13
+ * сводит пересечением полей. Без правила приложение одного издателя
14
+ * исключает из схемы приложение другого издателя или урезает вход ядра
15
+ * (03.12.2026, «Кооперативный участок» 0.1.0 скопировал документные типы ядра).
16
+ *
17
+ * Правило проверяется дважды одним кодом: набор издателя (`app-kit`)
18
+ * останавливает выпуск, оркестратор узла отказывает приложению в подключении
19
+ * к схеме. Проверка только на стороне издателя не защищает узел: выпуск можно
20
+ * собрать и без набора.
21
+ *
22
+ * Приставка выводится из имени пакета. Ключ — имя после области, только
23
+ * строчные латинские буквы и цифры (`@voskhod/chat-coop` → `chatcoop`).
24
+ * Типы приложения начинаются с ключа с заглавной первой буквой и следующей
25
+ * заглавной буквой (`ChatcoopRoom`), поля `Query`/`Mutation`/`Subscription` —
26
+ * с ключа и следующей заглавной буквы (`chatcoopRooms`). Внутри приставки
27
+ * заглавных букв нет, поэтому приставки разных ключей не пересекаются:
28
+ * `KubFoo` не подходит приложению `ku` — после `Ku` стоит строчная `b`.
29
+ * Каталог закрепляет ключ за первым опубликованным пакетом.
30
+ *
31
+ * Модуль зависит только от `graphql`.
32
+ */
33
+ const graphql_1 = require("graphql");
34
+ /**
35
+ * Общие типы платформы — объявлены в `@coopenomics/extension-sdk/graphql`.
36
+ * Приложение берёт их из SDK без копий; гейт `pnpm check`
37
+ * (`scripts/check-shared-graphql-types.mjs`) держит список равным объявлениям.
38
+ */
39
+ exports.SHARED_SCHEMA_TYPES = [
40
+ 'AccountType',
41
+ 'DocumentAggregate',
42
+ 'EntrepreneurCertificate',
43
+ 'GenerateDocumentInput',
44
+ 'GenerateDocumentOptionsInput',
45
+ 'GenerateMetaDocumentInput',
46
+ 'GeneratedDocument',
47
+ 'IndividualCertificate',
48
+ 'LangType',
49
+ 'MetaDocumentInput',
50
+ 'OrganizationCertificate',
51
+ 'PaginationInput',
52
+ 'RepresentedByCertificate',
53
+ 'SignatureInfo',
54
+ 'SignatureInfoInput',
55
+ 'SignedDigitalDocument',
56
+ 'SignedDigitalDocumentInput',
57
+ 'Transaction',
58
+ 'UserCertificateUnion',
59
+ ];
60
+ /** Встроенные и служебные имена схемы: их объявляет GraphQL или федерация. */
61
+ const RESERVED_TYPES = new Set([
62
+ 'Query',
63
+ 'Mutation',
64
+ 'Subscription',
65
+ 'String',
66
+ 'Int',
67
+ 'Float',
68
+ 'Boolean',
69
+ 'ID',
70
+ '_Any',
71
+ '_Entity',
72
+ '_Service',
73
+ 'link__Import',
74
+ 'link__Purpose',
75
+ 'federation__FieldSet',
76
+ 'federation__Scope',
77
+ 'federation__Policy',
78
+ 'FieldSet',
79
+ ]);
80
+ const ROOT_TYPES = new Set(['Query', 'Mutation', 'Subscription']);
81
+ const FEDERATION_FIELDS = new Set(['_service', '_entities']);
82
+ /**
83
+ * Приставка схемы по имени пакета (`@scope/name`). `null` — из имени ключ не
84
+ * выводится (нет латинских букв в начале).
85
+ */
86
+ function appSchemaPrefix(packageId) {
87
+ const name = packageId.includes('/') ? packageId.slice(packageId.indexOf('/') + 1) : packageId;
88
+ const key = name.toLowerCase().replace(/[^a-z0-9]/g, '');
89
+ if (!/^[a-z]/.test(key))
90
+ return null;
91
+ return { key, typePrefix: key[0].toUpperCase() + key.slice(1), fieldPrefix: key };
92
+ }
93
+ /** Имя начинается с приставки, за ней — заглавная латинская буква. */
94
+ function hasPrefix(name, prefix) {
95
+ return name.length > prefix.length && name.startsWith(prefix) && /[A-Z]/.test(name[prefix.length]);
96
+ }
97
+ function definitionsByName(doc) {
98
+ const out = new Map();
99
+ for (const d of doc.definitions) {
100
+ if (!('name' in d) || !d.name)
101
+ continue;
102
+ if (d.kind === graphql_1.Kind.DIRECTIVE_DEFINITION)
103
+ continue;
104
+ const named = d;
105
+ const list = out.get(named.name.value) ?? [];
106
+ list.push(named);
107
+ out.set(named.name.value, list);
108
+ }
109
+ return out;
110
+ }
111
+ function fieldsOf(defs) {
112
+ const out = new Map();
113
+ for (const d of defs) {
114
+ const fields = d.fields ?? [];
115
+ for (const f of fields)
116
+ out.set(f.name.value, (0, graphql_1.print)(f.type));
117
+ }
118
+ return out;
119
+ }
120
+ function valuesOf(defs) {
121
+ const out = new Set();
122
+ for (const d of defs) {
123
+ for (const v of d.values ?? [])
124
+ out.add(v.name.value);
125
+ for (const t of d.types ?? [])
126
+ out.add(t.name.value);
127
+ }
128
+ return out;
129
+ }
130
+ const kindOf = (defs) => defs[0].kind.replace(/_(TYPE_)?(DEFINITION|EXTENSION)$/, '');
131
+ /**
132
+ * Нарушения правила в схеме приложения. Пустой список — приложение можно
133
+ * сводить с ядром. Конфликты, которых правило не видит (тип с приставкой,
134
+ * совпавший с типом ядра), находит само сведение.
135
+ */
136
+ function checkAppSubgraph(input) {
137
+ const prefix = appSchemaPrefix(input.packageId);
138
+ if (!prefix) {
139
+ return [{ subject: input.packageId, reason: 'из имени пакета не выводится приставка схемы: имя начинается не с латинской буквы' }];
140
+ }
141
+ const core = definitionsByName((0, graphql_1.parse)(input.coreSdl));
142
+ const app = definitionsByName((0, graphql_1.parse)(input.appSdl));
143
+ const shared = new Set(exports.SHARED_SCHEMA_TYPES);
144
+ const out = [];
145
+ for (const [name, defs] of app) {
146
+ if (ROOT_TYPES.has(name)) {
147
+ for (const field of fieldsOf(defs).keys()) {
148
+ if (FEDERATION_FIELDS.has(field) || hasPrefix(field, prefix.fieldPrefix))
149
+ continue;
150
+ out.push({
151
+ subject: `${name}.${field}`,
152
+ reason: `поле запроса без приставки приложения: назовите его ${prefix.fieldPrefix}${field[0].toUpperCase()}${field.slice(1)}`,
153
+ });
154
+ }
155
+ continue;
156
+ }
157
+ if (RESERVED_TYPES.has(name))
158
+ continue;
159
+ const coreDefs = core.get(name);
160
+ // Скаляр, объявленный ядром (DateTime, JSON), сводится без конфликта.
161
+ if (defs[0].kind === graphql_1.Kind.SCALAR_TYPE_DEFINITION && coreDefs?.[0].kind === graphql_1.Kind.SCALAR_TYPE_DEFINITION)
162
+ continue;
163
+ if (shared.has(name)) {
164
+ if (!coreDefs)
165
+ continue; // ядро без этого типа — сведение покажет расхождение
166
+ out.push(...compareShared(name, defs, coreDefs));
167
+ continue;
168
+ }
169
+ if (hasPrefix(name, prefix.typePrefix))
170
+ continue;
171
+ // Приставка внутри имени (`CreateKuDecisionInput`) переносится в начало, а не повторяется.
172
+ const suggested = prefix.typePrefix + name.replace(new RegExp(`${prefix.typePrefix}(?=[A-Z])`), '');
173
+ out.push({
174
+ subject: name,
175
+ reason: coreDefs
176
+ ? `тип совпадает с типом ядра и не входит в общие типы платформы: возьмите общий тип из @coopenomics/extension-sdk/graphql или назовите свой ${suggested}`
177
+ : `тип без приставки приложения: назовите его ${suggested}`,
178
+ });
179
+ }
180
+ return out;
181
+ }
182
+ /** Общий тип в приложении обязан совпадать с ядром: иначе он меняет форму типа ядра. */
183
+ function compareShared(name, app, core) {
184
+ if (kindOf(app) !== kindOf(core)) {
185
+ return [{ subject: name, reason: `общий тип объявлен другим видом, чем в ядре` }];
186
+ }
187
+ const kind = app[0].kind;
188
+ if (kind === graphql_1.Kind.ENUM_TYPE_DEFINITION || kind === graphql_1.Kind.UNION_TYPE_DEFINITION) {
189
+ const a = valuesOf(app);
190
+ const c = valuesOf(core);
191
+ const same = a.size === c.size && [...a].every((v) => c.has(v));
192
+ return same ? [] : [{ subject: name, reason: `состав общего типа расходится с ядром: обновите @coopenomics/extension-sdk` }];
193
+ }
194
+ const a = fieldsOf(app);
195
+ const c = fieldsOf(core);
196
+ const out = [];
197
+ for (const [field, type] of a) {
198
+ if (!c.has(field))
199
+ out.push({ subject: `${name}.${field}`, reason: 'поля нет в общем типе ядра: приложение не добавляет поля к общим типам' });
200
+ else if (c.get(field) !== type)
201
+ out.push({ subject: `${name}.${field}`, reason: `тип поля ${type}, у ядра ${c.get(field)}: обновите @coopenomics/extension-sdk` });
202
+ }
203
+ // Вход федерация сводит пересечением полей: недостающее поле срезало бы вход ядра.
204
+ if (kind === graphql_1.Kind.INPUT_OBJECT_TYPE_DEFINITION) {
205
+ for (const field of c.keys()) {
206
+ if (!a.has(field))
207
+ out.push({ subject: `${name}.${field}`, reason: 'во входном общем типе нет поля ядра: обновите @coopenomics/extension-sdk' });
208
+ }
209
+ }
210
+ return out;
211
+ }
@@ -0,0 +1,18 @@
1
+ import type { IBlockchainDeltaMapper } from './blockchain-sync.interface';
2
+ import type { IDelta } from './delta';
3
+ /**
4
+ * Абстрактный базовый класс для всех блокчейн дельта-мапперов
5
+ * Предоставляет общую реализацию getAllEventPatterns()
6
+ */
7
+ export declare abstract class AbstractBlockchainDeltaMapper<TBlockchainData = any, TDomainEntity = any> implements IBlockchainDeltaMapper<TBlockchainData, TDomainEntity> {
8
+ /**
9
+ * Получение всех возможных паттернов событий для подписки
10
+ * Возвращает массив паттернов типа "delta::contract::table"
11
+ */
12
+ getAllEventPatterns(): string[];
13
+ abstract getSupportedContractNames(): string[];
14
+ abstract getSupportedTableNames(): string[];
15
+ abstract mapDeltaToBlockchainData(delta: IDelta): TBlockchainData | null;
16
+ abstract extractSyncValue(delta: IDelta): string;
17
+ abstract extractSyncKey(): string;
18
+ }