odant-work 1.0.108 → 1.0.110

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
  });
@@ -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;