odant-work 1.0.99 → 1.0.101

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 (27) hide show
  1. package/#system/package-manifest.json +8 -8
  2. package/$server/$folder/$class/$structure/$user/class.js +1 -0
  3. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/profile/$handler/class.js +5 -2
  4. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/staff/$handler/class.js +3 -0
  5. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/tokens/$handler/class.js +24 -0
  6. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/users/$handler/class.js +213 -0
  7. package/$server/$folder/lib/consultant/consultant.js +6 -1
  8. package/$server/$folder/lib/explorer/explorer.js +18 -1
  9. package/$server/$folder/lib/prompt-bar/prompt-bar.js +15 -1
  10. package/$server/$folder/lib/tree/tree.js +2 -3
  11. package/MODULES/$domain/class.js +1 -0
  12. package/MODULES//320/234/320/276/320/264/320/265/320/273/320/270/Local/$provider/class.js +1 -0
  13. package/{$server/$folder/$class/$users → USERS/$user}/class.js +4 -1
  14. package/oda/oda.js +15 -1
  15. package/package.json +1 -1
  16. package/readme.md +1 -1
  17. package/sources/client/handler.js +17 -5
  18. package/sources/client.js +68 -35
  19. package/sources/host/auth-methods.js +14 -3
  20. package/sources/modules/rag/extract.js +1 -1
  21. package/sources/modules/user-profile/user-profile.js +120 -115
  22. package/sources/modules/user-profile/user-tokens.js +185 -0
  23. package/sources/server/class/distro.js +9 -5
  24. package/sources/server/class/security.js +34 -10
  25. package/sources/server/folder.js +7 -7
  26. package/sources/server/user.js +3 -0
  27. package/USERS/$users/class.js +0 -4
@@ -0,0 +1,185 @@
1
+ ODA({ is: 'user-tokens',
2
+ template: /* html */`
3
+ <style>
4
+ :host {
5
+ overflow: auto;
6
+ @apply --light;
7
+ @apply --vertical;
8
+ @apply --flex;
9
+ padding: 16px;
10
+ box-sizing: border-box;
11
+ }
12
+ .tokens-wrap {
13
+ gap: 12px;
14
+ width: min(520px, 100%);
15
+ align-self: center;
16
+ margin: 0 auto auto auto;
17
+ box-sizing: border-box;
18
+ }
19
+ button {
20
+ min-height: 40px;
21
+ padding: 8px 14px;
22
+ border-radius: 8px;
23
+ font-size: medium;
24
+ cursor: pointer;
25
+ max-width: 100%;
26
+ box-sizing: border-box;
27
+ }
28
+ .token-row {
29
+ gap: 8px;
30
+ align-items: center;
31
+ justify-content: space-between;
32
+ flex-wrap: wrap;
33
+ border: 1px solid rgba(128, 128, 128, 0.35);
34
+ border-radius: 8px;
35
+ padding: 8px 10px;
36
+ }
37
+ .hint {
38
+ font-size: small;
39
+ text-align: center;
40
+ opacity: 0.78;
41
+ line-height: 1.4;
42
+ }
43
+ .msg {
44
+ font-size: small;
45
+ text-align: center;
46
+ }
47
+ .msg[error] {
48
+ color: var(--error-color, #dc2626);
49
+ }
50
+ </style>
51
+ <div no-flex vertical class="tokens-wrap">
52
+ <div style="font-size: large; font-weight: 600; text-align: center;">Токены подключений</div>
53
+ <div class="hint">
54
+ Персональный токен используется вместе с адресом WORK в расширении <b>WORK Chrome Bridge</b> и внешних ИИ-клиентах (MCP).
55
+ </div>
56
+ <div ~if="!canManage" class="msg" error>
57
+ Управление токенами доступно только владельцу активной учётной записи.
58
+ </div>
59
+ <div ~if="canManage" vertical style="gap: 10px; width: 100%;">
60
+ <button center horizontal flex class="success-invert" @tap.stop.prevent="mcp_token" title="Выпустить персональный токен для внешних ИИ-клиентов (MCP) и расширения WORK Chrome Bridge">
61
+ <span>Выпустить токен подключения</span>
62
+ </button>
63
+ <button center horizontal flex @tap.stop.prevent="mcp_list" title="Список токенов: срок жизни, последнее использование, отзыв по одному">
64
+ <span>{{mcpList ? 'Скрыть список токенов' : 'Список токенов…'}}</span>
65
+ </button>
66
+ <div ~if="mcpList" vertical style="gap: 8px; width: 100%;">
67
+ <div ~if="!mcpList.length" class="hint">Активных токенов нет</div>
68
+ <div ~for="mcpList" horizontal class="token-row">
69
+ <span flex>{{$for.item.label}}{{$for.item.role ? ' (' + $for.item.role + ')' : ''}}</span>
70
+ <span no-flex style="font-size: small; opacity: 0.8;">{{$for.item.expired ? 'истёк' : 'до ' + fmtDate($for.item.expires)}} · был {{fmtDate($for.item.lastUsed)}}</span>
71
+ <button no-flex style="min-height: 32px; font-size: small;" @tap.stop.prevent="mcp_revoke_one($for.item.id)">Отозвать</button>
72
+ </div>
73
+ </div>
74
+ <button center horizontal flex class="error-invert" @tap.stop.prevent="mcp_revoke">
75
+ <span>Отозвать все токены</span>
76
+ </button>
77
+ </div>
78
+ <div ~if="text" class="msg" :error="!!error">{{text}}</div>
79
+ </div>
80
+ `,
81
+ $item: null,
82
+ mcpList: null,
83
+ text: '',
84
+ error: false,
85
+ get canManage() {
86
+ if (!WORK?.uid)
87
+ return false;
88
+ if (this.$item?.id)
89
+ return this.$item.id === WORK.uid;
90
+ return true;
91
+ },
92
+ attached() {
93
+ this._onAuth = () => {
94
+ if (!this.canManage)
95
+ this.mcpList = null;
96
+ this.render?.();
97
+ };
98
+ WORK.authEvents?.addEventListener?.('auth', this._onAuth);
99
+ },
100
+ detached() {
101
+ if (this._onAuth)
102
+ WORK.authEvents?.removeEventListener?.('auth', this._onAuth);
103
+ },
104
+ fmtDate(ms) {
105
+ return ms ? new Date(ms).toLocaleDateString() : '—';
106
+ },
107
+ async mcp_list() {
108
+ this.error = false;
109
+ this.text = '';
110
+ try {
111
+ this.mcpList = this.mcpList ? null : await WORK.fetch('/', 'mcp_token_list', {}, {});
112
+ }
113
+ catch (e) {
114
+ this.error = true;
115
+ this.text = e?.message || String(e || '');
116
+ }
117
+ },
118
+ async mcp_revoke_one(id) {
119
+ try {
120
+ await WORK.showConfirm('Отозвать этот токен? Подключённый клиент перестанет работать.');
121
+ }
122
+ catch { return; }
123
+ this.error = false;
124
+ try {
125
+ await WORK.fetch('/', 'mcp_token_revoke', {}, { id });
126
+ this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
127
+ this.text = 'Токен отозван';
128
+ }
129
+ catch (e) {
130
+ this.error = true;
131
+ this.text = e?.message || String(e || '');
132
+ }
133
+ },
134
+ async mcp_token() {
135
+ try {
136
+ await WORK.showConfirm('Выпустить персональный токен для подключения (WORK Chrome Bridge, OpenCode, Claude Code…)? Он даёт доступ к WORK с вашими правами и покажется один раз.');
137
+ }
138
+ catch { return; }
139
+ this.error = false;
140
+ this.text = '';
141
+ try {
142
+ const r = await WORK.fetch('/', 'mcp_token_create', {}, { label: 'Подключение (MCP / Chrome)' });
143
+ if (this.mcpList)
144
+ this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
145
+ if (typeof WORK.showModal === 'function') {
146
+ const dlg = ODA.createComponent('user-token', {
147
+ token: r.token,
148
+ origin: location.origin,
149
+ });
150
+ try {
151
+ await WORK.showModal(dlg, {
152
+ TITLE: { label: 'Токен подключения' },
153
+ allowClose: true,
154
+ BUTTONS: [],
155
+ });
156
+ }
157
+ catch { /* закрыли окно */ }
158
+ }
159
+ else {
160
+ prompt('Токен подключения — скопируйте, повторно он не показывается.\nАдрес сервера: ' + location.origin + '\nАдрес MCP: ' + location.origin + '/mcp', r.token);
161
+ }
162
+ }
163
+ catch (e) {
164
+ this.error = true;
165
+ this.text = e?.message || String(e || '');
166
+ }
167
+ },
168
+ async mcp_revoke() {
169
+ try {
170
+ await WORK.showConfirm('Отозвать все токены подключения? Подключённые внешние клиенты и Chrome Bridge перестанут работать.');
171
+ }
172
+ catch { return; }
173
+ this.error = false;
174
+ try {
175
+ const r = await WORK.fetch('/', 'mcp_token_revoke', {}, { all: true });
176
+ if (this.mcpList)
177
+ this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
178
+ this.text = 'Токенов отозвано: ' + (r?.revoked ?? 0);
179
+ }
180
+ catch (e) {
181
+ this.error = true;
182
+ this.text = e?.message || String(e || '');
183
+ }
184
+ },
185
+ });
@@ -7,7 +7,7 @@
7
7
  * презентационные материалы и пользовательская документация (`docs`, `readme.md`, `whitepaper.*`);
8
8
  * - Настроенные эталонные модули и коннекторы (`/MODULES/**`);
9
9
  * - Чистые системные метапапки доменов (`/ORGANIZATIONS/$domain`, `/PROJECTS/$domain`,
10
- * `/USERS/$users`, `/NODES/$node` / `/NODES/$nodes`) БЕЗ пользователей, организаций и проектов;
10
+ * `/USERS/$user`, `/NODES/$node` / `/NODES/$nodes`) БЕЗ пользователей, организаций и проектов;
11
11
  * - Опционально: `node_modules` (для 100% офлайн-запуска без `npm install`);
12
12
  * - Опционально: локальные модели ИИ и веса (`/MODELS/Local/*`, `/MODELS/Halogen/*` с `#weights` и `#adapters`);
13
13
  * - Опционально: локальный Python-рантайм (`.venv`);
@@ -62,7 +62,6 @@ const CORE_DIRS = [
62
62
  'rules',
63
63
  'docs',
64
64
  'PROJECTS/$domain',
65
- 'USERS/$users',
66
65
  ];
67
66
 
68
67
  function normRel(p) {
@@ -288,9 +287,14 @@ export function collectDistroEntriesSync(rootDir = process.cwd(), opts = {}) {
288
287
  for (const dir of CORE_DIRS) {
289
288
  walkRelDir(dir);
290
289
  }
291
- for (const nodeMeta of ['NODES/$node', 'NODES/$nodes']) {
292
- if (fs.existsSync(path.join(absRoot, nodeMeta)))
293
- walkRelDir(nodeMeta);
290
+ for (const container of ['USERS', 'NODES']) {
291
+ const containerAbs = path.join(absRoot, container);
292
+ if (!fs.existsSync(containerAbs))
293
+ continue;
294
+ for (const e of fs.readdirSync(containerAbs, { withFileTypes: true })) {
295
+ if (e.isDirectory() && e.name.startsWith('$'))
296
+ walkRelDir(`${container}/${e.name}`);
297
+ }
294
298
  }
295
299
 
296
300
  // 4. Раздел /MODULES (все группы кроме Модели — целиком; в Модели пропускаем odant, а Local/Halogen — по выбору)
@@ -575,6 +575,17 @@ export const classSecurityMethods = {
575
575
  }
576
576
  if (this._isSystemItem(item))
577
577
  return true;
578
+ if (this.areaOf(item).kind === POLICY.AREA.SECRET)
579
+ return false;
580
+ const isUserSession = Boolean(uid && params.session?.principal?.kind !== 'node');
581
+ if (isUserSession && (this.DATA?.allowAllUsers === true || item?.DATA?.allowAllUsers === true)) {
582
+ if (!(item instanceof FS.$class) || item === this || item.DATA?.allowAllUsers === true || !item.hasAssignments?.())
583
+ return true;
584
+ }
585
+ if (this.DATA?.container === true && !this.hasAssignments() && (item === this || !(item instanceof FS.$class))) {
586
+ if (isUserSession && await this._hasAccessibleChild(item, params))
587
+ return true;
588
+ }
578
589
  const roles = await this.roles(params);
579
590
  const isModNode = this.type === '$module'
580
591
  || item?.type === '$module'
@@ -739,18 +750,36 @@ export const classSecurityMethods = {
739
750
  return false;
740
751
  },
741
752
 
753
+ async _hasAccessibleChild(node, params, depth = 0) {
754
+ if (!node || depth > 3)
755
+ return false;
756
+ const items = await Promise.resolve(node.items).catch(() => []);
757
+ for (const i of items || []) {
758
+ if (!i || i.isMetaFolder || i.id?.[0] === '$')
759
+ continue;
760
+ if (i instanceof FS.$class) {
761
+ if (await i.allowAccess(params))
762
+ return true;
763
+ }
764
+ else if (depth < 3 && await this._hasAccessibleChild(i, params, depth + 1)) {
765
+ return true;
766
+ }
767
+ }
768
+ return false;
769
+ },
770
+
742
771
  async allowAccess(params) {
743
772
  const isSysSession = DEV_MODE || !params?.session || params.session.$user === globalThis.WORK;
744
- // Раздел /USERS ($users): виден внутренним сотрудникам и скрыт от внешних (external-only) и гостей
745
- if (this.type === '$users') {
773
+ await this.init;
774
+ // Раздел /USERS (usersContainer): виден внутренним сотрудникам и скрыт от внешних (external-only) и гостей
775
+ if (this.DATA?.usersContainer === true) {
746
776
  if (isSysSession)
747
777
  return true;
748
778
  if (params?.session?.principal?.kind === 'node')
749
779
  return false;
750
780
  return this._hasInternalWorkRole(params);
751
781
  }
752
- // Домен-контейнер (например /PROJECTS): виден только BOSS или при наличии хотя бы одного доступного потомка
753
- await this.init;
782
+ // Домен-контейнер (например /PROJECTS, /MODULES): виден только BOSS или при наличии хотя бы одного доступного потомка
754
783
  if (this.DATA?.container === true && !this.hasAssignments()) {
755
784
  if (isSysSession)
756
785
  return true;
@@ -759,12 +788,7 @@ export const classSecurityMethods = {
759
788
  const uid = this.constructor.resolveUid(params);
760
789
  if (uid && (await this.allBosses).some(u => u?.id === uid))
761
790
  return true;
762
- const items = await this.items;
763
- for (const i of items) {
764
- if (i instanceof FS.$class && await i.allowAccess(params))
765
- return true;
766
- }
767
- return false;
791
+ return this._hasAccessibleChild(this, params);
768
792
  }
769
793
  let result = await this.canSee(this, params);
770
794
  if (!result) {
@@ -1329,7 +1329,6 @@ export class $folder extends $item{
1329
1329
  * Возвращает null, если ограничений по типам нет (кроме отсечения не-средовых узлов).
1330
1330
  */
1331
1331
  _mainTreeAllowedTypes() {
1332
- const ENV_TYPES = new Set(['$domain', '$structure', '$project', '$module', '$provider', '$mcp', '$users', '$user', '$node', '$ai']);
1333
1332
  if (this.type === '$server')
1334
1333
  return null;
1335
1334
  if (Array.isArray(this.DATA?.mainTreeChildren))
@@ -1341,16 +1340,14 @@ export class $folder extends $item{
1341
1340
  if (this.type === '$folder')
1342
1341
  return null;
1343
1342
  if (this.parent?.type === '$server')
1344
- return ENV_TYPES;
1343
+ return null;
1345
1344
  if (this.type === '$project' || this.type === '$structure')
1346
1345
  return new Set(['$structure', '$project']);
1347
1346
  if (this.type === '$module' || this.type === '$mcp' || this.type === '$user' || this.type === '$node' || this.type === '$ai')
1348
1347
  return new Set();
1349
1348
  if (this.type === '$provider')
1350
1349
  return new Set(['$ai']);
1351
- if (this.type === '$domain' || this.type === '$users')
1352
- return ENV_TYPES;
1353
- return ENV_TYPES;
1350
+ return null;
1354
1351
  }
1355
1352
 
1356
1353
  _isMainTreeLeaf() {
@@ -1362,8 +1359,11 @@ export class $folder extends $item{
1362
1359
  if (!Array.isArray(items) || !items.length)
1363
1360
  return items || [];
1364
1361
  const allowed = this._mainTreeAllowedTypes();
1365
- if (!allowed)
1366
- return items;
1362
+ if (!allowed) {
1363
+ if (!this.parent || this.type === '$folder')
1364
+ return items;
1365
+ return items.filter(it => it && it.id?.[0] !== '$' && !it.DATA?.objects);
1366
+ }
1367
1367
  if (allowed.size === 0)
1368
1368
  return [];
1369
1369
  return items.filter(it => {
@@ -99,6 +99,9 @@ export class $user extends $class {
99
99
  }
100
100
 
101
101
  async allowAccess(params) {
102
+ await this.init;
103
+ if (this.DATA?.usersContainer === true)
104
+ return super.allowAccess(params);
102
105
  // WORK_DEV снимает все проверки видимости — и доступ к кабинету тоже (как canSee/canWrite)
103
106
  if (DEV_MODE)
104
107
  return true;
@@ -1,4 +0,0 @@
1
- export default {
2
- label: 'Пользователи',
3
- icon: 'social:people',
4
- };