@coopenomics/app-kit 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.
@@ -1,7 +1,10 @@
1
- import { ForbiddenException, Inject, UseGuards } from '@nestjs/common';
1
+ import { Inject, UseGuards } from '@nestjs/common';
2
2
  import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql';
3
3
  import {
4
+ CurrentUser,
4
5
  ExtensionAccessGuard,
6
+ RequireRight,
7
+ RightsGuard,
5
8
  loadExtensionConfig,
6
9
  type ExtensionIdentity,
7
10
  } from '@coopenomics/extension-sdk';
@@ -13,11 +16,10 @@ import {
13
16
  type ICooperativeVarsPort,
14
17
  type IDocumentPort,
15
18
  } from '@coopenomics/innercoop';
16
- import { CurrentIdentity } from './current-identity.decorator';
17
19
  import {
18
- ExampleAppCooperative,
19
- ExampleAppDraftDocument,
20
- ExampleAppSignProbe,
20
+ ExampleappCooperative,
21
+ ExampleappDraftDocument,
22
+ ExampleappSignProbe,
21
23
  } from './core-demo.types';
22
24
 
23
25
  /**
@@ -44,30 +46,30 @@ export class CoreDemoResolver {
44
46
  @Inject(CHAIN_PORT) private readonly chain: IChainPort,
45
47
  ) {}
46
48
 
47
- @Query(() => ExampleAppCooperative, {
48
- name: 'exampleAppCooperative',
49
+ @Query(() => ExampleappCooperative, {
50
+ name: 'exampleappCooperative',
49
51
  nullable: true,
50
52
  description:
51
53
  'Реквизиты кооператива узла — чтение у ядра портом cooperativeVars',
52
54
  })
53
- async cooperative(): Promise<ExampleAppCooperative | null> {
55
+ async cooperative(): Promise<ExampleappCooperative | null> {
54
56
  return this.vars.get();
55
57
  }
56
58
 
57
- @Mutation(() => ExampleAppDraftDocument, {
58
- name: 'exampleAppDraftDocument',
59
+ @Mutation(() => ExampleappDraftDocument, {
60
+ name: 'exampleappDraftDocument',
59
61
  description: 'Документ на подпись пайщику: формирует ядро портом document',
60
62
  })
61
63
  @UseGuards(ExtensionAccessGuard)
62
64
  async draftDocument(
63
- @CurrentIdentity() identity: ExtensionIdentity,
65
+ @CurrentUser() identity: ExtensionIdentity,
64
66
  @Args('registryId', {
65
67
  type: () => Int,
66
68
  defaultValue: 1,
67
69
  description: 'Номер шаблона в реестре документов',
68
70
  })
69
71
  registryId: number,
70
- ): Promise<ExampleAppDraftDocument> {
72
+ ): Promise<ExampleappDraftDocument> {
71
73
  const doc = await this.documents.generate({
72
74
  data: {
73
75
  registry_id: registryId,
@@ -86,17 +88,17 @@ export class CoreDemoResolver {
86
88
  };
87
89
  }
88
90
 
89
- @Mutation(() => ExampleAppSignProbe, {
90
- name: 'exampleAppSignProbe',
91
+ @Mutation(() => ExampleappSignProbe, {
92
+ name: 'exampleappSignProbe',
91
93
  description:
92
94
  'Проба подписи: ядро подписывает заявленное действие цепи своим ключом, в цепь транзакция не отправляется',
93
95
  })
94
- @UseGuards(ExtensionAccessGuard)
95
- async signProbe(
96
- @CurrentIdentity() identity: ExtensionIdentity,
97
- ): Promise<ExampleAppSignProbe> {
98
- if (identity.role !== 'chairman')
99
- throw new ForbiddenException('Пробу подписи запускает председатель');
96
+ // Право из таблицы `rights.ts`: не председателю гард отказывает кодом
97
+ // EXAMPLEAPP_INSUFFICIENT_RIGHTS. Свой отказ приложение бросает `AppError`
98
+ // из SDK: исключение Nest в ответе подграфа код теряет (правило app-kit check).
99
+ @UseGuards(ExtensionAccessGuard, RightsGuard)
100
+ @RequireRight('SignProbe', 'run')
101
+ async signProbe(): Promise<ExampleappSignProbe> {
100
102
  // broadcast=false: транзакция подписана и возвращена, состояние цепи не меняется.
101
103
  const result = await this.chain.transact(
102
104
  { ...PROBE_ACTION, authorization: [], data: { owner: this.coopname } },
@@ -1,8 +1,8 @@
1
1
  import { Field, Int, ObjectType } from '@nestjs/graphql';
2
2
 
3
3
  /** Реквизиты кооператива узла — прочитаны у ядра портом `cooperativeVars`. */
4
- @ObjectType('ExampleAppCooperative')
5
- export class ExampleAppCooperative {
4
+ @ObjectType('ExampleappCooperative')
5
+ export class ExampleappCooperative {
6
6
  @Field(() => String, { description: 'Учётное имя кооператива в цепи' })
7
7
  coopname!: string;
8
8
 
@@ -14,8 +14,8 @@ export class ExampleAppCooperative {
14
14
  }
15
15
 
16
16
  /** Документ, сформированный ядром для пайщика, — до подписи. */
17
- @ObjectType('ExampleAppDraftDocument')
18
- export class ExampleAppDraftDocument {
17
+ @ObjectType('ExampleappDraftDocument')
18
+ export class ExampleappDraftDocument {
19
19
  @Field(() => String, { description: 'Заголовок документа' })
20
20
  fullTitle!: string;
21
21
 
@@ -32,8 +32,8 @@ export class ExampleAppDraftDocument {
32
32
  }
33
33
 
34
34
  /** Итог пробы подписи действия цепи ядром. */
35
- @ObjectType('ExampleAppSignProbe')
36
- export class ExampleAppSignProbe {
35
+ @ObjectType('ExampleappSignProbe')
36
+ export class ExampleappSignProbe {
37
37
  @Field(() => String, { description: 'Действие цепи, которое подписало ядро' })
38
38
  action!: string;
39
39
 
@@ -0,0 +1,8 @@
1
+ import { registerAppMessages } from '@coopenomics/extension-sdk';
2
+ import ru from './ru.json';
3
+
4
+ /**
5
+ * Словарь приложения: тексты отказов `errors.<КОД>`. Модуль приложения
6
+ * импортирует этот файл, поэтому словарь готов раньше первого отказа.
7
+ */
8
+ registerAppMessages('exampleapp', ru);
@@ -0,0 +1,5 @@
1
+ {
2
+ "errors": {
3
+ "EXAMPLEAPP_INSUFFICIENT_RIGHTS": "Недостаточно прав для этого действия"
4
+ }
5
+ }
@@ -10,7 +10,7 @@ import { Directive, Field, ID, ObjectType } from '@nestjs/graphql';
10
10
  * account name). В рабочем пакете на этом месте стоит отношение `@requires`
11
11
  * либо ResolveReference на SharedCooperator.
12
12
  */
13
- @ObjectType('Note')
13
+ @ObjectType('ExampleappNote')
14
14
  @Directive('@key(fields: "id")')
15
15
  export class Note {
16
16
  @Field(() => ID)
@@ -3,7 +3,7 @@ import { NotesService } from './notes.service';
3
3
  import { NotesResolver } from './notes.resolver';
4
4
 
5
5
  @Module({
6
- // Поле на пайщике ядра (Cooperator.exampleAppNotesCount) снято 25.11.2026:
6
+ // Поле на пайщике ядра (Cooperator.exampleappNotesCount) снято 25.11.2026:
7
7
  // ядро не объявляет своих сущностей с @key, шлюз такую схему не соберёт.
8
8
  // Вернуть, когда ядро отдаст Account как расширяемую сущность.
9
9
  providers: [NotesService, NotesResolver],
@@ -8,20 +8,20 @@ import {
8
8
  Resolver,
9
9
  } from '@nestjs/graphql';
10
10
  import {
11
+ CurrentUser,
11
12
  ExtensionAccessGuard,
12
13
  type ExtensionIdentity,
13
14
  } from '@coopenomics/extension-sdk';
14
- import { CurrentIdentity } from '../core/current-identity.decorator';
15
15
  import { Note } from './note.entity';
16
16
  import { NotesService } from './notes.service';
17
17
 
18
18
  /**
19
19
  * Локальные Query / Mutation расширения.
20
20
  *
21
- * - `exampleAppNotes` — публичная выдача последних заметок;
21
+ * - `exampleappNotes` — публичная выдача последних заметок;
22
22
  * в реальном пакете её можно тоже закрыть guard'ом — здесь оставлено
23
23
  * открытой, чтобы показать оба варианта (open и protected).
24
- * - `exampleAppAddNote` — защищена `ExtensionJwtAuthGuard`. Username
24
+ * - `exampleappAddNote` — защищена `ExtensionJwtAuthGuard`. Username
25
25
  * автора берётся из JWT в реальном пакете; в этом примере он передаётся
26
26
  * аргументом — чтобы пример был запускаемым без сценария на gateway.
27
27
  *
@@ -32,19 +32,19 @@ import { NotesService } from './notes.service';
32
32
  export class NotesResolver {
33
33
  constructor(private readonly notes: NotesService) {}
34
34
 
35
- @Query(() => [Note], { name: 'exampleAppNotes' })
35
+ @Query(() => [Note], { name: 'exampleappNotes' })
36
36
  list(
37
37
  @Args('limit', { type: () => Int, nullable: true }) limit?: number,
38
38
  ): Note[] {
39
39
  return this.notes.list(limit);
40
40
  }
41
41
 
42
- @Mutation(() => Note, { name: 'exampleAppAddNote' })
42
+ @Mutation(() => Note, { name: 'exampleappAddNote' })
43
43
  @UseGuards(ExtensionAccessGuard)
44
44
  add(
45
45
  // Автор — пайщик, которого опознало ядро, а не аргумент запроса: иначе
46
46
  // заметку можно записать от чужого имени.
47
- @CurrentIdentity() identity: ExtensionIdentity,
47
+ @CurrentUser() identity: ExtensionIdentity,
48
48
  @Args('body') body: string,
49
49
  ): Note {
50
50
  return this.notes.add(identity.username, body);
@@ -0,0 +1,13 @@
1
+ import type { AppRightsConfig } from '@coopenomics/extension-sdk';
2
+
3
+ /**
4
+ * Права приложения: роль пайщика → ресурс → действия. Операция называет
5
+ * право `@RequireRight('SignProbe', 'run')` и стоит под `RightsGuard`;
6
+ * нехватка прав — отказ с кодом `deniedCode` из словаря приложения.
7
+ */
8
+ export const exampleappRights: AppRightsConfig = {
9
+ table: {
10
+ chairman: { SignProbe: ['run'] },
11
+ },
12
+ deniedCode: 'EXAMPLEAPP_INSUFFICIENT_RIGHTS',
13
+ };
@@ -6,6 +6,7 @@
6
6
  "lib": ["ES2022"],
7
7
  "strict": true,
8
8
  "esModuleInterop": true,
9
+ "resolveJsonModule": true,
9
10
  "skipLibCheck": true,
10
11
  "experimentalDecorators": true,
11
12
  "emitDecoratorMetadata": true,
@@ -132,9 +132,9 @@ call('init').then(function (ctx) {
132
132
  applyTheme(ctx.theme);
133
133
  text(el('who'), ctx.username);
134
134
  text(el('coop'), ctx.coopname);
135
- return gql('{ exampleAppCooperative { coopname name shortAbbr } }');
135
+ return gql('{ exampleappCooperative { coopname name shortAbbr } }');
136
136
  }).then(function (data) {
137
- var c = data.exampleAppCooperative;
137
+ var c = data.exampleappCooperative;
138
138
  text(el('coop-name'), c ? c.shortAbbr + ' «' + c.name + '»' : '—');
139
139
  }).catch(function (e) { text(el('coop-name'), e.message); });
140
140
 
@@ -164,7 +164,7 @@ function renderNotes(notes) {
164
164
  }
165
165
 
166
166
  function loadNotes() {
167
- return gql('{ exampleAppNotes(limit: 10) { id authorUsername body } }').then(function (d) { renderNotes(d.exampleAppNotes); });
167
+ return gql('{ exampleappNotes(limit: 10) { id authorUsername body } }').then(function (d) { renderNotes(d.exampleappNotes); });
168
168
  }
169
169
  loadNotes().catch(function (e) { text(el('note-error'), e.message); });
170
170
 
@@ -173,7 +173,7 @@ el('note-add').addEventListener('click', function () {
173
173
  text(el('note-error'), '');
174
174
  if (!body) return;
175
175
  el('note-add').disabled = true;
176
- gql('mutation($b: String!) { exampleAppAddNote(body: $b) { id } }', { b: body })
176
+ gql('mutation($b: String!) { exampleappAddNote(body: $b) { id } }', { b: body })
177
177
  .then(function () { el('note-body').value = ''; return loadNotes(); })
178
178
  .catch(function (e) { text(el('note-error'), e.message); })
179
179
  .then(function () { el('note-add').disabled = false; });
@@ -184,8 +184,8 @@ el('sign').addEventListener('click', function () {
184
184
  text(el('sign-error'), '');
185
185
  el('sign-result').innerHTML = '';
186
186
  el('sign').disabled = true;
187
- gql('mutation { exampleAppDraftDocument { fullTitle hash } }')
188
- .then(function (d) { return call('sign', { hash: d.exampleAppDraftDocument.hash }); })
187
+ gql('mutation { exampleappDraftDocument { fullTitle hash } }')
188
+ .then(function (d) { return call('sign', { hash: d.exampleappDraftDocument.hash }); })
189
189
  .then(function (signed) {
190
190
  var first = signed && signed.signatures && signed.signatures[0];
191
191
  var box = el('sign-result');
@@ -1,12 +0,0 @@
1
- import { createParamDecorator, ExecutionContext } from '@nestjs/common';
2
- import { GqlExecutionContext } from '@nestjs/graphql';
3
- import type { ExtensionIdentity } from '@coopenomics/extension-sdk';
4
-
5
- /**
6
- * Пайщик, сделавший запрос. Его кладёт в запрос `ExtensionAccessGuard` после
7
- * ответа ядра; без охранника на резолвере значения нет.
8
- */
9
- export const CurrentIdentity = createParamDecorator(
10
- (_data: unknown, context: ExecutionContext): ExtensionIdentity =>
11
- GqlExecutionContext.create(context).getContext().req.user,
12
- );
@@ -1,3 +0,0 @@
1
- Пакеты SDK приложений, собранные из чекаута mono. Набор кладёт их в эту папку,
2
- когда команда `create` запущена из чекаута mono: в npm такая версия SDK ещё не
3
- вышла. Каркас из npm-пакета набора берёт SDK из npm, архивов в папке нет.