odant-work 1.0.83 → 1.0.85

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,24 +3,84 @@
3
3
  * Хранятся в `#security` класса:
4
4
  * '#security': {
5
5
  * BOSS: [...], USER: [...],
6
- * LINKS: [{ id: '/ПУТЬ', access: 'read'|'write', scope?: 'own'|'place'|'unit'|'all' }], // общие ссылки — всем назначенным
7
- * ROLES: [{ id, label?, icon?, USERS: [...], LINKS: [...], ROLES: [...] }], // дерево должностей
6
+ * LINKS: [{ id: '/ПУТЬ', access: 'none'|'read'|'write'|'create'|'delete', scope?: 'own'|'place'|'unit'|'all' }],
7
+ * ROLES: [{ id, label?, icon?, USERS: [...], LINKS: [...], ROLES: [...] }],
8
8
  * }
9
+ * 4-уровневая накопительная модель доступа RWCD (+ явный запрет `none`):
10
+ * - none (0) — явный запрет (переопределяет унаследованное от родительской папки/класса право);
11
+ * - read (1, R) — чтение данных и отчётов;
12
+ * - write (2, W) — R + изменение существующих объектов и проведение/исправление/отмена операций;
13
+ * - create (3, C) — W + создание новых объектов и документов;
14
+ * - delete (4, D) — C + удаление и восстановление объектов.
15
+ * Внутри одной роли права проваливаются вниз по дереву классов и могут быть переопределены
16
+ * на любом дочернем классе вверх или вниз (вплоть до `none` — правило наиболее специфичного пути).
17
+ * Между несколькими ролями права объединяются по максимуму.
9
18
  * Псевдо-пользователи в `USERS`:
10
- * - 'USERS' — все зарегистрированные (вошедшие) пользователи;
19
+ * - 'USERS' — все зарегистрированные (вошедшие) пользователи своего сервера;
11
20
  * - 'GUESTS' — все внешние посетители (включая неавторизованных).
12
- * Правила:
13
- * - у прикладной роли нет зоны-папки и нет id системной роли (любой регистр, уникален в классе);
14
- * - назначение на любую прикладную роль делает пользователя участником (USER) подразделения;
15
- * - ссылка места действует своим access для его участников;
16
- * - вышестоящее место видит ссылки вложенных мест, но только на чтение;
17
- * - BOSS структуры видит и администрирует ссылки всех мест.
21
+ * Также в `USERS` могут быть:
22
+ * - локальное подразделение/организация/проект ('/ORGANIZATIONS/...', '/PROJECTS/...');
23
+ * - удалённый сервер сети (host_id или '/NODES/<Узел>');
24
+ * - удалённый пользователь ('/NODES/<Узел>/USERS/<uid>' или '<uid>@<host_id>');
25
+ * - удалённое подразделение/организация ('/NODES/<Узел>/ORGANIZATIONS/...', '/NODES/<Узел>/PROJECTS/...').
18
26
  * Чистые функции поверх объекта `#security` (без ввода-вывода).
19
27
  */
20
28
 
21
29
  /** Имена метапапок типов-структур (в них лежит class.js подразделения/организации/проекта). */
22
30
  export const STRUCTURE_META_NAMES = Object.freeze(['$structure', '$base', '$project', '$server']);
23
31
 
32
+ /** Допустимые уровни доступа на ссылке (RWCD + явный запрет none). */
33
+ export const ACCESS_LEVELS = Object.freeze(['none', 'read', 'write', 'create', 'delete']);
34
+
35
+ /** Числовой ранг уровней доступа (включая системный admin). */
36
+ export const ACCESS_RANK = Object.freeze({
37
+ none: 0,
38
+ read: 1,
39
+ write: 2,
40
+ create: 3,
41
+ delete: 4,
42
+ admin: 5,
43
+ });
44
+
45
+ const ACCESS_ALIASES = Object.freeze({
46
+ '0': 'none',
47
+ '-': 'none',
48
+ none: 'none',
49
+ '1': 'read',
50
+ r: 'read',
51
+ read: 'read',
52
+ '2': 'write',
53
+ w: 'write',
54
+ write: 'write',
55
+ '3': 'create',
56
+ c: 'create',
57
+ create: 'create',
58
+ '4': 'delete',
59
+ d: 'delete',
60
+ delete: 'delete',
61
+ });
62
+
63
+ /** Нормализовать значение уровня доступа в каноническую строку RWCD или null. */
64
+ export function normalizeAccess(raw) {
65
+ if (raw === undefined || raw === null)
66
+ return null;
67
+ const key = String(raw).trim().toLowerCase();
68
+ return ACCESS_ALIASES[key] || null;
69
+ }
70
+
71
+ /** Достаточен ли фактический уровень доступа `actual` для требуемого `required`. */
72
+ export function hasAccess(actual, required = 'read') {
73
+ const reqRank = ACCESS_RANK[required] || 0;
74
+ if (reqRank <= 0)
75
+ return true;
76
+ return (ACCESS_RANK[actual] || 0) >= reqRank;
77
+ }
78
+
79
+ /** Максимум из двух уровней доступа (admin > delete > create > write > read > none). */
80
+ export function maxAccess(a, b) {
81
+ return (ACCESS_RANK[b] || 0) > (ACCESS_RANK[a] || 0) ? b : a;
82
+ }
83
+
24
84
  /** Групповые псевдо-субъекты для назначения на рабочие места и в USER. */
25
85
  export const PSEUDO_USERS = Object.freeze({
26
86
  USERS: 'USERS',
@@ -34,7 +94,12 @@ export function isPseudoUser(id) {
34
94
 
35
95
  /** Проверка, является ли идентификатор путём структурного подразделения (/ORGANIZATIONS/...). */
36
96
  export function isNodeSubject(id) {
37
- return typeof id === 'string' && id.startsWith('/');
97
+ return typeof id === 'string' && id.startsWith('/') && !/^\/NODES(?:\/|$)/i.test(id);
98
+ }
99
+
100
+ /** Проверка, является ли идентификатор удалённым субъектом из /NODES/... */
101
+ export function isRemoteSubject(id) {
102
+ return typeof id === 'string' && /^\/NODES\/[^/]+(?:\/.*)?$/i.test(id);
38
103
  }
39
104
 
40
105
  function normNodePath(p) {
@@ -42,17 +107,84 @@ function normNodePath(p) {
42
107
  return s || '/';
43
108
  }
44
109
 
45
- /** Сопоставление субъекта uid (строка/null или { uid, nodePath, nodeOnly }) со списком назначенных USERS. */
110
+ function parseRemoteEntry(entry) {
111
+ if (typeof entry !== 'string')
112
+ return null;
113
+ const norm = normNodePath(entry);
114
+ const m = /^\/NODES\/([^/]+)(?:\/(.*))?$/i.exec(norm);
115
+ if (!m)
116
+ return null;
117
+ const nodeSeg = m[1];
118
+ const rest = m[2] ? '/' + m[2] : '';
119
+ const userMatch = /^\/USERS\/([^/]+)$/i.exec(rest);
120
+ if (userMatch)
121
+ return { kind: 'remote-user', nodeSeg, nodePath: `/NODES/${nodeSeg}`, remoteUid: userMatch[1], rest };
122
+ if (rest && /^\/(?:ORGANIZATIONS|PROJECTS)(?:\/|$)/i.test(rest))
123
+ return { kind: 'remote-unit', nodeSeg, nodePath: `/NODES/${nodeSeg}`, remotePath: rest };
124
+ return { kind: 'remote-node', nodeSeg, nodePath: `/NODES/${nodeSeg}`, rest };
125
+ }
126
+
127
+ /**
128
+ * Сопоставление субъекта (uid строка/null или объект
129
+ * `{ uid, nodePath, nodeOnly, remoteNodeId, remoteNodePath, remoteActor, remoteFromPath }`)
130
+ * со списком назначенных USERS.
131
+ */
46
132
  export function matchesUserList(list, subject) {
47
133
  if (!Array.isArray(list) || !list.length)
48
134
  return false;
49
135
  if (subject && typeof subject === 'object' && !Array.isArray(subject)) {
50
- const { uid = null, nodePath = '', nodeOnly = false } = subject;
136
+ const {
137
+ uid = null,
138
+ nodePath = '',
139
+ nodeOnly = false,
140
+ remoteNodeId = '',
141
+ remoteNodePath = '',
142
+ remoteActor = '',
143
+ remoteFromPath = '',
144
+ } = subject;
51
145
  if (nodePath) {
52
146
  const target = normNodePath(nodePath);
53
147
  if (list.some(item => isNodeSubject(item) && normNodePath(item) === target))
54
148
  return true;
55
149
  }
150
+ if (remoteNodeId || remoteNodePath) {
151
+ const normRemoteNode = remoteNodePath ? normNodePath(remoteNodePath) : '';
152
+ const normRemoteNodeId = String(remoteNodeId || '').trim().toUpperCase();
153
+ const normActor = String(remoteActor || '').trim();
154
+ const normFrom = remoteFromPath ? normNodePath(remoteFromPath) : '';
155
+ const remoteNodeSeg = normRemoteNode ? normRemoteNode.split('/').filter(Boolean)[1] || '' : '';
156
+ for (const item of list) {
157
+ if (typeof item !== 'string' || !item)
158
+ continue;
159
+ // Совпадение с узлом сети по host_id (principalId)
160
+ if (normRemoteNodeId && item.toUpperCase() === normRemoteNodeId)
161
+ return true;
162
+ // Совпадение по формату actor@host_id
163
+ if (normActor && normRemoteNodeId && item.toUpperCase() === `${normActor}@${normRemoteNodeId}`.toUpperCase())
164
+ return true;
165
+ // Совпадение по пути /NODES/<Узел>[/USERS/<uid> | /ORGANIZATIONS/...]
166
+ const parsed = parseRemoteEntry(item);
167
+ if (!parsed)
168
+ continue;
169
+ const sameNode = (normRemoteNode && normNodePath(parsed.nodePath).toLowerCase() === normRemoteNode.toLowerCase())
170
+ || (normRemoteNodeId && parsed.nodeSeg.toUpperCase() === normRemoteNodeId)
171
+ || (remoteNodeSeg && parsed.nodeSeg.toLowerCase() === remoteNodeSeg.toLowerCase());
172
+ if (!sameNode)
173
+ continue;
174
+ if (parsed.kind === 'remote-node')
175
+ return true;
176
+ if (parsed.kind === 'remote-user' && normActor && parsed.remoteUid === normActor)
177
+ return true;
178
+ if (parsed.kind === 'remote-unit' && normFrom
179
+ && (normFrom === parsed.remotePath || normFrom.startsWith(parsed.remotePath + '/')))
180
+ return true;
181
+ }
182
+ // Для удалённого узла локальные псевдо-субъекты 'USERS' не подставляются —
183
+ // только явное назначение узла/его пользователя/подразделения или 'GUESTS'.
184
+ if (list.includes('GUESTS') || list.includes('GUEST'))
185
+ return true;
186
+ return false;
187
+ }
56
188
  if (nodeOnly)
57
189
  return false;
58
190
  return matchesUserList(list, uid);
@@ -88,25 +220,71 @@ export function isOpenToGuests(security) {
88
220
  return walkPlaces(places).some(({ node }) => matchesUserList(node.USERS, null));
89
221
  }
90
222
 
91
- const RANK = { read: 1, write: 2 };
92
-
93
- function maxAccess(a, b) {
94
- return (RANK[b] || 0) > (RANK[a] || 0) ? b : a;
95
- }
96
-
97
223
  /** Видимость данных по ссылке (docs/architecture-v2.md, Р8): свои объекты, своего места, подразделения с вложенными, все. */
98
224
  export const LINK_SCOPES = Object.freeze(['own', 'place', 'unit', 'all']);
99
225
 
100
226
  /** Нормализовать одну ссылку {id, access, scope?}; мусор — null, неизвестный scope отбрасывается (действует умолчание). */
101
227
  export function normalizeLink(raw) {
102
- const id = String(raw?.id || '').trim();
103
- const access = String(raw?.access || '').trim();
104
- if (!id.startsWith('/') || (access !== 'read' && access !== 'write'))
228
+ const id = String(raw?.id || '').trim().replace(/\/+$/, '');
229
+ const access = normalizeAccess(raw?.access);
230
+ if (!id.startsWith('/') || !access)
105
231
  return null;
106
232
  const scope = String(raw?.scope || '').trim();
107
233
  return LINK_SCOPES.includes(scope) ? { id, access, scope } : { id, access };
108
234
  }
109
235
 
236
+ /**
237
+ * Вычислить эффективную ссылку для пути `clsPath` внутри одного набора ссылок (одной роли или общих LINKS)
238
+ * по правилу наиболее специфичного предка (longest prefix match).
239
+ * Это позволяет переопределять унаследованное от папки право вверх или вниз (вплоть до `none`).
240
+ * @returns {{ link: object, access: string, denied: boolean } | null}
241
+ */
242
+ export function resolveLinkInSet(links, clsPath) {
243
+ const p = normNodePath(clsPath);
244
+ if (!p.startsWith('/') || !Array.isArray(links) || !links.length)
245
+ return null;
246
+ let best = null;
247
+ let bestLen = -1;
248
+ for (const l of links) {
249
+ if (!l?.id)
250
+ continue;
251
+ const lid = normNodePath(l.id);
252
+ if (p !== lid && !p.startsWith(lid + '/'))
253
+ continue;
254
+ if (lid.length > bestLen) {
255
+ best = l;
256
+ bestLen = lid.length;
257
+ }
258
+ else if (lid.length === bestLen && best) {
259
+ // При совпадении путей в одном списке — более высокий ранг побеждает (или явный none при равенстве)
260
+ if ((ACCESS_RANK[l.access] || 0) >= (ACCESS_RANK[best.access] || 0))
261
+ best = l;
262
+ }
263
+ }
264
+ if (!best)
265
+ return null;
266
+ return { link: best, access: best.access, denied: best.access === 'none' };
267
+ }
268
+
269
+ /**
270
+ * Список путей строго ниже `basePath` в том же наборе ссылок, на которых эффективный уровень
271
+ * строго ниже `minAccess` (например, явный запрет `none` или сужение до `read` при проверке `write`).
272
+ */
273
+ export function deniedSubpathsInSet(links, basePath, minAccess = 'read') {
274
+ const base = normNodePath(basePath);
275
+ const out = [];
276
+ for (const l of Array.isArray(links) ? links : []) {
277
+ if (!l?.id)
278
+ continue;
279
+ const lid = normNodePath(l.id);
280
+ if (!lid.startsWith(base + '/'))
281
+ continue;
282
+ if (!hasAccess(l.access, minAccess))
283
+ out.push(lid);
284
+ }
285
+ return out;
286
+ }
287
+
110
288
  /** Нормализовать дерево прикладных ролей; мусор отбрасывается. */
111
289
  export function normalizePlaces(raw, seen = new Set(), depth = 0) {
112
290
  if (!Array.isArray(raw) || depth > 10)
@@ -215,11 +393,35 @@ export function hasPlaceAssignments(security) {
215
393
  return walkPlaces(places).some(({ node }) => node.USERS.length > 0);
216
394
  }
217
395
 
396
+ /**
397
+ * Построить единый субъект проверки прав из `uid` и `params.session`
398
+ * (учитывает локального пользователя, локальный вызов цифрового двойника и удалённый узел сети /NODES).
399
+ */
400
+ export function buildSubject(uid, params = {}) {
401
+ const twinFrom = params?.session?.twinCall?.fromPath || '';
402
+ const nodeOnly = Boolean(params?.session?.twinRoleOnly);
403
+ const principal = params?.session?.principal;
404
+ if (principal?.kind === 'node') {
405
+ const remoteActor = principal.actorId
406
+ || (typeof principal.actor === 'string' && principal.actor.includes('@') ? principal.actor.split('@')[0] : '');
407
+ return {
408
+ uid,
409
+ nodePath: twinFrom,
410
+ nodeOnly,
411
+ remoteNodeId: principal.id || '',
412
+ remoteNodePath: principal.nodePath || params?.session?.$user?.path || '',
413
+ remoteActor,
414
+ remoteFromPath: principal.fromPath || twinFrom || '',
415
+ };
416
+ }
417
+ return twinFrom ? { uid, nodePath: twinFrom, nodeOnly } : uid;
418
+ }
419
+
218
420
  /**
219
421
  * Эффективные ссылки мест для пользователя: Map id → { access, via: [trailKey] }.
220
- * Свои ссылки места — своим access; ссылки вложенных мест — на чтение.
422
+ * Свои ссылки места — своим access; ссылки вложенных мест — на чтение (кроме явного none).
221
423
  * @param {object} security Секция `#security`
222
- * @param {string} uid
424
+ * @param {string|object} uid
223
425
  * @param {object} [opts]
224
426
  * @param {boolean} [opts.bossAll] BOSS: все ссылки всех мест — на чтение
225
427
  */
@@ -228,7 +430,7 @@ export function placeLinksFor(security, uid, opts = {}) {
228
430
  const eff = new Map();
229
431
  const add = (link, via) => {
230
432
  const cur = eff.get(link.id);
231
- const next = maxAccess(cur?.access, link.access);
433
+ const next = cur ? maxAccess(cur.access, link.access) : link.access;
232
434
  const seen = new Set(cur?.via || []);
233
435
  seen.add(via);
234
436
  eff.set(link.id, { access: next, via: [...seen] });
@@ -237,7 +439,7 @@ export function placeLinksFor(security, uid, opts = {}) {
237
439
  if (opts.bossAll)
238
440
  for (const { node, trail } of all)
239
441
  for (const l of node.LINKS)
240
- add({ id: l.id, access: 'read' }, trailKey(trail));
442
+ add({ id: l.id, access: l.access === 'none' ? 'none' : 'read' }, trailKey(trail));
241
443
  const mine = new Set(memberTrailKeys(security, uid));
242
444
  if (mine.size) {
243
445
  const under = key => [...mine].some(m => key === m || key.startsWith(m + '/'));
@@ -246,8 +448,10 @@ export function placeLinksFor(security, uid, opts = {}) {
246
448
  if (!under(key))
247
449
  continue;
248
450
  const downgrade = !mine.has(key);
249
- for (const l of node.LINKS)
250
- add({ id: l.id, access: downgrade ? 'read' : l.access }, key);
451
+ for (const l of node.LINKS) {
452
+ const effAccess = l.access === 'none' ? 'none' : (downgrade ? 'read' : l.access);
453
+ add({ id: l.id, access: effAccess }, key);
454
+ }
251
455
  }
252
456
  }
253
457
  return eff;