odant-work 1.0.107 → 1.0.109

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.
@@ -7,9 +7,12 @@ import path from 'node:path';
7
7
  import crypto from 'node:crypto';
8
8
  import { getMailer } from '../../host/mail.js';
9
9
  import { LOCAL_ORIGIN } from '../../host/config.js';
10
+ import { normalizePhone, hasLocalSmsGateway, sendViaSmsProvider } from '../../host/sms.js';
10
11
  import { buildPointChain, readPointConfig, getAdapter } from '../../modules/notify/index.js';
11
12
  import { audit } from './audit.js';
12
13
 
14
+ const sysSession = () => ({ $user: globalThis.WORK });
15
+
13
16
  let customInvitesFile = '';
14
17
 
15
18
  export function _setInvitesFileForTests(filePath = '') {
@@ -60,7 +63,7 @@ export function findRoleByTrail(roles, trail = '') {
60
63
 
61
64
  function normalizeChannel(ch = 'link') {
62
65
  const v = String(ch || 'link').trim().toLowerCase();
63
- return ['link', 'email', 'telegram', 'max'].includes(v) ? v : 'link';
66
+ return ['link', 'email', 'phone', 'telegram', 'max'].includes(v) ? v : 'link';
64
67
  }
65
68
 
66
69
  function computeStatus(inv, now = Date.now()) {
@@ -189,7 +192,7 @@ export async function consumeInvite({ token = '', uid = '', resolver = null, soc
189
192
  throw new Error(`Точка приглашения ${inv.pointPath} не найдена`);
190
193
 
191
194
  await item.init;
192
- const data = structuredClone(item.DATA || {});
195
+ const data = JSON.parse(JSON.stringify(item.DATA || {}));
193
196
  data['#security'] ??= {};
194
197
 
195
198
  if (inv.trail === 'BOSS') {
@@ -209,7 +212,7 @@ export async function consumeInvite({ token = '', uid = '', resolver = null, soc
209
212
 
210
213
  await item.save({
211
214
  post: item.constructor.toScript(data),
212
- session: { $user: globalThis.WORK },
215
+ session: sysSession(),
213
216
  sockets,
214
217
  });
215
218
  item.reset?.();
@@ -282,7 +285,7 @@ export const INVITE_METHODS = Object.freeze({
282
285
  level: 'read',
283
286
  fn: async function (params = {}) {
284
287
  await this.assertAccess(params, this.constructor.ACCESS_LEVEL.BOSS);
285
- return listPointInvites(this.path);
288
+ return listPointInvites(this.path || '/');
286
289
  },
287
290
  },
288
291
 
@@ -292,7 +295,7 @@ export const INVITE_METHODS = Object.freeze({
292
295
  await this.assertAccess(params, this.constructor.ACCESS_LEVEL.BOSS);
293
296
  const token = params.post?.token ?? params.token ?? '';
294
297
  const id = params.post?.id ?? params.id ?? '';
295
- const rev = revokeInvite({ pointPath: this.path, token, id });
298
+ const rev = revokeInvite({ pointPath: this.path || '/', token, id });
296
299
  audit('invite_revoke', { pointPath: this.path, id: rev.id, params });
297
300
  return { ok: true, invite: rev };
298
301
  },
@@ -305,7 +308,13 @@ export const INVITE_METHODS = Object.freeze({
305
308
  const post = (params.post && typeof params.post === 'object') ? params.post : params;
306
309
  const trail = String(post.trail || '').trim();
307
310
  const channel = normalizeChannel(post.channel || 'link');
308
- const recipient = String(post.recipient || '').trim();
311
+ let recipient = String(post.recipient || '').trim();
312
+ if (channel === 'phone') {
313
+ const norm = normalizePhone(recipient);
314
+ if (!norm)
315
+ throw new Error('Укажите корректный номер телефона (например, +79991234567)');
316
+ recipient = norm;
317
+ }
309
318
  const note = String(post.note || '').trim();
310
319
  const ttlHours = Number(post.ttlHours) || 168;
311
320
 
@@ -323,8 +332,8 @@ export const INVITE_METHODS = Object.freeze({
323
332
  }
324
333
 
325
334
  const inv = createInvite({
326
- pointPath: this.path,
327
- pointLabel: this.label || this.DATA?.label || this.id || this.path,
335
+ pointPath: this.path || '/',
336
+ pointLabel: this.label || this.DATA?.label || this.id || this.path || 'WORK',
328
337
  trail,
329
338
  placeLabel,
330
339
  channel,
@@ -373,6 +382,26 @@ export const INVITE_METHODS = Object.freeze({
373
382
  warning = 'SMTP-сервер не настроен — скопируйте ссылку вручную и отправьте получателю.';
374
383
  }
375
384
  }
385
+ else if (channel === 'phone' && recipient) {
386
+ if (hasLocalSmsGateway()) {
387
+ try {
388
+ await sendViaSmsProvider({
389
+ phone: recipient,
390
+ message: text,
391
+ mode: 'sms',
392
+ ip: params.request?.socket?.remoteAddress || '',
393
+ });
394
+ sent = true;
395
+ sentVia = 'phone';
396
+ }
397
+ catch (err) {
398
+ warning = `Не удалось отправить SMS (${err?.message || err}) — скопируйте ссылку и отправьте получателю вручную.`;
399
+ }
400
+ }
401
+ else {
402
+ warning = 'Локальный SMS-шлюз не настроен — скопируйте ссылку и отправьте получателю вручную.';
403
+ }
404
+ }
376
405
  else if ((channel === 'telegram' || channel === 'max') && recipient) {
377
406
  const bot = await resolveChannelBotForPoint(this, channel);
378
407
  const looksLikeId = /^-?\d{4,}$/.test(recipient) || (channel === 'max' && /^[a-z0-9_-]{4,}$/i.test(recipient) && !recipient.startsWith('@'));
@@ -412,4 +441,116 @@ export const INVITE_METHODS = Object.freeze({
412
441
  };
413
442
  },
414
443
  },
444
+
445
+ invite_lookup_user: {
446
+ level: 'read',
447
+ fn: async function (params = {}) {
448
+ await this.assertAccess(params, this.constructor.ACCESS_LEVEL.BOSS);
449
+ const post = (params.post && typeof params.post === 'object') ? params.post : params;
450
+ const rawEmail = String(post.email || params.email || '').trim().toLowerCase();
451
+ const rawPhone = String(post.phone || params.phone || '').trim();
452
+ const normPhone = rawPhone ? normalizePhone(rawPhone) : '';
453
+ const usersRoot = await globalThis.WORK?.$users;
454
+ if (!usersRoot)
455
+ return { exists: false };
456
+ const list = await usersRoot.items;
457
+ let matched = null;
458
+ if (rawEmail && rawEmail.includes('@')) {
459
+ const targetUid = crypto.createHash('sha256').update(rawEmail, 'utf8').digest('hex').slice(0, 16).toUpperCase();
460
+ for (const u of (Array.isArray(list) ? list : [])) {
461
+ if (!u)
462
+ continue;
463
+ await u.init?.catch?.(() => {});
464
+ const uEmail = String(u.DATA?.email || '').trim().toLowerCase();
465
+ if (u.id === targetUid || (uEmail && uEmail === rawEmail)) {
466
+ matched = u;
467
+ break;
468
+ }
469
+ }
470
+ }
471
+ if (!matched && normPhone) {
472
+ for (const u of (Array.isArray(list) ? list : [])) {
473
+ if (!u)
474
+ continue;
475
+ await u.init?.catch?.(() => {});
476
+ const uPhone = normalizePhone(u.DATA?.phone || '');
477
+ if (uPhone && uPhone === normPhone) {
478
+ matched = u;
479
+ break;
480
+ }
481
+ }
482
+ }
483
+ if (!matched)
484
+ return { exists: false };
485
+ const enabled = typeof matched._ownUserEnabledSync === 'function' ? matched._ownUserEnabledSync() : (matched.DATA?.enabled !== false);
486
+ return {
487
+ exists: true,
488
+ uid: matched.id,
489
+ label: matched.DATA?.label || matched.label || matched.DATA?.email || matched.DATA?.phone || matched.id,
490
+ email: matched.DATA?.email || '',
491
+ phone: matched.DATA?.phone || '',
492
+ enabled,
493
+ };
494
+ },
495
+ },
496
+
497
+ invite_assign_existing: {
498
+ level: 'write',
499
+ fn: async function (params = {}) {
500
+ await this.assertAccess(params, this.constructor.ACCESS_LEVEL.BOSS);
501
+ const post = (params.post && typeof params.post === 'object') ? params.post : params;
502
+ const cleanUid = String(post.uid || params.uid || '').trim().toUpperCase();
503
+ const trail = String(post.trail || params.trail || '').trim();
504
+ if (!cleanUid)
505
+ throw new Error('Не указан пользователь (uid)');
506
+ if (!trail)
507
+ throw new Error('Не выбрано рабочее место');
508
+
509
+ const usersRoot = await globalThis.WORK?.$users;
510
+ const userNode = usersRoot ? await usersRoot.get_item('//' + cleanUid).catch(() => null) : null;
511
+ if (!userNode)
512
+ throw new Error('Пользователь не найден на сервере');
513
+ await userNode.init?.catch?.(() => {});
514
+ if (typeof userNode._ownUserEnabledSync === 'function' && !userNode._ownUserEnabledSync())
515
+ throw new Error('Учётная запись пользователя отключена администратором');
516
+
517
+ await this.init;
518
+ const data = JSON.parse(JSON.stringify(this.DATA || {}));
519
+ data['#security'] ??= {};
520
+ let placeLabel = '';
521
+ if (trail === 'BOSS') {
522
+ placeLabel = 'Руководитель (BOSS)';
523
+ data['#security'].BOSS ??= [];
524
+ if (!data['#security'].BOSS.includes(cleanUid))
525
+ data['#security'].BOSS.push(cleanUid);
526
+ }
527
+ else {
528
+ data['#security'].ROLES ??= [];
529
+ const roleNode = findRoleByTrail(data['#security'].ROLES, trail);
530
+ if (!roleNode)
531
+ throw new Error(`Рабочее место «${trail}» не найдено`);
532
+ placeLabel = roleNode.label || roleNode.id;
533
+ roleNode.USERS ??= [];
534
+ if (!roleNode.USERS.includes(cleanUid))
535
+ roleNode.USERS.push(cleanUid);
536
+ }
537
+
538
+ await this.save({
539
+ post: this.constructor.toScript(data),
540
+ session: sysSession(),
541
+ sockets: params.sockets,
542
+ });
543
+ this.reset?.();
544
+ this.fire?.('changed', { value: null });
545
+ audit('invite_assign_existing', { pointPath: this.path || '/', uid: cleanUid, trail, params });
546
+ return {
547
+ ok: true,
548
+ uid: cleanUid,
549
+ pointPath: this.path || '/',
550
+ pointLabel: this.label || this.DATA?.label || this.id || this.path || 'WORK',
551
+ trail,
552
+ placeLabel,
553
+ };
554
+ },
555
+ },
415
556
  });
@@ -364,6 +364,15 @@ export async function sendMessage(storage, params = {}) {
364
364
  const isParticipant = thread.participants.some(p => p.uid === uid);
365
365
  if (!isParticipant && !isTwinBot)
366
366
  throw new Error(ACCESS_DENIED);
367
+ if (thread.kind === 'dm' && !isTwinBot && !isSysSession(params)) {
368
+ const peerIds = thread.participants.map(p => p.uid).filter(id => id && id !== uid);
369
+ const usersRoot = peerIds.length ? await Promise.resolve(globalThis.WORK?.$users).catch(() => null) : null;
370
+ for (const peerId of peerIds) {
371
+ const peerNode = usersRoot ? await Promise.resolve(usersRoot.get_item?.('//' + peerId)).catch(() => null) : null;
372
+ if (peerNode && typeof peerNode._ownUserEnabledSync === 'function' && !peerNode._ownUserEnabledSync())
373
+ throw new Error('Пользователь отключён администратором');
374
+ }
375
+ }
367
376
  if (thread.kind !== 'dm' && !isTwinBot && !isSysSession(params)) {
368
377
  const canSee = await storage.canSee?.(storage, params).catch(() => false);
369
378
  const roles = await storage.roles?.(params).catch(() => []) || [];
@@ -566,12 +575,16 @@ export async function visibleContacts(storage, params = {}) {
566
575
  const userMap = new Map();
567
576
  for (const u of allUserItems) {
568
577
  await u.init?.catch?.(() => {});
578
+ const enabled = typeof u._ownUserEnabledSync === 'function'
579
+ ? u._ownUserEnabledSync()
580
+ : (u.DATA?.enabled !== false && u.DATA?.blocked !== true);
569
581
  userMap.set(u.id, {
570
582
  id: u.id,
571
583
  path: u.path || `/USERS/${u.id}`,
572
584
  label: u.DATA?.label || u.label || u.id,
573
585
  icon: u.DATA?.icon || u.icon || '',
574
586
  online: Boolean(u.online),
587
+ enabled,
575
588
  self: u.id === uid,
576
589
  external: false,
577
590
  });
@@ -675,6 +688,8 @@ export async function visibleContacts(storage, params = {}) {
675
688
  if (id === uid) continue;
676
689
  const entry = userMap.get(id);
677
690
  if (!entry) continue;
691
+ if (!isWorkBoss && entry.enabled === false)
692
+ continue;
678
693
  out.push({
679
694
  ...entry,
680
695
  external: externalOnlyIds.has(id),
@@ -1011,6 +1011,11 @@ export const classSecurityMethods = {
1011
1011
  return all.filter(u => {
1012
1012
  if (!u?.id || seen.has(u.id))
1013
1013
  return false;
1014
+ const enabled = typeof u._ownUserEnabledSync === 'function'
1015
+ ? u._ownUserEnabledSync()
1016
+ : (u.DATA?.enabled !== false && u.DATA?.blocked !== true);
1017
+ if (!enabled)
1018
+ return false;
1014
1019
  seen.add(u.id);
1015
1020
  return true;
1016
1021
  });
@@ -257,6 +257,37 @@ export class $server extends $class {
257
257
  async get_public_vapid() {
258
258
  return getPublicVapid(vapidKeys);
259
259
  }
260
+ async support_contact_info() {
261
+ const { getPublicSupportContact } = await import('../host/sms.js');
262
+ return { contact: getPublicSupportContact() };
263
+ }
264
+ async sms_settings_get(params = {}) {
265
+ await this.assertAccess(params, $class.ACCESS_LEVEL.BOSS);
266
+ const { getMaskedSmsSettings } = await import('../host/sms.js');
267
+ return getMaskedSmsSettings();
268
+ }
269
+ async sms_settings_save(params = {}) {
270
+ await this.assertAccess(params, $class.ACCESS_LEVEL.BOSS);
271
+ const { writeSmsConfig } = await import('../host/sms.js');
272
+ const body = (params.post && typeof params.post === 'object') ? params.post : params;
273
+ return writeSmsConfig(body);
274
+ }
275
+ async sms_settings_test(params = {}) {
276
+ await this.assertAccess(params, $class.ACCESS_LEVEL.BOSS);
277
+ const { sendViaSmsProvider, normalizePhone } = await import('../host/sms.js');
278
+ const body = (params.post && typeof params.post === 'object') ? params.post : params;
279
+ const phone = normalizePhone(body.phone || '');
280
+ if (!phone)
281
+ throw new Error('Укажите корректный номер телефона для проверки (например, +79991234567)');
282
+ const code = String(Math.floor(100000 + Math.random() * 900000));
283
+ const res = await sendViaSmsProvider({
284
+ phone,
285
+ code,
286
+ message: `Тестовое сообщение ODANT-WORK (${code})`,
287
+ ip: params.request?.socket?.remoteAddress || '',
288
+ });
289
+ return { ok: true, phone, ...res };
290
+ }
260
291
  async store_push_subscription(params) {
261
292
  this._assertPushSubject(params);
262
293
  const endpoint = params.post?.endpoint;
@@ -169,6 +169,8 @@ export class $user extends $class {
169
169
  return true;
170
170
  if (globalThis.WORK && await this._isWorkBoss(params))
171
171
  return true;
172
+ if (!this._ownUserEnabledSync())
173
+ return false;
172
174
  const { visibleContacts } = await import('./chat-threads.js');
173
175
  const contacts = await visibleContacts(this, params);
174
176
  return contacts.some(c => c.id === this.id);