odant-work 1.0.100 → 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.
@@ -3,4 +3,5 @@ export default{
3
3
  isSystem: true,
4
4
  allowRoles: false,
5
5
  allowTypes: '',
6
+ mainTreeChildren: [],
6
7
  }
@@ -1,8 +1,11 @@
1
1
  import '/sources/modules/user-profile/user-profile.js';
2
2
  export default {
3
- label: 'Профиль и токены',
3
+ label: 'Профиль',
4
4
  icon: 'icons:account-circle',
5
5
  order: 15,
6
+ allowUse($context) {
7
+ return !$context?.DATA?.usersContainer;
8
+ },
6
9
  component: {
7
10
  template: /* html */`
8
11
  <style>
@@ -12,7 +15,7 @@ export default {
12
15
  overflow: hidden;
13
16
  }
14
17
  </style>
15
- <user-profile flex></user-profile>
18
+ <user-profile :$item flex></user-profile>
16
19
  `
17
20
  }
18
21
  };
@@ -0,0 +1,24 @@
1
+ import '/sources/modules/user-profile/user-tokens.js';
2
+ export default {
3
+ label: 'Токены',
4
+ icon: 'communication:vpn-key',
5
+ order: 18,
6
+ allowUse($context, params) {
7
+ if (!$context?.id || $context?.DATA?.usersContainer)
8
+ return false;
9
+ const uid = $context?.constructor?.resolveUid?.(params) || params?.session?.uid || '';
10
+ return Boolean(uid && $context.id === uid);
11
+ },
12
+ component: {
13
+ template: /* html */`
14
+ <style>
15
+ :host {
16
+ @apply --vertical;
17
+ @apply --flex;
18
+ overflow: hidden;
19
+ }
20
+ </style>
21
+ <user-tokens :$item flex></user-tokens>
22
+ `
23
+ }
24
+ };
@@ -0,0 +1,213 @@
1
+ export default {
2
+ label: 'Пользователи',
3
+ icon: 'social:people',
4
+ order: 15,
5
+ default: true,
6
+ allowUse($context) {
7
+ return Boolean($context?.DATA?.usersContainer);
8
+ },
9
+ component: {
10
+ imports: 'oda//icon, oda//button',
11
+ template: /* html */`
12
+ <style>
13
+ :host {
14
+ @apply --vertical;
15
+ @apply --flex;
16
+ overflow: auto;
17
+ padding: 16px;
18
+ gap: 12px;
19
+ box-sizing: border-box;
20
+ background: var(--content-background);
21
+ color: var(--content-color);
22
+ }
23
+ .header {
24
+ @apply --horizontal-center;
25
+ gap: 10px;
26
+ flex-wrap: wrap;
27
+ }
28
+ .search {
29
+ flex: 1 1 220px;
30
+ min-width: 180px;
31
+ padding: 7px 10px;
32
+ border-radius: 8px;
33
+ border: 1px solid var(--subtle-border, #cbd5e1);
34
+ background: var(--content-background);
35
+ color: var(--content-color);
36
+ font-size: 13.5px;
37
+ box-sizing: border-box;
38
+ }
39
+ .count {
40
+ font-size: 12.5px;
41
+ opacity: 0.72;
42
+ }
43
+ .list {
44
+ @apply --vertical;
45
+ gap: 8px;
46
+ }
47
+ .row {
48
+ @apply --horizontal-center;
49
+ gap: 10px;
50
+ padding: 8px 12px;
51
+ border-radius: 10px;
52
+ border: 1px solid var(--subtle-border, #e2e8f0);
53
+ cursor: pointer;
54
+ transition: border-color .12s ease, background .12s ease;
55
+ }
56
+ .row:hover {
57
+ border-color: var(--accent-color, #4f46e5);
58
+ background: color-mix(in oklch, var(--accent-back, #4f46e5) 6%, transparent);
59
+ }
60
+ .row[disabled-user] {
61
+ opacity: 0.58;
62
+ }
63
+ .meta {
64
+ @apply --vertical;
65
+ flex: 1;
66
+ min-width: 0;
67
+ gap: 2px;
68
+ }
69
+ .title {
70
+ font-size: 14px;
71
+ font-weight: 600;
72
+ overflow: hidden;
73
+ text-overflow: ellipsis;
74
+ white-space: nowrap;
75
+ }
76
+ .sub {
77
+ font-size: 12px;
78
+ opacity: 0.72;
79
+ overflow: hidden;
80
+ text-overflow: ellipsis;
81
+ white-space: nowrap;
82
+ }
83
+ .badge {
84
+ font-size: 11.5px;
85
+ padding: 2px 8px;
86
+ border-radius: 999px;
87
+ border: 1px solid var(--subtle-border, #cbd5e1);
88
+ }
89
+ .badge.off {
90
+ color: var(--error-color, #dc2626);
91
+ border-color: color-mix(in srgb, var(--error-color, #dc2626) 45%, transparent);
92
+ }
93
+ .toggle-btn {
94
+ padding: 4px 10px;
95
+ border-radius: 6px;
96
+ border: 1px solid var(--subtle-border, #cbd5e1);
97
+ background: transparent;
98
+ color: inherit;
99
+ cursor: pointer;
100
+ font-size: 12px;
101
+ }
102
+ .toggle-btn:hover {
103
+ border-color: var(--accent-color, #4f46e5);
104
+ }
105
+ </style>
106
+ <div class="header">
107
+ <input class="search" placeholder="Поиск по имени, email или uid…" ::value="query">
108
+ <span class="count">Всего: {{filtered.length}}</span>
109
+ </div>
110
+ <div ~if="loading" class="count">Загрузка пользователей…</div>
111
+ <div ~if="!loading && !filtered.length" class="count">Пользователи не найдены</div>
112
+ <div ~if="!loading && filtered.length" class="list">
113
+ <div ~for="filtered" class="row" :disabled-user="!$for.item.enabled" @tap="openUser($for.item)">
114
+ <oda-icon round :icon="$for.item.icon || 'icons:account-circle'" :icon-color="$for.item.iconColor" icon-size="32"></oda-icon>
115
+ <div class="meta">
116
+ <span class="title">{{$for.item.label}}</span>
117
+ <span class="sub">{{$for.item.email ? ($for.item.email + ' · ') : ''}}{{$for.item.id}}</span>
118
+ </div>
119
+ <span ~if="!$for.item.enabled" class="badge off">Отключён</span>
120
+ <span ~if="$for.item.enabled" class="badge">Активен</span>
121
+ <button ~if="canToggle && $for.item.id !== selfUid" type="button" class="toggle-btn" @tap.stop="toggleEnabled($for.item)">
122
+ {{$for.item.enabled ? 'Отключить' : 'Включить'}}
123
+ </button>
124
+ </div>
125
+ </div>
126
+ `,
127
+ $item: {
128
+ $def: null,
129
+ set(n, o) {
130
+ if (o && this._onChanged)
131
+ o.unlisten?.('changed', this._onChanged);
132
+ if (n) {
133
+ this._onChanged ??= () => this.debounce?.('users-reload', () => this.reload(), 200) ?? this.reload();
134
+ n.listen?.('changed', this._onChanged);
135
+ this.reload();
136
+ }
137
+ }
138
+ },
139
+ users: [],
140
+ loading: false,
141
+ canToggle: false,
142
+ query: '',
143
+ get selfUid() {
144
+ return WORK?.uid || '';
145
+ },
146
+ get filtered() {
147
+ const q = String(this.query || '').trim().toLowerCase();
148
+ if (!q)
149
+ return this.users || [];
150
+ return (this.users || []).filter(u =>
151
+ String(u.label || '').toLowerCase().includes(q)
152
+ || String(u.email || '').toLowerCase().includes(q)
153
+ || String(u.id || '').toLowerCase().includes(q)
154
+ );
155
+ },
156
+ async reload() {
157
+ if (!this.$item)
158
+ return;
159
+ this.loading = true;
160
+ try {
161
+ this.canToggle = Boolean(WORK?.DEV_MODE || await globalThis.WORK?.isBoss?.catch?.(() => false));
162
+ const raw = (await this.$item.items) || [];
163
+ const list = [];
164
+ for (const u of raw) {
165
+ if (!u || !u.id || u.id.startsWith('$'))
166
+ continue;
167
+ try { await u.init; } catch {}
168
+ const d = u.DATA || {};
169
+ list.push({
170
+ id: u.id,
171
+ label: u.label || d.label || d.email || u.id,
172
+ email: d.email || '',
173
+ icon: u.icon || d.icon || '',
174
+ iconColor: u.iconColor || '',
175
+ enabled: d.enabled !== false && d.blocked !== true,
176
+ item: u,
177
+ });
178
+ }
179
+ list.sort((a, b) => String(a.label).localeCompare(String(b.label), 'ru'));
180
+ this.users = list;
181
+ }
182
+ catch {
183
+ this.users = [];
184
+ }
185
+ finally {
186
+ this.loading = false;
187
+ }
188
+ },
189
+ openUser(entry) {
190
+ if (!entry?.item)
191
+ return;
192
+ const exec = top?.execute || window.execute;
193
+ exec?.(entry.item, { view: 'system/profile' });
194
+ },
195
+ async toggleEnabled(entry) {
196
+ if (!entry?.item || !this.canToggle)
197
+ return;
198
+ const next = !entry.enabled;
199
+ try {
200
+ const res = await entry.item.fetch('set_enabled', { enabled: next });
201
+ entry.enabled = res?.enabled !== false;
202
+ this.users = [...this.users];
203
+ }
204
+ catch (e) {
205
+ console.warn('[users] set_enabled:', e?.message || e);
206
+ }
207
+ },
208
+ detached() {
209
+ if (this.$item && this._onChanged)
210
+ this.$item.unlisten?.('changed', this._onChanged);
211
+ }
212
+ }
213
+ };
@@ -138,7 +138,16 @@ export default {
138
138
  icon: user?.icon || 'icons:account-circle',
139
139
  default: 'icons:account-circle',
140
140
  style: `color: white; fill: white; background:${user?.iconColor || 'transparent'}`,
141
- click: () => {
141
+ click: async () => {
142
+ if (WORK?.uid) {
143
+ const userNode = WORK.USER || await WORK.get_$user?.(WORK.uid).catch(() => null);
144
+ if (userNode) {
145
+ this._autoOpenedLogin = false;
146
+ this.visibleMode = 'main';
147
+ window.execute?.(userNode, { view: 'system/profile' });
148
+ return;
149
+ }
150
+ }
142
151
  this.showUser = true;
143
152
  },
144
153
  errorInvert: !WORK.uid,
@@ -717,6 +726,7 @@ export default {
717
726
  }
718
727
  }
719
728
  else {
729
+ this._autoOpenedLogin = true;
720
730
  this.showUser = true;
721
731
  }
722
732
  }
@@ -726,6 +736,7 @@ export default {
726
736
  this.async(async ()=>{
727
737
  await this._handleInviteQuery();
728
738
  if(!WORK.uid && !WORK.DEV_MODE){
739
+ this._autoOpenedLogin = true;
729
740
  this.visibleMode = 'user';
730
741
  if(this.left_drawer)
731
742
  this.left_drawer.closed = true;
@@ -763,6 +774,12 @@ export default {
763
774
  }
764
775
  WORK.authEvents?.addEventListener('auth', () => {
765
776
  this.user_icon = undefined;
777
+ if (WORK.uid && this._autoOpenedLogin && this.visibleMode === 'user') {
778
+ this._autoOpenedLogin = false;
779
+ this.visibleMode = 'main';
780
+ if (this.left_drawer)
781
+ this.left_drawer.closed = false;
782
+ }
766
783
  this._refreshLeftButtons();
767
784
  this._initTopLicenseBanner();
768
785
  this._refreshSupportBadge();
@@ -6,7 +6,6 @@ function rawItem(it) {
6
6
  return it?.[R]?.target || it;
7
7
  }
8
8
 
9
- const MAIN_TREE_ENV_TYPES = new Set(['$domain', '$structure', '$project', '$module', '$provider', '$mcp', '$users', '$user', '$node', '$ai']);
10
9
  const MAIN_TREE_LEAF_TYPES = new Set(['$module', '$mcp', '$user', '$ai']);
11
10
 
12
11
  function isRootSectionNode(it) {
@@ -51,14 +50,14 @@ function filterMainTreeItems(items, parent) {
51
50
  if (parent.type === '$folder')
52
51
  return items;
53
52
  if (isRootSectionNode(parent))
54
- return items.filter(f => f && MAIN_TREE_ENV_TYPES.has(f.type));
53
+ return items.filter(f => f && !f.DATA?.objects);
55
54
  if (isMainTreeLeaf(parent))
56
55
  return [];
57
56
  if (parent.type === '$project' || parent.type === '$structure')
58
57
  return items.filter(f => f && (f.type === '$structure' || f.type === '$project'));
59
58
  if (parent.type === '$provider')
60
59
  return items.filter(f => f?.type === '$ai');
61
- return items.filter(f => f && MAIN_TREE_ENV_TYPES.has(f.type));
60
+ return items.filter(f => f && !f.DATA?.objects);
62
61
  }
63
62
 
64
63
  /**
@@ -2,6 +2,7 @@ export default {
2
2
  label: 'Модули',
3
3
  icon: 'odant:folder',
4
4
  form: 'system',
5
+ container: true,
5
6
  mainTreeChildren: ['$folder', '$module', '$provider', '$mcp'],
6
7
  ACCESS: {
7
8
  mcp_catalog: 'read',
@@ -10,6 +10,7 @@ export default {
10
10
  label: 'Local',
11
11
  protocol: 'local',
12
12
  form: 'system',
13
+ allowAllUsers: true,
13
14
  mainTreeChildren: ['$ai'],
14
15
  baseUrl: 'http://127.0.0.1:8731/v1/chat/completions',
15
16
  }
@@ -2,4 +2,7 @@ export default {
2
2
  label: 'Пользователи',
3
3
  icon: 'social:people',
4
4
  allowTypes: '$user',
5
- }
5
+ usersContainer: true,
6
+ allowRoles: false,
7
+ mainTreeChildren: ['$user'],
8
+ };
package/oda/oda.js CHANGED
@@ -356,13 +356,27 @@ localStorage: {
356
356
  }
357
357
  this.save();
358
358
  }
359
- save() {
359
+ save(sync = false) {
360
360
  if (this._value === undefined)
361
361
  return;
362
+ if (sync) {
363
+ this.flush();
364
+ return;
365
+ }
362
366
  this.debounce('saveToLocalStorage',()=>{
363
367
  globalThis.localStorage.setItem(this.path, JSON.stringify(this.value));
364
368
  })
365
369
  }
370
+ flush() {
371
+ if (this._value === undefined)
372
+ return;
373
+ const dbKey = 'saveToLocalStorage.0';
374
+ if (this.__debounces__?.[dbKey]) {
375
+ clearTimeout(this.__debounces__[dbKey]);
376
+ delete this.__debounces__[dbKey];
377
+ }
378
+ globalThis.localStorage.setItem(this.path, JSON.stringify(this.value));
379
+ }
366
380
  get version() {
367
381
  return this.value.$$stamp;
368
382
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.100",
3
+ "version": "1.0.101",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
package/readme.md CHANGED
@@ -114,7 +114,7 @@ WORK решает проблему управления организацион
114
114
  | `/MODULES/` | Эталонные модули и внешние коннекторы (`Register`, `Geo`, `KLADR`, `Process`, `1C`, `Bitrix24`, `Telegram`, `DaData`, …) — предки для модулей организаций |
115
115
  | `/MODELS/` | Встроенный источник ИИ: локальные (`Local`) и внешние провайдеры/модели (`$provider`, `$ai`), дообучение и профилировщик железа |
116
116
  | `/NODES/` | Карта адресов внешних серверов WORK (федерация серверов) |
117
- | `/USERS/` | Пользователи (класс `$users`, личные кабинеты `$user`) |
117
+ | `/USERS/` | Пользователи (класс `$user`, личные кабинеты `$user`) |
118
118
  | `tests/`, `docs/` | Автотесты, контрольные задания (`tests/eval`) и проектная документация (`docs/architecture.md` — канон) |
119
119
 
120
120
  ## 5. В каком это состоянии
package/sources/client.js CHANGED
@@ -5,6 +5,7 @@ import { Reactor } from "./reactor.js";
5
5
  import { RTCCaller } from "./modules/call/call.js";
6
6
  import "./modules/user-profile/user-profile.js";
7
7
  import "./modules/user-profile/user-token.js";
8
+ import "./modules/user-profile/user-tokens.js";
8
9
  window.RTCCaller = RTCCaller;
9
10
  class WORK_ServerError extends Error{}
10
11
  window.CORE = CORE;
@@ -437,53 +438,85 @@ WORK.login = async function(force = false){
437
438
  WORK.credentials = window.top.WORK.credentials;
438
439
  WORK.uid = window.top.WORK.uid || '';
439
440
  WORK.USER = window.top.WORK.USER;
441
+ WORK._loginError = null;
440
442
  return res;
441
443
  }
442
444
  }
443
- catch { /* cross-origin fallback */ }
445
+ catch (err) {
446
+ if (!err || err.name === 'SecurityError') { /* cross-origin fallback */ }
447
+ else {
448
+ WORK._loginError = err;
449
+ throw err;
450
+ }
451
+ }
444
452
  }
445
453
  if (!force && WORK._loginPromise && WORK._loginTargetUid === nextUid)
446
454
  return WORK._loginPromise;
447
455
  WORK._loginTargetUid = nextUid;
448
- return WORK._loginPromise = (async () => {
449
- WORK.credentials = nextCreds;
450
- let KEY = secure.getItem('KEY');
451
- let uid = WORK.credentials?.uid;
452
- if(uid && KEY){
453
- if (WORK.uid && WORK.uid !== uid)
456
+ WORK._loginError = null;
457
+ WORK._loginInProgress = true;
458
+ try {
459
+ WORK.authEvents?.dispatchEvent?.(new CustomEvent('login-state', { detail: { pending: true, error: null } }));
460
+ } catch {}
461
+ const run = (async () => {
462
+ try {
463
+ WORK.credentials = nextCreds;
464
+ let KEY = secure.getItem('KEY');
465
+ let uid = WORK.credentials?.uid;
466
+ if(uid && KEY){
467
+ if (WORK.uid && WORK.uid !== uid)
468
+ await WORK.removeCurrentPushSubscription?.();
469
+ let challengeId = crypto.randomUUID();
470
+ const challenge = await WORK.fetch("/", 'user_login_start', { uid, challengeId});
471
+ KEY = Uint8Array.from(atob(KEY), c => c.charCodeAt(0));
472
+ let privateKey = await crypto.subtle.importKey("pkcs8", KEY, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, true, ["sign"]);
473
+ let signature = await crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, privateKey, new TextEncoder().encode(challenge));
474
+ signature = WORK.arrayBufferToBase64(signature);
475
+ let pendingInviteToken = '';
476
+ try { pendingInviteToken = sessionStorage.getItem('work.pendingInviteToken') || ''; } catch { /* ignore */ }
477
+ const res = await WORK.fetch("/", 'user_login_finish' , { uid, time: WORK.credentials.time, challengeId}, {signature, ...(pendingInviteToken ? { inviteToken: pendingInviteToken } : {})});
478
+ if (pendingInviteToken) {
479
+ try { sessionStorage.removeItem('work.pendingInviteToken'); } catch { /* ignore */ }
480
+ }
481
+ WORK.uid = uid;
482
+ WORK._loginError = null;
483
+ WORK._anonExitSynced = false;
484
+ await WORK.syncAuthUI();
485
+ WORK.refreshChatUnread?.();
486
+ WORK.notifyAuth?.({ uid, reason: 'login' });
487
+ return res;
488
+ }
489
+ const hadAuth = Boolean(WORK.uid);
490
+ if (WORK.uid)
454
491
  await WORK.removeCurrentPushSubscription?.();
455
- let challengeId = crypto.randomUUID();
456
- const challenge = await WORK.fetch("/", 'user_login_start', { uid, challengeId});
457
- KEY = Uint8Array.from(atob(KEY), c => c.charCodeAt(0));
458
- let privateKey = await crypto.subtle.importKey("pkcs8", KEY, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, true, ["sign"]);
459
- let signature = await crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, privateKey, new TextEncoder().encode(challenge));
460
- signature = WORK.arrayBufferToBase64(signature);
461
- let pendingInviteToken = '';
462
- try { pendingInviteToken = sessionStorage.getItem('work.pendingInviteToken') || ''; } catch { /* ignore */ }
463
- const res = await WORK.fetch("/", 'user_login_finish' , { uid, time: WORK.credentials.time, challengeId}, {signature, ...(pendingInviteToken ? { inviteToken: pendingInviteToken } : {})});
464
- if (pendingInviteToken) {
465
- try { sessionStorage.removeItem('work.pendingInviteToken'); } catch { /* ignore */ }
492
+ WORK.uid = '';
493
+ WORK._loginError = null;
494
+ WORK.USER = undefined;
495
+ WORK.chatUnread = { total: 0, byThread: {}, byNode: {}, byPeer: {} };
496
+ if (hadAuth || !WORK._anonExitSynced) {
497
+ WORK._anonExitSynced = true;
498
+ await WORK.fetch("/", 'user_exit', {}, {}).catch(() => {});
466
499
  }
467
- WORK.uid = uid;
468
- WORK._anonExitSynced = false;
469
500
  await WORK.syncAuthUI();
470
- WORK.refreshChatUnread?.();
471
- WORK.notifyAuth?.({ uid, reason: 'login' });
472
- return res;
501
+ WORK.notifyAuth?.({ uid: '', reason: 'logout' });
502
+ }
503
+ catch (err) {
504
+ WORK._loginError = err;
505
+ if (WORK._loginPromise === run)
506
+ WORK._loginPromise = null;
507
+ throw err;
473
508
  }
474
- const hadAuth = Boolean(WORK.uid);
475
- if (WORK.uid)
476
- await WORK.removeCurrentPushSubscription?.();
477
- WORK.uid = '';
478
- WORK.USER = undefined;
479
- WORK.chatUnread = { total: 0, byThread: {}, byNode: {}, byPeer: {} };
480
- if (hadAuth || !WORK._anonExitSynced) {
481
- WORK._anonExitSynced = true;
482
- await WORK.fetch("/", 'user_exit', {}, {}).catch(() => {});
509
+ finally {
510
+ WORK._loginInProgress = false;
511
+ try {
512
+ WORK.authEvents?.dispatchEvent?.(new CustomEvent('login-state', {
513
+ detail: { pending: false, error: WORK._loginError || null, uid: WORK.uid || '' }
514
+ }));
515
+ } catch {}
483
516
  }
484
- await WORK.syncAuthUI();
485
- WORK.notifyAuth?.({ uid: '', reason: 'logout' });
486
517
  })();
518
+ WORK._loginPromise = run;
519
+ return run;
487
520
  }
488
521
  WORK.applyChatReadLocal = function ({ threadId = '', kind = '', nodePath = '', peerId = '' } = {}) {
489
522
  const u = WORK.chatUnread;
@@ -608,7 +641,7 @@ class WebSocketEvents {
608
641
  onopen(e) {
609
642
  this.send(JSON.stringify(Object.keys(CORE.$item.ITEMS)));
610
643
  WORK.connected = true;
611
- WORK.login();
644
+ WORK.login().catch(() => {});
612
645
  }
613
646
  onclose(e) {
614
647
  WORK.connected = false;
@@ -378,12 +378,20 @@ export const authMethods = {
378
378
  const uid = String(rawUid || '').trim().toUpperCase();
379
379
  if (!UID_RE.test(uid))
380
380
  throw new Error("uid required");
381
- if (session.uid !== uid) {
381
+ const challengeKey = challengeId != null ? String(challengeId) : '';
382
+ if (session.uid === uid) {
383
+ if (challengeKey) {
384
+ const entry = pendingLogins.get(challengeKey);
385
+ if (entry?.uid === uid)
386
+ pendingLogins.delete(challengeKey);
387
+ }
388
+ }
389
+ else {
382
390
  let signature = params.post?.signature;
383
391
  if (!signature) throw new Error("login session break. Need signature.");
384
- const challengeEntry = pendingLogins.get(String(challengeId));
392
+ const challengeEntry = pendingLogins.get(challengeKey);
385
393
  if (!challengeEntry) throw new Error("login session break. Challenge expired or missing.");
386
- pendingLogins.delete(String(challengeId));
394
+ pendingLogins.delete(challengeKey);
387
395
  const challengeValue = challengeEntry.value ?? challengeEntry;
388
396
  if (!challengeEntry.expiresAt || Date.now() > challengeEntry.expiresAt)
389
397
  throw new Error("login session break. Challenge expired.");
@@ -477,6 +485,9 @@ export const authMethods = {
477
485
  }
478
486
  const affected = Object.values($server.sessions).filter(s => s.uid === uid);
479
487
  this.constructor.clearAllSessionsForUid(uid);
488
+ for (const [id, c] of pendingLogins)
489
+ if (c?.uid === uid)
490
+ pendingLogins.delete(id);
480
491
  const { time } = params.post || {};
481
492
  if (time)
482
493
  delete session[time];
@@ -87,7 +87,7 @@ export function kindOf(p) {
87
87
  if (name === 'class.js') {
88
88
  const meta = segs[segs.length - 2];
89
89
  const owner = segs[segs.length - 3];
90
- if (meta === '$handler' || meta === '$method' || meta === '$trigger')
90
+ if (meta === '$handler' || segs.includes('handlers'))
91
91
  return null;
92
92
  if (meta?.[0] === '$' && (owner === undefined || owner[0] !== '$'))
93
93
  return 'class';
@@ -56,62 +56,72 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
56
56
  </div>
57
57
  <div vertical style="gap: 16px; align-items: center;">
58
58
  <div class="photo" vertical style="padding: 16px; border-radius: 50%;">
59
- <oda-icon :icon="photoIcon" round @tap="loadPhoto" style="border-radius: 50%; fill: white; color: white;" icon-size="180"></oda-icon>
59
+ <oda-icon :icon="photoIcon" round @tap="!isOtherUser && loadPhoto()" style="border-radius: 50%; fill: white; color: white;" icon-size="180"></oda-icon>
60
60
  </div>
61
- <input id="name" placeholder="Имя" ::value="params.name" name="name">
62
- <input id="surname" placeholder="Фамилия" ::value="params.surname" name="surname">
63
- <input id="patronymic" placeholder="Отчество" ::value="params.patronymic" name="patronymic">
64
- <input id="email" :disabled="isLogin || showCode" placeholder="Email" ::value="params.email" type="email" name="email" :error="!correctEmail" :success="correctEmail">
65
- <oda-otp-input ~if="showCode" center @complete="_onCode"></oda-otp-input>
66
- <button ~if="state.label && !showCode" center horizontal :disabled="!correctEmail" flex raised :class="state.class" @tap.stop.prevent="register_start" style="gap: 8px;align-items: center;">
61
+ <input id="name" :disabled="isOtherUser" placeholder="Имя" ::value="params.name" name="name">
62
+ <input id="surname" :disabled="isOtherUser" placeholder="Фамилия" ::value="params.surname" name="surname">
63
+ <input id="patronymic" :disabled="isOtherUser" placeholder="Отчество" ::value="params.patronymic" name="patronymic">
64
+ <input id="email" :disabled="isOtherUser || isLogin || showCode" placeholder="Email" ::value="params.email" type="email" name="email" :error="!correctEmail" :success="correctEmail">
65
+ <oda-otp-input ~if="!isOtherUser && showCode" center @complete="_onCode"></oda-otp-input>
66
+ <button ~if="!isOtherUser && state.label && !showCode" center horizontal :disabled="!correctEmail" flex raised :class="state.class" @tap.stop.prevent="register_start" style="gap: 8px;align-items: center;">
67
67
  <span>{{state.label}}</span>
68
68
  <oda-icon ~if="state.icon" :icon="state.icon"></oda-icon>
69
69
  </button>
70
- <div ~if="isLogin && state?.name === 'ok' && !showCode" vertical style="gap: 8px; width: 100%; border-top: 1px solid rgba(128,128,128,.3); padding-top: 12px; margin-top: 4px;">
71
- <div style="font-size: medium; font-weight: 600; text-align: center;">Подключения</div>
72
- <button center horizontal flex @tap.stop.prevent="mcp_token" title="Один токен для внешних ИИ-клиентов (MCP) и расширения WORK Chrome Bridge">
73
- <span>Токен для подключения</span>
74
- </button>
75
- <div style="font-size: small; text-align: center; opacity: 0.75; line-height: 1.35;">
76
- Этот же токен вместе с адресом WORK вводится в расширении <b>WORK Chrome Bridge</b> и MCP-клиентах.
77
- </div>
78
- <button center horizontal flex @tap.stop.prevent="mcp_list" title="Список токенов: срок жизни, последнее использование, отзыв по одному">
79
- <span>Список токенов…</span>
80
- </button>
81
- <div ~if="mcpList" vertical style="gap: 8px; width: 100%;">
82
- <div ~if="!mcpList.length" style="font-size: small; text-align: center;">токенов нет</div>
83
- <div ~for="mcpList" horizontal style="gap: 8px; align-items: center; justify-content: space-between; border: 1px solid gray; border-radius: 8px; padding: 4px 8px;">
84
- <span flex>{{$for.item.label}}{{$for.item.role ? ' (' + $for.item.role + ')' : ''}}</span>
85
- <span no-flex style="font-size: small;">{{$for.item.expired ? 'истёк' : 'до ' + fmtDate($for.item.expires)}} · был{{fmtDate($for.item.lastUsed)}}</span>
86
- <button no-flex style="height: 32px; font-size: medium;" @tap.stop.prevent="mcp_revoke_one($for.item.id)">Отозвать</button>
87
- </div>
88
- </div>
89
- <button center horizontal flex @tap.stop.prevent="mcp_revoke">
90
- <span>Отозвать все токены</span>
91
- </button>
92
- </div>
93
70
  </div>
94
71
  <div flex style="text-align: center;" ~html="state.legend"></div>
95
72
  <div flex style="text-align: center;" :error="!!error" @tap="fill_code">{{text}}</div>
96
73
  </div>
97
74
  `,
75
+ $item: {
76
+ $def: null,
77
+ set(n) {
78
+ this._syncFromItem(n);
79
+ }
80
+ },
98
81
  error: null,
99
82
  text: '',
83
+ isLoggingIn: false,
84
+ get isOtherUser() {
85
+ return Boolean(this.$item?.id && WORK?.uid && this.$item.id !== WORK.uid);
86
+ },
87
+ get hasKey() {
88
+ return Boolean(this.credentials?.uid && this.workSecure.getItem('KEY'));
89
+ },
100
90
  get state(){
101
- if(!this.isRegistered || this.error)
91
+ if (this.isOtherUser) {
92
+ const targetUid = this.$item?.id || this.params?.uid || '';
93
+ const enabled = this.$item?.DATA?.enabled !== false;
94
+ return {
95
+ name: 'other',
96
+ label: '',
97
+ legend: (targetUid ? ('uid: ' + targetUid) : '') + (enabled ? '' : ' · <b>Отключён</b>'),
98
+ class: 'info-invert'
99
+ };
100
+ }
101
+ const errMsg = String(this.error?.message || this.error || '');
102
+ const keyRejected = /user not registered|need publickey|login failed|challenge issued for another user/i.test(errMsg);
103
+ if(!this.isRegistered || !this.hasKey || keyRejected)
102
104
  return {
103
105
  name: 'unregistered',
104
106
  label: 'Register KEY',
105
107
  legend: 'Для входа в систему необходимо зарегистрировать ключ безопасности. <p>Ключ будет создан на Вашем устройстве, и привязан к адресу электронной почты.',
106
108
  class: 'success-invert'
107
109
  }
108
- if(!this.isLogin)
110
+ if(!this.isLogin) {
111
+ if (this.isLoggingIn)
112
+ return {
113
+ name: 'logging-in',
114
+ label: '',
115
+ legend: 'Выполняется вход в систему…',
116
+ class: 'info-invert'
117
+ }
109
118
  return {
110
- name: 'need-check',
111
- label: 'Check KEY',
112
- legend: 'Вы не вошли в систему, требуется проверка ключа.',
113
- class: 'error-invert'
119
+ name: 'need-login',
120
+ label: 'Войти',
121
+ legend: 'Для входа в систему нажмите «Войти».',
122
+ class: 'success-invert'
114
123
  }
124
+ }
115
125
  if(this.isChanged)
116
126
  return {
117
127
  name: 'changed',
@@ -194,8 +204,57 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
194
204
  },
195
205
 
196
206
  attached() {
197
- this.credentials = this.workSecure.getItem('credentials');
207
+ this._syncFromItem(this.$item);
198
208
  this._loadPendingInvite();
209
+ this._onAuthState = () => {
210
+ if (this.isOtherUser)
211
+ return;
212
+ this.isLoggingIn = Boolean(WORK._loginInProgress);
213
+ if (WORK._loginError) {
214
+ this.error = WORK._loginError;
215
+ this.text = WORK._loginError?.message || String(WORK._loginError);
216
+ }
217
+ else if (this.isLogin) {
218
+ this.error = null;
219
+ this.text = '';
220
+ }
221
+ this.isLogin = undefined;
222
+ this.render?.();
223
+ };
224
+ WORK.authEvents?.addEventListener?.('auth', this._onAuthState);
225
+ WORK.authEvents?.addEventListener?.('login-state', this._onAuthState);
226
+ },
227
+ detached() {
228
+ if (this._onAuthState) {
229
+ WORK.authEvents?.removeEventListener?.('auth', this._onAuthState);
230
+ WORK.authEvents?.removeEventListener?.('login-state', this._onAuthState);
231
+ }
232
+ },
233
+ async _syncFromItem(item) {
234
+ if (item?.id && WORK?.uid && item.id !== WORK.uid) {
235
+ try { await item.init; } catch {}
236
+ const d = item.DATA || {};
237
+ this.credentials = null;
238
+ this.params = {
239
+ ...this.params,
240
+ uid: item.id,
241
+ name: d.name || '',
242
+ surname: d.surname || '',
243
+ patronymic: d.patronymic || '',
244
+ email: d.email || '',
245
+ icon: item.icon || d.icon || '',
246
+ };
247
+ this.error = null;
248
+ this.text = '';
249
+ this.showCode = false;
250
+ return;
251
+ }
252
+ this.credentials = this.workSecure.getItem('credentials');
253
+ this.isLoggingIn = Boolean(WORK._loginInProgress);
254
+ if (WORK._loginError) {
255
+ this.error = WORK._loginError;
256
+ this.text = WORK._loginError?.message || String(WORK._loginError);
257
+ }
199
258
  },
200
259
  pendingInvite: null,
201
260
  pendingInviteToken: '',
@@ -255,78 +314,12 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
255
314
  },
256
315
  reg: null,
257
316
  showCode: false,
258
- mcpList: null,
259
- fmtDate(ms) {
260
- return ms ? new Date(ms).toLocaleDateString() : '—';
261
- },
262
- /** Список токенов MCP: подпись, срок жизни, последнее использование; каждый можно отозвать отдельно. */
263
- async mcp_list() {
264
- this.mcpList = this.mcpList ? null : await WORK.fetch('/', 'mcp_token_list', {}, {});
265
- },
266
- async mcp_revoke_one(id) {
267
- try {
268
- await WORK.showConfirm('Отозвать этот токен? Подключённый клиент перестанет работать.');
269
- }
270
- catch { return; }
271
- try {
272
- await WORK.fetch('/', 'mcp_token_revoke', {}, { id });
273
- this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
274
- }
275
- catch (e) {
276
- this.text = e.message;
277
- }
278
- },
279
317
  get workSecure() {
280
318
  return ODA.LocalStorage.create('work-secure');
281
319
  },
282
- /** Токен подключения (MCP и WORK Chrome Bridge): выпускается вошедшим пользователем, показывается один раз. */
283
- async mcp_token() {
284
- try {
285
- await WORK.showConfirm('Выпустить персональный токен для подключения (WORK Chrome Bridge, OpenCode, Claude Code…)? Он даёт доступ к WORK с вашими правами и покажется один раз.');
286
- }
287
- catch { return; }
288
- try {
289
- const r = await WORK.fetch('/', 'mcp_token_create', {}, { label: 'Подключение (MCP / Chrome)' });
290
- if (this.mcpList)
291
- this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
292
- if (typeof WORK.showModal === 'function') {
293
- const dlg = ODA.createComponent('user-token', {
294
- token: r.token,
295
- origin: location.origin,
296
- });
297
- try {
298
- await WORK.showModal(dlg, {
299
- TITLE: { label: 'Токен подключения' },
300
- allowClose: true,
301
- BUTTONS: [],
302
- });
303
- }
304
- catch { /* закрыли окно */ }
305
- }
306
- else {
307
- prompt('Токен подключения — скопируйте, повторно он не показывается.\nАдрес сервера: ' + location.origin + '\nАдрес MCP: ' + location.origin + '/mcp', r.token);
308
- }
309
- }
310
- catch (e) {
311
- this.text = e.message;
312
- }
313
- },
314
- async mcp_revoke() {
315
- try {
316
- await WORK.showConfirm('Отозвать все токены подключения? Подключённые внешние клиенты и Chrome Bridge перестанут работать.');
317
- }
318
- catch { return; }
319
- try {
320
- const r = await WORK.fetch('/', 'mcp_token_revoke', {}, { all: true });
321
- if (this.mcpList)
322
- this.mcpList = await WORK.fetch('/', 'mcp_token_list', {}, {});
323
- this.text = 'Токенов отозвано: ' + (r?.revoked ?? 0);
324
- }
325
- catch (e) {
326
- this.text = e.message;
327
- }
328
- },
329
320
  async register_start(e) {
321
+ if (this.isOtherUser)
322
+ return false;
330
323
  this.params.uid = await this.uid;
331
324
  switch (this.state?.name) {
332
325
  case 'ok': {
@@ -338,14 +331,16 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
338
331
  WORK.USER = undefined;
339
332
  WORK.credentials = this.workSecure.setItem('credentials', this.params);
340
333
  this.workSecure.setItem('KEY', null);
334
+ this.workSecure.flush?.();
341
335
 
342
336
  location.reload();
343
337
  } break;
344
- case 'need-check': {
345
- this.check();
338
+ case 'need-login': {
339
+ await this.check(true);
346
340
  } break;
347
341
  case 'changed':
348
342
  case 'unregistered': {
343
+ this.error = null;
349
344
  try {
350
345
  const registrationId = globalThis.crypto?.randomUUID?.() || WORK.genGUID?.() || (Date.now().toString(36) + Math.random().toString(36).slice(2));
351
346
  const regPayload = { ...this.params, registrationId, ...(this.pendingInviteToken ? { inviteToken: this.pendingInviteToken } : {}) };
@@ -364,7 +359,6 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
364
359
  }
365
360
  } break;
366
361
  }
367
- this.error = null;
368
362
  return true;
369
363
  },
370
364
  async _onCode(e) {
@@ -418,7 +412,8 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
418
412
  let privateKey = await window.crypto.subtle.exportKey("pkcs8", keyPair.privateKey);
419
413
  privateKey = WORK.arrayBufferToBase64(privateKey);
420
414
  this.workSecure.setItem('KEY', privateKey);
421
- await this.check();
415
+ this.workSecure.flush?.();
416
+ await this.check(true);
422
417
  this.credentials = this.params;
423
418
  this.isLogin = undefined;
424
419
  }
@@ -428,14 +423,24 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
428
423
  this.text = e.message;
429
424
  }
430
425
  },
431
- check() {
432
- return WORK.login().then(res => {
426
+ async check(force = false) {
427
+ this.isLoggingIn = true;
428
+ this.error = null;
429
+ this.text = 'Выполняется вход в систему…';
430
+ try {
431
+ const res = await WORK.login(force);
433
432
  this.error = null;
434
- this.text = res;
435
- }).catch(e => {
433
+ this.text = res || '';
434
+ return res;
435
+ }
436
+ catch (e) {
436
437
  this.error = e;
437
- this.text = e.message;
438
- });
438
+ this.text = e?.message || String(e || '');
439
+ return null;
440
+ }
441
+ finally {
442
+ this.isLoggingIn = Boolean(WORK._loginInProgress);
443
+ }
439
444
  }
440
445
  })
441
446
 
@@ -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
- };