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.
@@ -0,0 +1,351 @@
1
+ import * as crypto from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const BOOT_DIR = path.resolve('.');
6
+ const REL_SMS_FILE = '#system/sms.json';
7
+
8
+ function smsFileCandidates() {
9
+ const cwd = path.resolve('.');
10
+ const list = [path.join(cwd, REL_SMS_FILE)];
11
+ if (cwd !== BOOT_DIR)
12
+ list.push(path.join(BOOT_DIR, REL_SMS_FILE));
13
+ return list;
14
+ }
15
+
16
+ export function getSmsConfigPath() {
17
+ return path.resolve(REL_SMS_FILE);
18
+ }
19
+
20
+ /**
21
+ * Нормализация номера телефона в E.164 (`+79991234567`).
22
+ * Поддерживает РФ 11-значные `8...` и `7...`, а также международный `+...` (7–15 цифр).
23
+ */
24
+ export function normalizePhone(raw = '') {
25
+ let s = String(raw || '').trim();
26
+ if (!s)
27
+ return '';
28
+ s = s.replace(/[\s().-]+/g, '');
29
+ if (s.startsWith('00'))
30
+ s = '+' + s.slice(2);
31
+ if (!s.startsWith('+')) {
32
+ if (/^8\d{10}$/.test(s))
33
+ s = '+7' + s.slice(1);
34
+ else if (/^7\d{10}$/.test(s))
35
+ s = '+' + s;
36
+ else
37
+ return '';
38
+ }
39
+ if (!/^\+[1-9]\d{6,14}$/.test(s))
40
+ return '';
41
+ return s;
42
+ }
43
+
44
+ export function isValidPhone(raw = '') {
45
+ return Boolean(normalizePhone(raw));
46
+ }
47
+
48
+ /**
49
+ * Детерминированный первичный uid для пользователя, впервые зарегистрированного по телефону.
50
+ * Префикс `tel:` исключает коллизии с `SHA-256(email)`.
51
+ */
52
+ export function uidOfPhone(phone) {
53
+ const norm = normalizePhone(phone);
54
+ if (!norm)
55
+ throw new Error('Некорректный номер телефона (используйте международный формат, например +79991234567)');
56
+ return crypto.createHash('sha256').update('tel:' + norm, 'utf8').digest('hex').slice(0, 16).toUpperCase();
57
+ }
58
+
59
+ export function maskSecret(val = '') {
60
+ const s = String(val || '').trim();
61
+ if (!s)
62
+ return '';
63
+ if (s.length <= 6)
64
+ return '***';
65
+ return s.slice(0, 3) + '***' + s.slice(-3);
66
+ }
67
+
68
+ export function isMaskedSecret(val = '') {
69
+ return String(val || '').includes('***');
70
+ }
71
+
72
+ function defaultSmsConfig() {
73
+ return {
74
+ provider: 'none', // 'none' | 'smsru' | 'smsc' | 'webhook'
75
+ mode: 'sms', // 'sms' | 'flashcall'
76
+ apiKey: '',
77
+ login: '',
78
+ password: '',
79
+ sender: '',
80
+ webhookUrl: '',
81
+ webhookToken: '',
82
+ supportContact: {
83
+ label: '',
84
+ email: '',
85
+ phone: '',
86
+ note: '',
87
+ },
88
+ };
89
+ }
90
+
91
+ export function readSmsConfig() {
92
+ const base = defaultSmsConfig();
93
+ for (const filePath of smsFileCandidates()) {
94
+ try {
95
+ if (!fs.existsSync(filePath))
96
+ continue;
97
+ const raw = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
98
+ if (!raw || typeof raw !== 'object')
99
+ continue;
100
+ const sc = raw.supportContact && typeof raw.supportContact === 'object' ? raw.supportContact : {};
101
+ return {
102
+ provider: ['none', 'smsru', 'smsc', 'webhook'].includes(String(raw.provider || '').toLowerCase())
103
+ ? String(raw.provider).toLowerCase()
104
+ : 'none',
105
+ mode: String(raw.mode || '').toLowerCase() === 'flashcall' ? 'flashcall' : 'sms',
106
+ apiKey: String(raw.apiKey || '').trim(),
107
+ login: String(raw.login || '').trim(),
108
+ password: String(raw.password || '').trim(),
109
+ sender: String(raw.sender || '').trim(),
110
+ webhookUrl: String(raw.webhookUrl || '').trim(),
111
+ webhookToken: String(raw.webhookToken || '').trim(),
112
+ supportContact: {
113
+ label: String(sc.label || '').trim(),
114
+ email: String(sc.email || '').trim(),
115
+ phone: String(sc.phone || '').trim(),
116
+ note: String(sc.note || '').trim(),
117
+ },
118
+ };
119
+ }
120
+ catch { /* ignore broken json */ }
121
+ }
122
+ return base;
123
+ }
124
+
125
+ export function writeSmsConfig(patch = {}) {
126
+ const cur = readSmsConfig();
127
+ const next = {
128
+ provider: ['none', 'smsru', 'smsc', 'webhook'].includes(String(patch.provider ?? cur.provider).toLowerCase())
129
+ ? String(patch.provider ?? cur.provider).toLowerCase()
130
+ : 'none',
131
+ mode: String(patch.mode ?? cur.mode).toLowerCase() === 'flashcall' ? 'flashcall' : 'sms',
132
+ apiKey: patch.apiKey !== undefined && !isMaskedSecret(patch.apiKey) ? String(patch.apiKey || '').trim() : cur.apiKey,
133
+ login: patch.login !== undefined ? String(patch.login || '').trim() : cur.login,
134
+ password: patch.password !== undefined && !isMaskedSecret(patch.password) ? String(patch.password || '').trim() : cur.password,
135
+ sender: patch.sender !== undefined ? String(patch.sender || '').trim() : cur.sender,
136
+ webhookUrl: patch.webhookUrl !== undefined ? String(patch.webhookUrl || '').trim() : cur.webhookUrl,
137
+ webhookToken: patch.webhookToken !== undefined && !isMaskedSecret(patch.webhookToken) ? String(patch.webhookToken || '').trim() : cur.webhookToken,
138
+ supportContact: {
139
+ label: patch.supportContact?.label !== undefined ? String(patch.supportContact.label || '').trim().slice(0, 120) : cur.supportContact.label,
140
+ email: patch.supportContact?.email !== undefined ? String(patch.supportContact.email || '').trim().slice(0, 120) : cur.supportContact.email,
141
+ phone: patch.supportContact?.phone !== undefined ? String(patch.supportContact.phone || '').trim().slice(0, 40) : cur.supportContact.phone,
142
+ note: patch.supportContact?.note !== undefined ? String(patch.supportContact.note || '').trim().slice(0, 300) : cur.supportContact.note,
143
+ },
144
+ };
145
+ const filePath = getSmsConfigPath();
146
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
147
+ fs.writeFileSync(filePath, JSON.stringify(next, null, 2), 'utf-8');
148
+ return getMaskedSmsSettings(next);
149
+ }
150
+
151
+ export function hasLocalSmsGateway(cfg = readSmsConfig()) {
152
+ if (!cfg || cfg.provider === 'none')
153
+ return false;
154
+ if (cfg.provider === 'smsru')
155
+ return Boolean(cfg.apiKey);
156
+ if (cfg.provider === 'smsc')
157
+ return Boolean(cfg.login && cfg.password);
158
+ if (cfg.provider === 'webhook')
159
+ return Boolean(cfg.webhookUrl);
160
+ return false;
161
+ }
162
+
163
+ export function getMaskedSmsSettings(cfg = readSmsConfig()) {
164
+ return {
165
+ provider: cfg.provider,
166
+ mode: cfg.mode,
167
+ apiKey: maskSecret(cfg.apiKey),
168
+ hasApiKey: Boolean(cfg.apiKey),
169
+ login: cfg.login,
170
+ password: maskSecret(cfg.password),
171
+ hasPassword: Boolean(cfg.password),
172
+ sender: cfg.sender,
173
+ webhookUrl: cfg.webhookUrl,
174
+ webhookToken: maskSecret(cfg.webhookToken),
175
+ hasWebhookToken: Boolean(cfg.webhookToken),
176
+ connected: hasLocalSmsGateway(cfg),
177
+ supportContact: { ...cfg.supportContact },
178
+ };
179
+ }
180
+
181
+ /**
182
+ * Публичный контакт администратора (возвращается на экран блокировки ТОЛЬКО если явно заполнен).
183
+ */
184
+ export function getPublicSupportContact(cfg = readSmsConfig()) {
185
+ const sc = cfg?.supportContact || {};
186
+ const out = {
187
+ label: String(sc.label || '').trim(),
188
+ email: String(sc.email || '').trim(),
189
+ phone: String(sc.phone || '').trim(),
190
+ note: String(sc.note || '').trim(),
191
+ };
192
+ if (!out.label && !out.email && !out.phone && !out.note)
193
+ return null;
194
+ return out;
195
+ }
196
+
197
+ /**
198
+ * Отправить SMS или Flash-Call через локально настроенный провайдер.
199
+ * При `mode: 'flashcall'` у SMS.ru/SMSC.ru оператор сам звонит и может вернуть `overrideCode`
200
+ * (последние 4–6 цифр номера звонящего).
201
+ */
202
+ export async function sendViaSmsProvider({
203
+ phone,
204
+ code = '',
205
+ message = '',
206
+ mode,
207
+ ip = '',
208
+ config = null,
209
+ fetchImpl = globalThis.fetch,
210
+ } = {}) {
211
+ const cfg = config || readSmsConfig();
212
+ if (!hasLocalSmsGateway(cfg))
213
+ throw new Error('Локальный SMS-шлюз не настроен');
214
+ const norm = normalizePhone(phone);
215
+ if (!norm)
216
+ throw new Error('Некорректный номер телефона');
217
+ const digits = norm.replace(/^\+/, '');
218
+ const effMode = mode === 'flashcall' ? 'flashcall' : (mode === 'sms' ? 'sms' : cfg.mode);
219
+ const text = String(message || (code ? `Код подтверждения ODANT-WORK: ${code}` : '')).trim();
220
+ const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
221
+ ? AbortSignal.timeout(15_000)
222
+ : undefined;
223
+
224
+ if (cfg.provider === 'smsru') {
225
+ if (effMode === 'flashcall' && !message) {
226
+ const qs = new URLSearchParams({
227
+ phone: digits,
228
+ api_id: cfg.apiKey,
229
+ ip: ip || '127.0.0.1',
230
+ json: '1',
231
+ });
232
+ const res = await fetchImpl(`https://sms.ru/code/call?${qs.toString()}`, { signal });
233
+ const data = await res.json().catch(() => ({}));
234
+ if (!res.ok || data?.status !== 'OK')
235
+ throw new Error(data?.status_text || `SMS.ru flash-call ошибка (HTTP ${res.status})`);
236
+ return {
237
+ ok: true,
238
+ provider: 'smsru',
239
+ mode: 'flashcall',
240
+ overrideCode: data?.code ? String(data.code).trim() : '',
241
+ };
242
+ }
243
+ const form = new URLSearchParams({
244
+ api_id: cfg.apiKey,
245
+ to: digits,
246
+ msg: text,
247
+ json: '1',
248
+ ...(cfg.sender ? { from: cfg.sender } : {}),
249
+ });
250
+ const res = await fetchImpl('https://sms.ru/sms/send', {
251
+ method: 'POST',
252
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
253
+ body: form.toString(),
254
+ signal,
255
+ });
256
+ const data = await res.json().catch(() => ({}));
257
+ const entry = data?.sms?.[digits];
258
+ if (!res.ok || data?.status !== 'OK' || (entry && entry.status !== 'OK'))
259
+ throw new Error(entry?.status_text || data?.status_text || `SMS.ru ошибка (HTTP ${res.status})`);
260
+ return { ok: true, provider: 'smsru', mode: 'sms' };
261
+ }
262
+
263
+ if (cfg.provider === 'smsc') {
264
+ const form = new URLSearchParams({
265
+ login: cfg.login,
266
+ psw: cfg.password,
267
+ phones: norm,
268
+ fmt: '3',
269
+ charset: 'utf-8',
270
+ ...(effMode === 'flashcall' && !message
271
+ ? { mes: 'code', call: '1' }
272
+ : { mes: text, ...(cfg.sender ? { sender: cfg.sender } : {}) }),
273
+ });
274
+ const res = await fetchImpl('https://smsc.ru/sys/send.php', {
275
+ method: 'POST',
276
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
277
+ body: form.toString(),
278
+ signal,
279
+ });
280
+ const data = await res.json().catch(() => ({}));
281
+ if (!res.ok || data?.error)
282
+ throw new Error(data?.error || `SMSC.ru ошибка (HTTP ${res.status})`);
283
+ return {
284
+ ok: true,
285
+ provider: 'smsc',
286
+ mode: effMode,
287
+ ...(effMode === 'flashcall' && data?.code ? { overrideCode: String(data.code).trim() } : {}),
288
+ };
289
+ }
290
+
291
+ if (cfg.provider === 'webhook') {
292
+ const res = await fetchImpl(cfg.webhookUrl, {
293
+ method: 'POST',
294
+ headers: {
295
+ 'Content-Type': 'application/json',
296
+ ...(cfg.webhookToken ? { Authorization: `Bearer ${cfg.webhookToken}` } : {}),
297
+ },
298
+ body: JSON.stringify({
299
+ phone: norm,
300
+ code: String(code || ''),
301
+ message: text,
302
+ mode: effMode,
303
+ ...(cfg.sender ? { sender: cfg.sender } : {}),
304
+ }),
305
+ signal,
306
+ });
307
+ if (!res.ok) {
308
+ const errTxt = await res.text().catch(() => '');
309
+ throw new Error(errTxt || `SMS Webhook ошибка (HTTP ${res.status})`);
310
+ }
311
+ const data = await res.json().catch(() => ({}));
312
+ return {
313
+ ok: true,
314
+ provider: 'webhook',
315
+ mode: effMode,
316
+ ...(data?.code ? { overrideCode: String(data.code).trim() } : {}),
317
+ };
318
+ }
319
+
320
+ throw new Error(`Неизвестный SMS-провайдер: ${cfg.provider}`);
321
+ }
322
+
323
+ /**
324
+ * Попытаться отправить код подтверждения в уже привязанный Telegram/MAX чат пользователя.
325
+ */
326
+ export async function sendPhoneCodeViaMessenger({ uid, code, message = '' } = {}) {
327
+ if (!uid || !code || !globalThis.WORK)
328
+ return { ok: false };
329
+ try {
330
+ const { readUserBinding, resolveBotForPoint, getAdapter } = await import('../modules/notify/index.js');
331
+ const usersRoot = await globalThis.WORK.$users;
332
+ const userNode = usersRoot ? await usersRoot.get_item('//' + uid).catch(() => null) : null;
333
+ if (!userNode)
334
+ return { ok: false };
335
+ const binding = readUserBinding(userNode);
336
+ const text = message || `Код подтверждения входа ODANT-WORK: ${code}\nДействует 10 минут.`;
337
+ for (const ch of ['telegram', 'max']) {
338
+ const chat = binding?.chats?.[ch];
339
+ if (!chat?.chatId)
340
+ continue;
341
+ const bot = await resolveBotForPoint(globalThis.WORK, ch, chat.botId || '').catch(() => null);
342
+ if (!bot?.token)
343
+ continue;
344
+ const adapter = getAdapter(ch);
345
+ await adapter.sendMessage(bot.token, { chatId: chat.chatId, text, apiUrl: bot.apiUrl });
346
+ return { ok: true, channel: ch };
347
+ }
348
+ }
349
+ catch { /* fallback to SMS/hub */ }
350
+ return { ok: false };
351
+ }
@@ -39,10 +39,10 @@ const allSessions = () => Object.values($server?.sessions || {});
39
39
  /** Уведомить сессии о смене presence пользователя (online).
40
40
  * F24: анонимным сессиям (без вошедшего) местоположение людей не рассылаем.
41
41
  * Экспортировано для теста фильтра. */
42
- export function broadcastUserPath($user) {
43
- if (!$user?.short)
42
+ export function broadcastUserPath(user) {
43
+ if (!user?.short)
44
44
  return;
45
- const message = JSON.stringify({ path: $user.short, initiator: $user.id });
45
+ const message = JSON.stringify({ path: user.short, initiator: user.id, online: Boolean(user.online) });
46
46
  for (const session of allSessions()) {
47
47
  if (!session?.$user)
48
48
  continue; // анонимная сессия — без присутствия
@@ -1250,7 +1250,9 @@ export async function syncWithLicenseHub({ hubUrl, licensePath, systemDir, token
1250
1250
  * парой licenseId + HWID/отпечатком узла или привязанным токеном владельца (owk1...).
1251
1251
  */
1252
1252
  export async function sendLoginCodeViaLicenseHub({
1253
- email,
1253
+ email = '',
1254
+ phone = '',
1255
+ channel = '',
1254
1256
  code,
1255
1257
  hubUrl,
1256
1258
  systemDir,
@@ -1262,8 +1264,9 @@ export async function sendLoginCodeViaLicenseHub({
1262
1264
  const lic = loadLocalLicense(licensePath || LICENSE_FILE, { systemDir: sysDir, trustedPublicKey });
1263
1265
  if (lic.unlicensed) {
1264
1266
  throw new Error(
1265
- 'Локальная система не подключена к серверу поддержки: привяжите лицензию владельца '
1266
- + 'или настройте почтовый сервер в #system/mail.json'
1267
+ phone
1268
+ ? 'Локальная система не подключена к серверу поддержки: привяжите лицензию владельца или настройте SMS-шлюз в «Система → SMS / Контакты»'
1269
+ : 'Локальная система не подключена к серверу поддержки: привяжите лицензию владельца или настройте почтовый сервер в #system/mail.json'
1267
1270
  );
1268
1271
  }
1269
1272
 
@@ -1280,7 +1283,9 @@ export async function sendLoginCodeViaLicenseHub({
1280
1283
  ? AbortSignal.timeout(15000)
1281
1284
  : undefined,
1282
1285
  body: JSON.stringify({
1283
- email,
1286
+ ...(email ? { email } : {}),
1287
+ ...(phone ? { phone } : {}),
1288
+ ...(channel ? { channel } : {}),
1284
1289
  ...(code ? { code } : {}),
1285
1290
  licenseId: lic.licenseId,
1286
1291
  hwid: lic.hardware?.hwid || hw.hwid,