odant-work 1.0.113 → 1.0.115

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.113",
3
+ "version": "1.0.115",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
package/sources/client.js CHANGED
@@ -456,6 +456,15 @@ WORK.login = async function(force = false){
456
456
  }
457
457
  if (!force && window.top && window.top !== window) {
458
458
  try {
459
+ if (window.top.WORK?.uid && (!nextUid || window.top.WORK.uid === nextUid)) {
460
+ WORK.credentials = window.top.WORK.credentials || nextCreds;
461
+ WORK.uid = window.top.WORK.uid;
462
+ WORK.USER = window.top.WORK.USER;
463
+ WORK.userSettings = window.top.WORK.userSettings || WORK.userSettings;
464
+ WORK._userSettingsLoaded = Boolean(window.top.WORK._userSettingsLoaded);
465
+ WORK._loginError = null;
466
+ return "Вход выполнен";
467
+ }
459
468
  if (window.top.WORK?._loginPromise && window.top.WORK?._loginTargetUid === nextUid) {
460
469
  const res = await window.top.WORK._loginPromise;
461
470
  WORK.credentials = window.top.WORK.credentials;
@@ -489,6 +498,7 @@ WORK.login = async function(force = false){
489
498
  let KEY = secure.getItem('KEY');
490
499
  let uid = WORK.credentials?.uid;
491
500
  if(uid && KEY){
501
+ const wsidBeforeLogin = WORK.wsid || '';
492
502
  if (WORK.uid && WORK.uid !== uid)
493
503
  await WORK.removeCurrentPushSubscription?.();
494
504
  let challengeId = crypto.randomUUID();
@@ -527,6 +537,8 @@ WORK.login = async function(force = false){
527
537
  window.explorer?._refreshLeftButtons?.();
528
538
  await WORK.loadUserSettings?.();
529
539
  WORK.refreshChatUnread?.();
540
+ if (WORK.wsid && WORK.wsid !== wsidBeforeLogin && typeof WORK.fetch === 'function')
541
+ (WORK.USER?.fetch ? WORK.USER.fetch('info', { reset: 1 }) : WORK.fetch('/', 'chat_unread_summary')).catch(() => {});
530
542
  if (authChanged) {
531
543
  WORK._authNotifiedOnce = true;
532
544
  WORK.notifyAuth?.({ uid, reason: 'login' });
@@ -841,7 +853,9 @@ class WebSocketEvents {
841
853
  }
842
854
  WORK.connected = true;
843
855
  window.explorer?._refreshLeftButtons?.();
844
- if (!WORK._accountDisabled)
856
+ let credUid = '';
857
+ try { credUid = ODA.LocalStorage.create('work-secure').getItem('credentials')?.uid || ''; } catch {}
858
+ if (!WORK._accountDisabled && (!WORK.uid || (credUid && WORK.uid !== credUid)))
845
859
  WORK.login().catch(() => {});
846
860
  }
847
861
  onclose(e) {
@@ -849,11 +863,23 @@ class WebSocketEvents {
849
863
  WORK._ws = null;
850
864
  WORK.connected = false;
851
865
  WORK.wsid = '';
852
- WORK._loginPromise = null;
866
+ if (!WORK.uid)
867
+ WORK._loginPromise = null;
853
868
  window.explorer?._refreshLeftButtons?.();
854
- setTimeout(() => {
855
- new WebSocketEvents();
856
- }, 3000);
869
+ if (e?.code === 4403 || e?.code === 4401) {
870
+ console.warn('[ws] соединение отклонено сервером:', e.code, e.reason || '');
871
+ return;
872
+ }
873
+ const attempt = Number(WORK._wsReconnectAttempts) || 0;
874
+ const delays = [3000, 6000, 12000, 30000];
875
+ const delay = delays[Math.min(attempt, delays.length - 1)];
876
+ WORK._wsReconnectAttempts = attempt + 1;
877
+ clearTimeout(WORK._wsReconnectTimer);
878
+ WORK._wsReconnectTimer = setTimeout(() => {
879
+ WORK._wsReconnectTimer = 0;
880
+ if (!WORK._ws || WORK._ws.readyState > 1)
881
+ new WebSocketEvents();
882
+ }, delay);
857
883
  // console.log('Close webSocket connection');
858
884
  }
859
885
  onerror(e) {
@@ -872,9 +898,17 @@ class WebSocketEvents {
872
898
  case 'connect':{
873
899
  WORK.wsid = this.id = data.wsid;
874
900
  WORK.connected = true;
901
+ WORK._wsReconnectAttempts = 0;
875
902
  window.explorer?._refreshLeftButtons?.();
876
- if (WORK.uid && typeof WORK.fetch === 'function')
877
- (WORK.USER?.fetch ? WORK.USER.fetch('info', { reset: 1 }) : WORK.fetch('/', 'chat_unread_summary')).catch(() => {});
903
+ if (WORK.uid && typeof WORK.fetch === 'function') {
904
+ WORK.fetch('/', 'chat_unread_summary').catch(() => {
905
+ if (!WORK._accountDisabled)
906
+ WORK.login(true).catch(() => {});
907
+ });
908
+ }
909
+ else if (!WORK._accountDisabled) {
910
+ WORK.login().catch(() => {});
911
+ }
878
912
  } break;
879
913
  case 'user-settings': {
880
914
  if (data.settings && (!WORK.uid || data.uid === WORK.uid))
@@ -948,6 +982,9 @@ class WebSocketEvents {
948
982
  WORK.chatEvents.dispatchEvent(new CustomEvent('node.deleted', { detail: data }));
949
983
  } break;
950
984
  case 'chat:message':
985
+ case 'chat:edit':
986
+ case 'chat:delete':
987
+ case 'chat:action':
951
988
  case 'chat:read': {
952
989
  WORK.chatEvents ??= new EventTarget();
953
990
  if (data.type === 'chat:message' && data.message?.sender !== WORK.uid) {
@@ -964,7 +1001,7 @@ class WebSocketEvents {
964
1001
  }
965
1002
  WORK.chatUnread.total = (WORK.chatUnread.total || 0) + 1;
966
1003
  }
967
- else if (data.type === 'chat:read' && data.threadId) {
1004
+ else if (data.type === 'chat:read' && data.threadId && (!data.uid || data.uid === WORK.uid)) {
968
1005
  WORK.applyChatReadLocal?.(data);
969
1006
  break;
970
1007
  }
@@ -989,6 +1026,16 @@ class WebSocketEvents {
989
1026
  }
990
1027
  }
991
1028
  for (const item of matched) {
1029
+ if (typeof data.online === 'boolean') {
1030
+ const d = (item.DATA ??= {});
1031
+ d.online = data.online;
1032
+ if (item[R]?.__data__)
1033
+ item[R].__data__.online = data.online;
1034
+ Reactor.invalidate(item, 'DATA');
1035
+ Reactor.invalidate(item, 'online');
1036
+ item.increaseVersion();
1037
+ continue;
1038
+ }
992
1039
  const LISTS = item.constructor.LISTS || CORE.$item.LISTS;
993
1040
  for(let key of LISTS){
994
1041
  delete item[key];
@@ -1000,22 +1047,14 @@ class WebSocketEvents {
1000
1047
  // версия — до fire: слушатели changed делают load(), а его URL (и дедуп WORK.fetch) включает версию;
1001
1048
  // старый порядок склеивал reload с висящим прежним запросом и отдавал устаревший JSON
1002
1049
  item.increaseVersion();
1003
- if (item.DATA?.isUser && !item.DATA?.usersContainer) {
1004
- if (typeof data.online === 'boolean') {
1005
- (item.DATA ??= {}).online = data.online;
1050
+ if (item.DATA?.isUser && !item.DATA?.usersContainer && !WORK._roleRefresh.has(item)) {
1051
+ WORK._roleRefresh.add(item);
1052
+ item.fetch('info').then(() => {
1006
1053
  Reactor.invalidate(item, 'DATA');
1007
1054
  Reactor.invalidate(item, 'online');
1008
1055
  item.increaseVersion();
1009
- }
1010
- else if (!WORK._roleRefresh.has(item)) {
1011
- WORK._roleRefresh.add(item);
1012
- item.fetch('info').then(() => {
1013
- Reactor.invalidate(item, 'DATA');
1014
- Reactor.invalidate(item, 'online');
1015
- item.increaseVersion();
1016
- item.fire('changed', data);
1017
- }).catch(() => { }).finally(() => WORK._roleRefresh.delete(item));
1018
- }
1056
+ item.fire('changed', data);
1057
+ }).catch(() => { }).finally(() => WORK._roleRefresh.delete(item));
1019
1058
  }
1020
1059
  // роли пользователей и флаги безопасности (roleIds, hasSecurity, icon, label) приходят в info:
1021
1060
  // подтянуть свежие данные и уведомить дерево
@@ -18,15 +18,34 @@ export function sameOrigin(req) {
18
18
  return true;
19
19
  try {
20
20
  const strip = s => String(s || '').trim().toLowerCase().replace(/:(?:80|443)$/, '');
21
+ const normLoop = h => h.replace(/^127\.0\.0\.1(?=:|$)/, 'localhost').replace(/^\[::1\](?=:|$)/, 'localhost');
21
22
  const oHost = strip(new URL(origin).host);
22
23
  const hHost = strip(req?.headers?.host || req?.headers?.[':authority'] || '');
23
- if (hHost && oHost === hHost)
24
+ if (hHost && (oHost === hHost || normLoop(oHost) === normLoop(hHost)))
24
25
  return true;
25
- const fwd = strip(String(req?.headers?.['x-forwarded-host'] || '').split(',')[0]);
26
+ const parseForwardedHost = (raw) => {
27
+ const m = String(raw || '').match(/\bhost\s*=\s*"?([^";,\s]+)"?/i);
28
+ return m ? strip(m[1]) : '';
29
+ };
30
+ const fwd = strip(String(req?.headers?.['x-forwarded-host'] || req?.headers?.['x-original-host'] || req?.headers?.['x-host'] || '').split(',')[0])
31
+ || parseForwardedHost(req?.headers?.forwarded);
26
32
  const addr = String(req?.socket?.remoteAddress || req?.connection?.remoteAddress || '').trim();
27
33
  const isLoop = addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1';
28
- if (fwd && (isLoop || req?.headers?.['x-forwarded-proto']) && oHost === fwd)
34
+ const hasProxyHint = Boolean(req?.headers?.['x-forwarded-proto'] || req?.headers?.['cf-ray'] || req?.headers?.['x-real-ip'] || req?.headers?.['x-forwarded-for']);
35
+ if (fwd && (isLoop || hasProxyHint) && oHost === fwd)
29
36
  return true;
37
+ // Reverse proxy (Nginx/Cloudflare/tuunel) может переписывать Host без X-Forwarded-Host:
38
+ // если соединение локальное/через прокси и браузер подтвердил Sec-Fetch-Site: same-origin, пускаем.
39
+ const fetchSite = String(req?.headers?.['sec-fetch-site'] || '').trim().toLowerCase();
40
+ if ((isLoop || hasProxyHint) && fetchSite === 'same-origin')
41
+ return true;
42
+ const pubRaw = process.env.WORK_PUBLIC_ORIGIN || process.env.WORK_ORIGIN || globalThis.WORK?.DATA?.publicUrl || '';
43
+ if (pubRaw) {
44
+ try {
45
+ if (oHost === strip(new URL(String(pubRaw)).host))
46
+ return true;
47
+ } catch { /* ignore */ }
48
+ }
30
49
  return false;
31
50
  }
32
51
  catch {
@@ -102,8 +121,10 @@ export function notifyUserOnline(session, userOverride = null) {
102
121
  const user = userOverride || session?.$user;
103
122
  if (!user)
104
123
  return;
124
+ const r = globalThis.R || Symbol.for('R');
125
+ if (user[r]?.cache)
126
+ delete user[r].cache.online;
105
127
  user.online = undefined;
106
- user.reset?.();
107
128
  broadcastUserPath(user);
108
129
  }
109
130
 
@@ -181,7 +202,7 @@ export function onWebSocketConnect(ws, request) {
181
202
  const cookies = parseCookies(request);
182
203
  let session = $server.get_session(cookies.ssid);
183
204
  let wsid = $server.genGUID();
184
- const sock = { ws, events: [], visibleTasks: new Set(), session };
205
+ const sock = { ws, events: new Set(), visibleTasks: new Set(), session };
185
206
  session.sockets[wsid] = sock;
186
207
  ws.send(JSON.stringify({ type: 'connect', wsid }));
187
208
  if (session.uid)
@@ -44,7 +44,7 @@ export const MEMBERS = Object.freeze({
44
44
  logs: L.READ, logs_dates: L.READ, log_files: L.READ, read_log_bodies: L.READ,
45
45
  read_log_entry: L.READ, log_index: L.READ, chatSource: L.READ,
46
46
  chat_thread_open: L.CALL, chat_threads_list: L.READ, chat_messages_list: L.READ,
47
- chat_send: L.CALL, chat_mark_read: L.CALL, chat_action: L.WRITE, chat_unread_summary: L.AUTH, visible_contacts: L.AUTH, my_scope: L.AUTH,
47
+ chat_send: L.CALL, chat_mark_read: L.CALL, chat_action: L.WRITE, chat_edit: L.CALL, chat_delete: L.CALL, chat_unread_summary: L.AUTH, visible_contacts: L.AUTH, my_scope: L.AUTH,
48
48
  mail_accounts: L.READ, mail_list: L.READ, mail_read: L.READ,
49
49
  mail_draft_save: L.WRITE, mail_send: L.WRITE, mail_state: L.WRITE, mail_refresh: L.WRITE,
50
50
  calendar_list: L.READ, calendar_save: L.WRITE,
@@ -386,7 +386,21 @@ export async function sendMessage(storage, params = {}) {
386
386
  const replyTo = params.replyTo != null && Number.isFinite(Number(params.replyTo)) ? Number(params.replyTo) : null;
387
387
  const mentions = normalizeMentions(params.mentions);
388
388
  const attachments = normalizeAttachments(params.attachments);
389
- const meta = (params.meta && typeof params.meta === 'object') ? params.meta : (typeof params.meta === 'string' ? parseJsonSafe(params.meta, {}) : {});
389
+ const meta = (params.meta && typeof params.meta === 'object') ? { ...params.meta } : (typeof params.meta === 'string' ? parseJsonSafe(params.meta, {}) : {});
390
+
391
+ if (replyTo && !meta.replyPreview) {
392
+ const orig = db.prepare('SELECT id, sender, kind, content, attachments FROM chat_messages WHERE id = ? AND thread_id = ?').get(replyTo, threadId);
393
+ if (orig) {
394
+ const origAtts = parseJsonSafe(orig.attachments, []);
395
+ meta.replyPreview = {
396
+ id: Number(orig.id),
397
+ sender: orig.sender,
398
+ kind: orig.kind || 'text',
399
+ content: String(orig.content || '').slice(0, 180),
400
+ attachmentsCount: Array.isArray(origAtts) ? origAtts.length : 0,
401
+ };
402
+ }
403
+ }
390
404
 
391
405
  // Проверяем видимость вложений отправителем и выдаём участникам беседы доступ к конкретным файлам (Q8)
392
406
  const attPaths = attachments.map(a => a.path);
@@ -474,7 +488,8 @@ export async function markRead(storage, params = {}) {
474
488
  const targetId = params.lastMessageId != null ? Math.min(Number(params.lastMessageId) || 0, Number(maxRow?.max_id) || 0) : (Number(maxRow?.max_id) || 0);
475
489
  const nextRead = Math.max(Number(part.last_read_id) || 0, targetId);
476
490
  db.prepare('UPDATE chat_participants SET last_read_id = ? WHERE thread_id = ? AND uid = ?').run(nextRead, threadId, uid);
477
- notifyChatEvent([uid], {
491
+ const allParticipants = db.prepare('SELECT uid FROM chat_participants WHERE thread_id = ?').all(threadId).map(r => r.uid).filter(Boolean);
492
+ notifyChatEvent(allParticipants.length ? allParticipants : [uid], {
478
493
  type: 'chat:read',
479
494
  threadId,
480
495
  kind,
@@ -745,11 +760,90 @@ export async function resolveApproval(storage, params = {}) {
745
760
  notifyChatEvent(thread.participants.map(p => p.uid), {
746
761
  type: 'chat:action',
747
762
  threadId,
763
+ kind: thread.kind,
764
+ nodePath: thread.nodePath,
765
+ message: updated,
766
+ });
767
+ return { ok: true, message: updated };
768
+ }
769
+
770
+ /** Редактировать своё текстовое сообщение в беседе + рассылка по WebSocket. */
771
+ export async function editMessage(storage, params = {}) {
772
+ const uid = resolveActorUid(storage, params);
773
+ if (!uid)
774
+ throw new Error(ACCESS_DENIED);
775
+ const threadId = String(params.threadId || '').trim();
776
+ const messageId = Number(params.messageId);
777
+ const nextContent = String(params.message ?? params.content ?? '').trim();
778
+ if (!threadId || !Number.isFinite(messageId) || !nextContent)
779
+ throw new Error('Требуются threadId, messageId и непустой текст');
780
+
781
+ const kindHint = threadId.startsWith('dm:') ? 'dm' : 'twin';
782
+ const db = await dbForThreadStorage(storage, kindHint);
783
+ const thread = getThreadWithMeta(db, threadId, uid);
784
+ if (!thread)
785
+ throw new Error('Беседа не найдена');
786
+ if (!thread.participants.some(p => p.uid === uid))
787
+ throw new Error(ACCESS_DENIED);
788
+
789
+ const row = db.prepare('SELECT * FROM chat_messages WHERE id = ? AND thread_id = ?').get(messageId, threadId);
790
+ if (!row)
791
+ throw new Error('Сообщение не найдено');
792
+ if (row.sender !== uid)
793
+ throw new Error('Можно редактировать только свои сообщения');
794
+ if (row.kind && !['text', 'dm', 'twin'].includes(row.kind))
795
+ throw new Error('Редактирование доступно только для текстовых сообщений');
796
+
797
+ const meta = parseJsonSafe(row.meta, {});
798
+ const nextMeta = { ...meta, editedAt: Date.now() };
799
+ db.prepare('UPDATE chat_messages SET content = ?, meta = ? WHERE id = ? AND thread_id = ?')
800
+ .run(nextContent, JSON.stringify(nextMeta), messageId, threadId);
801
+ const updated = formatMessageRow(db.prepare('SELECT * FROM chat_messages WHERE id = ?').get(messageId));
802
+ notifyChatEvent(thread.participants.map(p => p.uid), {
803
+ type: 'chat:edit',
804
+ threadId,
805
+ kind: thread.kind,
806
+ nodePath: thread.nodePath,
748
807
  message: updated,
749
808
  });
750
809
  return { ok: true, message: updated };
751
810
  }
752
811
 
812
+ /** Удалить своё сообщение из беседы + рассылка по WebSocket. */
813
+ export async function deleteMessage(storage, params = {}) {
814
+ const uid = resolveActorUid(storage, params);
815
+ if (!uid)
816
+ throw new Error(ACCESS_DENIED);
817
+ const threadId = String(params.threadId || '').trim();
818
+ const messageId = Number(params.messageId);
819
+ if (!threadId || !Number.isFinite(messageId))
820
+ throw new Error('Требуются threadId и messageId');
821
+
822
+ const kindHint = threadId.startsWith('dm:') ? 'dm' : 'twin';
823
+ const db = await dbForThreadStorage(storage, kindHint);
824
+ const thread = getThreadWithMeta(db, threadId, uid);
825
+ if (!thread)
826
+ throw new Error('Беседа не найдена');
827
+ if (!thread.participants.some(p => p.uid === uid))
828
+ throw new Error(ACCESS_DENIED);
829
+
830
+ const row = db.prepare('SELECT * FROM chat_messages WHERE id = ? AND thread_id = ?').get(messageId, threadId);
831
+ if (!row)
832
+ throw new Error('Сообщение не найдено');
833
+ if (row.sender !== uid)
834
+ throw new Error('Можно удалять только свои сообщения');
835
+
836
+ db.prepare('DELETE FROM chat_messages WHERE id = ? AND thread_id = ?').run(messageId, threadId);
837
+ notifyChatEvent(thread.participants.map(p => p.uid), {
838
+ type: 'chat:delete',
839
+ threadId,
840
+ kind: thread.kind,
841
+ nodePath: thread.nodePath,
842
+ messageId,
843
+ });
844
+ return { ok: true, threadId, messageId };
845
+ }
846
+
753
847
  /** Удалить сообщения беседы, привязанные к перенесённой задаче (`task_path`). */
754
848
  export async function deleteTaskMessages(storage, taskPath) {
755
849
  const raw = String(taskPath || '').trim();
@@ -207,6 +207,16 @@ export const classFeedMethods = {
207
207
  return CHAT.resolveApproval(this, mergeChatPost(params, post));
208
208
  },
209
209
 
210
+ /** Редактировать своё сообщение в беседе. */
211
+ async chat_edit(params = {}, post) {
212
+ return CHAT.editMessage(this, mergeChatPost(params, post));
213
+ },
214
+
215
+ /** Удалить своё сообщение из беседы. */
216
+ async chat_delete(params = {}, post) {
217
+ return CHAT.deleteMessage(this, mergeChatPost(params, post));
218
+ },
219
+
210
220
  /** Вычисляемый список видимых контактов («Люди»). */
211
221
  async visible_contacts(params = {}) {
212
222
  return CHAT.visibleContacts(this, params);
@@ -725,6 +725,8 @@ export class $file extends $folder{
725
725
  return log;
726
726
  }
727
727
  async allowAccess(params) {
728
+ if (this.path === '/sw.js' || this.path === '/favicon.ico' || this.path === '/logo.png')
729
+ return true;
728
730
  const $item = (await this.$class) || (await this.$owner);
729
731
  if (!$item)
730
732
  return true;
@@ -2356,7 +2356,7 @@ export class $folder extends $item{
2356
2356
  for(let session of Object.values($server.sessions)){
2357
2357
  for(let id in session.sockets){
2358
2358
  let socket = session.sockets[id];
2359
- let list = socket.events.filter(e=>isSubscribedTo(e, key));
2359
+ let list = [...(socket.events || [])].filter(e=>isSubscribedTo(e, key));
2360
2360
  if(list.length) // todo возможно надо посылать события всем в списке
2361
2361
  socket.ws.send(JSON.stringify({path: key, initiator: initiator?.id}));
2362
2362
  }