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.
- package/$server/$folder/$class/$structure/$server/handlers/pages/form/system/sms/$handler/class.js +293 -0
- package/$server/$folder/$class/$structure/handlers/methods/invite/$handler/class.js +31 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +2 -2
- package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +25 -2
- package/$server/$folder/handlers/pages/form/$handler/class.js +92 -34
- package/$server/$folder/lib/consultant/consultant.js +58 -6
- package/$server/$folder/lib/icon/icon.js +2 -1
- package/$server/$folder/lib/invite/invite.js +370 -0
- package/$server/$folder/lib/node-explorer/node-explorer.js +0 -3
- package/$server/$folder/lib/prompt-bar/prompt-bar.js +1 -1
- package/$server/$folder/lib/tree/tree.js +10 -5
- package/package.json +1 -1
- package/sources/client.js +63 -5
- package/sources/host/auth-methods.js +398 -27
- package/sources/host/sms.js +351 -0
- package/sources/host/websocket.js +3 -3
- package/sources/modules/license/index.js +9 -4
- package/sources/modules/user-profile/user-profile.js +337 -23
- package/sources/server/access/gateway.js +4 -1
- package/sources/server/access/invites.js +149 -8
- package/sources/server/chat-threads.js +15 -0
- package/sources/server/class/security.js +5 -0
- package/sources/server/server.js +31 -0
- package/sources/server/user.js +2 -0
|
@@ -8,6 +8,13 @@ import { notifyUserOnline } from './websocket.js';
|
|
|
8
8
|
import { audit } from '../server/access/audit.js';
|
|
9
9
|
import { inspectInvite, consumeInvite } from '../server/access/invites.js';
|
|
10
10
|
import { assertWorkplaceAvailableForLogin, sendLoginCodeViaLicenseHub } from '../modules/license/index.js';
|
|
11
|
+
import {
|
|
12
|
+
normalizePhone,
|
|
13
|
+
uidOfPhone,
|
|
14
|
+
hasLocalSmsGateway,
|
|
15
|
+
sendViaSmsProvider,
|
|
16
|
+
sendPhoneCodeViaMessenger,
|
|
17
|
+
} from './sms.js';
|
|
11
18
|
|
|
12
19
|
const REGISTER_CODE_TTL_MS = 10 * 60 * 1000;
|
|
13
20
|
const REGISTER_MAX_ATTEMPTS = 5;
|
|
@@ -16,11 +23,21 @@ const REGISTER_STARTS_PER_HOUR = 5;
|
|
|
16
23
|
const MAX_ICON_BYTES = 512 * 1024;
|
|
17
24
|
const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
18
25
|
const UID_RE = /^[0-9A-F]{16}$/;
|
|
26
|
+
const sysSession = () => ({ $user: globalThis.WORK });
|
|
19
27
|
|
|
20
28
|
/** Незавершённые входы: challengeId → { value, uid, expiresAt }. Одноразовые, со сроком. */
|
|
21
29
|
const pendingLogins = new Map();
|
|
22
30
|
|
|
23
|
-
/**
|
|
31
|
+
/** Одноразовые challenge для обращения отключённых пользователей. */
|
|
32
|
+
const pendingAppeals = new Map();
|
|
33
|
+
|
|
34
|
+
/** Последние обращения отключённых пользователей (rate-limit 1 раз в час). */
|
|
35
|
+
const appealsByUid = new Map();
|
|
36
|
+
|
|
37
|
+
/** Незавершённые привязки телефона в профиле: key → { uid, phone, code, at, attempts }. */
|
|
38
|
+
const pendingPhoneBinds = new Map();
|
|
39
|
+
|
|
40
|
+
/** Незавершённые регистрации (до проверки кода): registrationId → { id, uid, email, phone, contactType, code, at, attempts }. */
|
|
24
41
|
const pendingRegistrations = new Map();
|
|
25
42
|
|
|
26
43
|
/** Подтверждённые кодом регистрации (ожидание подписи ключа): registrationId → credentials. */
|
|
@@ -47,6 +64,55 @@ export function uidOfEmail(email) {
|
|
|
47
64
|
return crypto.createHash('sha256').update(String(email), 'utf8').digest('hex').slice(0, 16).toUpperCase();
|
|
48
65
|
}
|
|
49
66
|
|
|
67
|
+
export { uidOfPhone, normalizePhone };
|
|
68
|
+
|
|
69
|
+
async function findUserByPhone(serverObj, normPhone) {
|
|
70
|
+
if (!normPhone)
|
|
71
|
+
return null;
|
|
72
|
+
try {
|
|
73
|
+
const usersRoot = await (serverObj?.$users || globalThis.WORK?.$users);
|
|
74
|
+
const list = await usersRoot?.items;
|
|
75
|
+
for (const u of (Array.isArray(list) ? list : [])) {
|
|
76
|
+
if (!u)
|
|
77
|
+
continue;
|
|
78
|
+
await u.init?.catch?.(() => {});
|
|
79
|
+
const p = normalizePhone(u.DATA?.phone || '');
|
|
80
|
+
if (p && p === normPhone && u.DATA?.phoneVerified !== false)
|
|
81
|
+
return u;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch { /* ignore */ }
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function resolveUidForPhone(serverObj, normPhone) {
|
|
89
|
+
const existing = await findUserByPhone(serverObj, normPhone);
|
|
90
|
+
if (existing?.id)
|
|
91
|
+
return { uid: String(existing.id).toUpperCase(), existing };
|
|
92
|
+
return { uid: uidOfPhone(normPhone), existing: null };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function assertNotDisabledUser(serverObj, uid) {
|
|
96
|
+
if (!uid)
|
|
97
|
+
return null;
|
|
98
|
+
try {
|
|
99
|
+
const usersRoot = await (serverObj?.$users || globalThis.WORK?.$users);
|
|
100
|
+
const node = await usersRoot?.get_item?.('//' + uid).catch(() => null);
|
|
101
|
+
if (node) {
|
|
102
|
+
node.reset?.();
|
|
103
|
+
await node.init?.catch?.(() => {});
|
|
104
|
+
if (typeof node._ownUserEnabledSync === 'function' && !node._ownUserEnabledSync())
|
|
105
|
+
throw new Error('Учётная запись отключена администратором');
|
|
106
|
+
}
|
|
107
|
+
return node;
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
if (/отключена администратором/i.test(String(err?.message || '')))
|
|
111
|
+
throw err;
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
50
116
|
function throttleStart(session, email) {
|
|
51
117
|
const now = Date.now();
|
|
52
118
|
if (session.registration?.at && now - session.registration.at < REGISTER_START_INTERVAL_MS)
|
|
@@ -94,15 +160,34 @@ async function isFirstOrBossUser(uid) {
|
|
|
94
160
|
|
|
95
161
|
export const authMethods = {
|
|
96
162
|
async user_register_start(params = {}) {
|
|
97
|
-
let { uid, email, inviteToken, registrationId: postRegId } = params.post || {};
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
163
|
+
let { uid, email, phone, contactType, inviteToken, registrationId: postRegId } = params.post || {};
|
|
164
|
+
const wantPhone = contactType === 'phone' || (Boolean(phone) && !email);
|
|
165
|
+
let expected = '';
|
|
166
|
+
let cleanEmail = '';
|
|
167
|
+
let normPhone = '';
|
|
168
|
+
|
|
169
|
+
if (wantPhone) {
|
|
170
|
+
normPhone = normalizePhone(phone || '');
|
|
171
|
+
if (!normPhone)
|
|
172
|
+
throw new Error("Некорректный номер телефона (укажите номер в формате +79991234567)");
|
|
173
|
+
const resolved = await resolveUidForPhone(this, normPhone);
|
|
174
|
+
expected = resolved.uid;
|
|
175
|
+
if (uid != null && String(uid).toUpperCase() !== expected && String(uid).toUpperCase() !== uidOfPhone(normPhone))
|
|
176
|
+
throw new Error("Неверный uid");
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
if (!email || typeof email !== 'string')
|
|
180
|
+
throw new Error("Не указан email или телефон");
|
|
181
|
+
cleanEmail = String(email).trim();
|
|
182
|
+
expected = uidOfEmail(cleanEmail);
|
|
183
|
+
if (uid != null && String(uid).toUpperCase() !== expected)
|
|
184
|
+
throw new Error("Неверный uid");
|
|
185
|
+
}
|
|
103
186
|
uid = expected;
|
|
187
|
+
await assertNotDisabledUser(this, uid);
|
|
188
|
+
|
|
104
189
|
let session = params.session;
|
|
105
|
-
throttleStart(session,
|
|
190
|
+
throttleStart(session, wantPhone ? ('tel:' + normPhone) : cleanEmail);
|
|
106
191
|
const now = Date.now();
|
|
107
192
|
prunePendingRegistrations(now);
|
|
108
193
|
const rawRegId = postRegId ?? params.registrationId;
|
|
@@ -118,13 +203,87 @@ export const authMethods = {
|
|
|
118
203
|
if (pendingRegistrations.size >= 10_000)
|
|
119
204
|
throw new Error("Слишком много незавершённых регистраций, повторите позже");
|
|
120
205
|
let code = crypto.randomInt(0, 1_000_000).toString().padStart(6, '0');
|
|
121
|
-
const reg = {
|
|
206
|
+
const reg = {
|
|
207
|
+
id: regId,
|
|
208
|
+
uid,
|
|
209
|
+
email: cleanEmail,
|
|
210
|
+
phone: normPhone,
|
|
211
|
+
contactType: wantPhone ? 'phone' : 'email',
|
|
212
|
+
code,
|
|
213
|
+
at: now,
|
|
214
|
+
attempts: 0,
|
|
215
|
+
};
|
|
122
216
|
session.registration = reg;
|
|
123
217
|
pendingRegistrations.set(regId, reg);
|
|
124
218
|
delete session.credentials;
|
|
125
219
|
if (DEV_MODE) {
|
|
126
|
-
console.log('[DEV] Registration code for',
|
|
220
|
+
console.log('[DEV] Registration code for', wantPhone ? normPhone : cleanEmail, ':', code);
|
|
127
221
|
}
|
|
222
|
+
|
|
223
|
+
if (wantPhone) {
|
|
224
|
+
const firstOrBoss = await isFirstOrBossUser.call(this, uid);
|
|
225
|
+
if (firstOrBoss && !DEV_MODE) {
|
|
226
|
+
return {
|
|
227
|
+
uid,
|
|
228
|
+
autoCode: code,
|
|
229
|
+
message: 'Регистрация первого администратора (BOSS) выполняется напрямую без SMS-шлюза.',
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
if (inviteToken) {
|
|
233
|
+
const inv = inspectInvite(inviteToken);
|
|
234
|
+
if (inv?.valid && inv.channel === 'phone' && normalizePhone(inv.recipient || '') === normPhone) {
|
|
235
|
+
return {
|
|
236
|
+
uid,
|
|
237
|
+
autoCode: code,
|
|
238
|
+
message: `Приглашение на ${inv.placeLabel} подтверждено по номеру ${normPhone}.`,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (DEV_MODE) {
|
|
243
|
+
return { uid, message: 'На ваш телефон отправлен одноразовый код подтверждения.' };
|
|
244
|
+
}
|
|
245
|
+
const msgSent = await sendPhoneCodeViaMessenger({ uid, code });
|
|
246
|
+
if (msgSent?.ok) {
|
|
247
|
+
return { uid, message: 'Одноразовый код отправлен в ваш привязанный мессенджер.' };
|
|
248
|
+
}
|
|
249
|
+
if (hasLocalSmsGateway()) {
|
|
250
|
+
const res = await sendViaSmsProvider({
|
|
251
|
+
phone: normPhone,
|
|
252
|
+
code,
|
|
253
|
+
ip: params.request?.socket?.remoteAddress || '',
|
|
254
|
+
});
|
|
255
|
+
if (res?.overrideCode)
|
|
256
|
+
reg.code = String(res.overrideCode);
|
|
257
|
+
return {
|
|
258
|
+
uid,
|
|
259
|
+
mode: res?.mode || 'sms',
|
|
260
|
+
message: res?.mode === 'flashcall'
|
|
261
|
+
? 'Вам поступает звонок-сброс — введите последние цифры входящего номера.'
|
|
262
|
+
: 'На ваш телефон отправлено SMS с одноразовым кодом.',
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
let relayError = '';
|
|
266
|
+
try {
|
|
267
|
+
const relayed = await sendLoginCodeViaLicenseHub({ phone: normPhone, code, channel: 'sms' });
|
|
268
|
+
if (relayed?.ok) {
|
|
269
|
+
if (relayed.code)
|
|
270
|
+
reg.code = String(relayed.code);
|
|
271
|
+
return {
|
|
272
|
+
uid,
|
|
273
|
+
message: relayed.message || 'На ваш телефон отправлено SMS с одноразовым кодом.',
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
catch (relayErr) {
|
|
278
|
+
relayError = relayErr?.message || String(relayErr);
|
|
279
|
+
console.warn('[auth] SMS-код не отправлен через сервер поддержки:', relayError);
|
|
280
|
+
}
|
|
281
|
+
throw new Error(
|
|
282
|
+
'SMS-шлюз не настроен. Администратор (BOSS) может настроить провайдера в корне WORK → «Система → SMS / Контакты»'
|
|
283
|
+
+ (relayError ? `, либо подключить лицензию к серверу поддержки (${relayError})` : '')
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
128
287
|
const activeMailer = getMailer();
|
|
129
288
|
if (!activeMailer) {
|
|
130
289
|
const firstOrBoss = await isFirstOrBossUser.call(this, uid);
|
|
@@ -136,10 +295,10 @@ export const authMethods = {
|
|
|
136
295
|
}
|
|
137
296
|
if (inviteToken) {
|
|
138
297
|
const inv = inspectInvite(inviteToken);
|
|
139
|
-
if (inv?.valid && inv.channel === 'email' && inv.recipient && inv.recipient.toLowerCase() ===
|
|
298
|
+
if (inv?.valid && inv.channel === 'email' && inv.recipient && inv.recipient.toLowerCase() === cleanEmail.toLowerCase()) {
|
|
140
299
|
return {
|
|
141
300
|
autoCode: code,
|
|
142
|
-
message: `Приглашение на ${inv.placeLabel} подтверждено по адресу ${
|
|
301
|
+
message: `Приглашение на ${inv.placeLabel} подтверждено по адресу ${cleanEmail}.`,
|
|
143
302
|
};
|
|
144
303
|
}
|
|
145
304
|
}
|
|
@@ -149,7 +308,7 @@ export const authMethods = {
|
|
|
149
308
|
// Подключённый (лицензированный) клиент без собственного SMTP отправляет код через сервер поддержки
|
|
150
309
|
let relayError = '';
|
|
151
310
|
try {
|
|
152
|
-
const relayed = await sendLoginCodeViaLicenseHub({ email, code });
|
|
311
|
+
const relayed = await sendLoginCodeViaLicenseHub({ email: cleanEmail, code });
|
|
153
312
|
if (relayed?.ok)
|
|
154
313
|
return "На Вашу почту отправлено письмо с одноразовым кодом, введите его для продолжения регистрации.";
|
|
155
314
|
}
|
|
@@ -165,7 +324,7 @@ export const authMethods = {
|
|
|
165
324
|
const fromUser = activeMailer.fromUser || activeMailer.transport?.options?.auth?.user || 'noreply@localhost';
|
|
166
325
|
const mailOptions = {
|
|
167
326
|
from: `"ODANT-WORK" <${fromUser}>`,
|
|
168
|
-
to:
|
|
327
|
+
to: cleanEmail,
|
|
169
328
|
subject: 'Код подтверждения ODANT-WORK',
|
|
170
329
|
text: `Ваш одноразовый код: ${code}\n\nДействует 10 минут.`,
|
|
171
330
|
html: `
|
|
@@ -213,15 +372,16 @@ export const authMethods = {
|
|
|
213
372
|
pendingRegistrations.delete(reg.id);
|
|
214
373
|
if (session.registration === reg)
|
|
215
374
|
delete session.registration;
|
|
216
|
-
const { uid, email } = reg;
|
|
217
|
-
let label = ((surname || '') + ' ' + (name || '') + ' ' + (patronymic || '')).trim() || email;
|
|
375
|
+
const { uid, email = '', phone = '' } = reg;
|
|
376
|
+
let label = ((surname || '') + ' ' + (name || '') + ' ' + (patronymic || '')).trim() || email || phone;
|
|
218
377
|
const credentials = {
|
|
219
378
|
uid,
|
|
220
379
|
service: "WORK (Extensible Fractal File System)",
|
|
221
380
|
origin: HOST,
|
|
222
381
|
KEY: Buffer.from(uid),
|
|
223
382
|
email,
|
|
224
|
-
|
|
383
|
+
...(phone ? { phone, phoneVerified: true } : {}),
|
|
384
|
+
name: label || email || phone,
|
|
225
385
|
challenge: crypto.randomUUID(),
|
|
226
386
|
verified: true,
|
|
227
387
|
};
|
|
@@ -242,7 +402,7 @@ export const authMethods = {
|
|
|
242
402
|
|| (session.credentials?.verified ? session.credentials : null);
|
|
243
403
|
if (!verified || !UID_RE.test(verified.uid))
|
|
244
404
|
throw new Error("registration failed: адрес не подтверждён");
|
|
245
|
-
const { uid, email } = verified;
|
|
405
|
+
const { uid, email = '', phone = '' } = verified;
|
|
246
406
|
if (postUid != null && String(postUid).toUpperCase() !== uid)
|
|
247
407
|
throw new Error("registration failed: uid не совпадает с подтверждённым адресом");
|
|
248
408
|
if (!publicKey || !signature || time == null)
|
|
@@ -287,11 +447,6 @@ export const authMethods = {
|
|
|
287
447
|
name = cleanStr(name);
|
|
288
448
|
patronymic = cleanStr(patronymic);
|
|
289
449
|
|
|
290
|
-
const credentials = {
|
|
291
|
-
uid, icon: '', surname, name, patronymic, email,
|
|
292
|
-
label: ((surname || '') + ' ' + (name || '') + ' ' + (patronymic || '')).trim() || email,
|
|
293
|
-
};
|
|
294
|
-
|
|
295
450
|
const $users = await this.$users;
|
|
296
451
|
const users = await $users.items;
|
|
297
452
|
await WORK.init;
|
|
@@ -299,17 +454,38 @@ export const authMethods = {
|
|
|
299
454
|
const currentBosses = Array.isArray(WORK?.DATA?.['#security']?.BOSS) ? WORK.DATA['#security'].BOSS : [];
|
|
300
455
|
const isFirstUser = users.length === 0 || !currentBosses.some(id => existingUserIds.has(id));
|
|
301
456
|
let $user_item = await $users._get_next_item(uid, CORE.$user);
|
|
457
|
+
await $user_item.init?.catch?.(() => {});
|
|
458
|
+
if (typeof $user_item._ownUserEnabledSync === 'function' && !$user_item._ownUserEnabledSync())
|
|
459
|
+
throw new Error('Учётная запись отключена администратором');
|
|
460
|
+
const prevData = $user_item.DATA || {};
|
|
461
|
+
const finalEmail = email || prevData.email || '';
|
|
462
|
+
const finalPhone = phone || prevData.phone || '';
|
|
463
|
+
const finalSurname = surname || prevData.surname || '';
|
|
464
|
+
const finalName = name || prevData.name || '';
|
|
465
|
+
const finalPatronymic = patronymic || prevData.patronymic || '';
|
|
466
|
+
const credentials = {
|
|
467
|
+
uid,
|
|
468
|
+
icon: prevData.icon || '',
|
|
469
|
+
surname: finalSurname,
|
|
470
|
+
name: finalName,
|
|
471
|
+
patronymic: finalPatronymic,
|
|
472
|
+
email: finalEmail,
|
|
473
|
+
...(finalPhone ? { phone: finalPhone, phoneVerified: Boolean(phone || prevData.phoneVerified !== false) } : {}),
|
|
474
|
+
label: ((finalSurname || '') + ' ' + (finalName || '') + ' ' + (finalPatronymic || '')).trim() || finalEmail || finalPhone,
|
|
475
|
+
};
|
|
302
476
|
credentials.keys = $user_item.keys || {};
|
|
303
477
|
credentials.keys[time] = publicKey;
|
|
304
|
-
if (
|
|
305
|
-
credentials.settings =
|
|
478
|
+
if (prevData.settings && typeof prevData.settings === 'object')
|
|
479
|
+
credentials.settings = prevData.settings;
|
|
480
|
+
if (prevData.enabled !== undefined)
|
|
481
|
+
credentials.enabled = prevData.enabled;
|
|
306
482
|
|
|
307
483
|
if (iconBytes)
|
|
308
484
|
credentials.icon = '/USERS//' + uid + '/$user/icon.png';
|
|
309
485
|
|
|
310
486
|
let post = CORE.$class.toScript(credentials);
|
|
311
487
|
|
|
312
|
-
let res = await $user_item.save({ filename: 'class.js', post, session:
|
|
488
|
+
let res = await $user_item.save({ filename: 'class.js', post, session: sysSession(), ignore_save_logs: true });
|
|
313
489
|
let u = await this.$users;
|
|
314
490
|
(await u.children)?.forEach?.(ch => ch.children = undefined);
|
|
315
491
|
u.children = undefined;
|
|
@@ -452,6 +628,201 @@ export const authMethods = {
|
|
|
452
628
|
return "Вход выполнен";
|
|
453
629
|
},
|
|
454
630
|
|
|
631
|
+
async user_bind_phone_start(params = {}) {
|
|
632
|
+
const uid = mcpUser(params);
|
|
633
|
+
const post = (params.post && typeof params.post === 'object') ? params.post : params;
|
|
634
|
+
const normPhone = normalizePhone(post.phone || params.phone || '');
|
|
635
|
+
if (!normPhone)
|
|
636
|
+
throw new Error('Некорректный номер телефона (укажите номер в формате +79991234567)');
|
|
637
|
+
const other = await findUserByPhone(this, normPhone);
|
|
638
|
+
if (other && String(other.id).toUpperCase() !== String(uid).toUpperCase())
|
|
639
|
+
throw new Error('Этот номер телефона уже привязан к другому профилю');
|
|
640
|
+
await assertNotDisabledUser(this, uid);
|
|
641
|
+
const now = Date.now();
|
|
642
|
+
for (const [k, v] of pendingPhoneBinds) {
|
|
643
|
+
if (!v?.at || now - v.at > REGISTER_CODE_TTL_MS)
|
|
644
|
+
pendingPhoneBinds.delete(k);
|
|
645
|
+
}
|
|
646
|
+
const prev = pendingPhoneBinds.get(uid);
|
|
647
|
+
if (prev?.at && now - prev.at < REGISTER_START_INTERVAL_MS)
|
|
648
|
+
throw new Error('Код уже отправлен, повторите через 30 секунд');
|
|
649
|
+
const code = crypto.randomInt(0, 1_000_000).toString().padStart(6, '0');
|
|
650
|
+
const entry = { uid, phone: normPhone, code, at: now, attempts: 0 };
|
|
651
|
+
pendingPhoneBinds.set(uid, entry);
|
|
652
|
+
if (DEV_MODE) {
|
|
653
|
+
console.log('[DEV] Phone bind code for', normPhone, ':', code);
|
|
654
|
+
return { ok: true, phone: normPhone, message: 'Код подтверждения отправлен на указанный номер.' };
|
|
655
|
+
}
|
|
656
|
+
const msgSent = await sendPhoneCodeViaMessenger({ uid, code });
|
|
657
|
+
if (msgSent?.ok)
|
|
658
|
+
return { ok: true, phone: normPhone, message: 'Код подтверждения отправлен в ваш привязанный мессенджер.' };
|
|
659
|
+
if (hasLocalSmsGateway()) {
|
|
660
|
+
const res = await sendViaSmsProvider({
|
|
661
|
+
phone: normPhone,
|
|
662
|
+
code,
|
|
663
|
+
ip: params.request?.socket?.remoteAddress || '',
|
|
664
|
+
});
|
|
665
|
+
if (res?.overrideCode)
|
|
666
|
+
entry.code = String(res.overrideCode);
|
|
667
|
+
return {
|
|
668
|
+
ok: true,
|
|
669
|
+
phone: normPhone,
|
|
670
|
+
mode: res?.mode || 'sms',
|
|
671
|
+
message: res?.mode === 'flashcall'
|
|
672
|
+
? 'Вам поступает звонок-сброс — введите последние цифры входящего номера.'
|
|
673
|
+
: 'На ваш телефон отправлено SMS с одноразовым кодом.',
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
const relayed = await sendLoginCodeViaLicenseHub({ phone: normPhone, code, channel: 'sms' });
|
|
677
|
+
if (relayed?.ok) {
|
|
678
|
+
if (relayed.code)
|
|
679
|
+
entry.code = String(relayed.code);
|
|
680
|
+
return { ok: true, phone: normPhone, message: relayed.message || 'На ваш телефон отправлено SMS с одноразовым кодом.' };
|
|
681
|
+
}
|
|
682
|
+
throw new Error('SMS-шлюз не настроен');
|
|
683
|
+
},
|
|
684
|
+
|
|
685
|
+
async user_bind_phone_finish(params = {}) {
|
|
686
|
+
const uid = mcpUser(params);
|
|
687
|
+
const post = (params.post && typeof params.post === 'object') ? params.post : params;
|
|
688
|
+
const code = String(post.code ?? params.code ?? '').trim();
|
|
689
|
+
const entry = pendingPhoneBinds.get(uid);
|
|
690
|
+
if (!entry || Date.now() - entry.at > REGISTER_CODE_TTL_MS) {
|
|
691
|
+
pendingPhoneBinds.delete(uid);
|
|
692
|
+
throw new Error('Срок действия проверочного кода истёк');
|
|
693
|
+
}
|
|
694
|
+
if (++entry.attempts > REGISTER_MAX_ATTEMPTS) {
|
|
695
|
+
pendingPhoneBinds.delete(uid);
|
|
696
|
+
throw new Error('Превышено число попыток ввода кода, запросите новый');
|
|
697
|
+
}
|
|
698
|
+
if (!sameCode(entry.code, code))
|
|
699
|
+
throw new Error('Введен неверный проверочный код');
|
|
700
|
+
pendingPhoneBinds.delete(uid);
|
|
701
|
+
const other = await findUserByPhone(this, entry.phone);
|
|
702
|
+
if (other && String(other.id).toUpperCase() !== String(uid).toUpperCase())
|
|
703
|
+
throw new Error('Этот номер телефона уже привязан к другому профилю');
|
|
704
|
+
const usersRoot = await this.$users;
|
|
705
|
+
const userNode = await usersRoot.get_item('//' + uid);
|
|
706
|
+
if (!userNode)
|
|
707
|
+
throw new Error('Профиль пользователя не найден');
|
|
708
|
+
await userNode.init?.catch?.(() => {});
|
|
709
|
+
const d = userNode.DATA || {};
|
|
710
|
+
const nextCreds = {
|
|
711
|
+
uid: userNode.id,
|
|
712
|
+
icon: d.icon || '',
|
|
713
|
+
surname: d.surname || '',
|
|
714
|
+
name: d.name || '',
|
|
715
|
+
patronymic: d.patronymic || '',
|
|
716
|
+
email: d.email || '',
|
|
717
|
+
phone: entry.phone,
|
|
718
|
+
phoneVerified: true,
|
|
719
|
+
label: d.label || ((d.surname || '') + ' ' + (d.name || '') + ' ' + (d.patronymic || '')).trim() || d.email || entry.phone,
|
|
720
|
+
keys: userNode.keys || d.keys || {},
|
|
721
|
+
...(d.settings ? { settings: d.settings } : {}),
|
|
722
|
+
...(d.enabled !== undefined ? { enabled: d.enabled } : {}),
|
|
723
|
+
};
|
|
724
|
+
const postScript = CORE.$class.toScript(nextCreds);
|
|
725
|
+
await userNode.save({ filename: 'class.js', post: postScript, session: sysSession(), ignore_save_logs: true });
|
|
726
|
+
userNode.reset?.();
|
|
727
|
+
await usersRoot.reset?.();
|
|
728
|
+
return { ok: true, phone: entry.phone };
|
|
729
|
+
},
|
|
730
|
+
|
|
731
|
+
async user_login_appeal_challenge(params = {}) {
|
|
732
|
+
const uid = String(params.uid || params.post?.uid || '').trim().toUpperCase();
|
|
733
|
+
const challengeId = String(params.challengeId || params.post?.challengeId || '').trim();
|
|
734
|
+
if (!UID_RE.test(uid))
|
|
735
|
+
throw new Error('uid required');
|
|
736
|
+
if (!challengeId || challengeId.length > 64)
|
|
737
|
+
throw new Error('challengeId required');
|
|
738
|
+
const usersRoot = await WORK.$users;
|
|
739
|
+
const accountNode = await usersRoot.get_item('//' + uid).catch(() => null);
|
|
740
|
+
if (!accountNode)
|
|
741
|
+
throw new Error('User not registered');
|
|
742
|
+
accountNode.reset?.();
|
|
743
|
+
await accountNode.init?.catch?.(() => {});
|
|
744
|
+
if (typeof accountNode._ownUserEnabledSync !== 'function' || accountNode._ownUserEnabledSync())
|
|
745
|
+
throw new Error('Учётная запись не отключена');
|
|
746
|
+
const now = Date.now();
|
|
747
|
+
for (const [id, c] of pendingAppeals)
|
|
748
|
+
if (now > c.expiresAt)
|
|
749
|
+
pendingAppeals.delete(id);
|
|
750
|
+
const challenge = crypto.randomUUID();
|
|
751
|
+
pendingAppeals.set(challengeId, { value: challenge, uid, expiresAt: now + CHALLENGE_TTL_MS });
|
|
752
|
+
return challenge;
|
|
753
|
+
},
|
|
754
|
+
|
|
755
|
+
async user_appeal_disabled(params = {}) {
|
|
756
|
+
const post = (params.post && typeof params.post === 'object') ? params.post : params;
|
|
757
|
+
const uid = String(post.uid || params.uid || '').trim().toUpperCase();
|
|
758
|
+
const challengeId = String(post.challengeId || params.challengeId || '').trim();
|
|
759
|
+
const time = post.time ?? params.time;
|
|
760
|
+
const signature = post.signature;
|
|
761
|
+
const rawMsg = String(post.message || '').replace(/[\r\0]+/g, ' ').trim().slice(0, 1000);
|
|
762
|
+
if (!UID_RE.test(uid))
|
|
763
|
+
throw new Error('uid required');
|
|
764
|
+
if (!rawMsg)
|
|
765
|
+
throw new Error('Введите текст обращения');
|
|
766
|
+
if (!signature || !challengeId)
|
|
767
|
+
throw new Error('Требуется криптографическая подпись ключа');
|
|
768
|
+
const entry = pendingAppeals.get(challengeId);
|
|
769
|
+
pendingAppeals.delete(challengeId);
|
|
770
|
+
if (!entry || Date.now() > entry.expiresAt || entry.uid !== uid)
|
|
771
|
+
throw new Error('Срок проверки подписи истёк, повторите отправку');
|
|
772
|
+
const usersRoot = await WORK.$users;
|
|
773
|
+
const accountNode = await usersRoot.get_item('//' + uid).catch(() => null);
|
|
774
|
+
if (!accountNode)
|
|
775
|
+
throw new Error('User not registered');
|
|
776
|
+
await accountNode.init?.catch?.(() => {});
|
|
777
|
+
if (typeof accountNode._ownUserEnabledSync !== 'function' || accountNode._ownUserEnabledSync())
|
|
778
|
+
throw new Error('Учётная запись не отключена');
|
|
779
|
+
const publicKey = accountNode.DATA?.keys?.[time];
|
|
780
|
+
if (!publicKey)
|
|
781
|
+
throw new Error('Ключ устройства не найден в профиле');
|
|
782
|
+
const PK = await crypto.subtle.importKey('spki', Buffer.from(publicKey, 'base64'), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, true, ['verify']);
|
|
783
|
+
const isValid = await crypto.subtle.verify(
|
|
784
|
+
{ name: 'RSASSA-PKCS1-v1_5' },
|
|
785
|
+
PK,
|
|
786
|
+
Buffer.from(signature, 'base64'),
|
|
787
|
+
new TextEncoder().encode(entry.value)
|
|
788
|
+
);
|
|
789
|
+
if (!isValid)
|
|
790
|
+
throw new Error('Подпись ключа недействительна');
|
|
791
|
+
|
|
792
|
+
const now = Date.now();
|
|
793
|
+
const prevAppeal = appealsByUid.get(uid) || 0;
|
|
794
|
+
if (now - prevAppeal < 3600_000)
|
|
795
|
+
throw new Error('Обращение уже отправлено. Повторная отправка возможна через час.');
|
|
796
|
+
|
|
797
|
+
await WORK.init;
|
|
798
|
+
const bosses = (Array.isArray(WORK?.DATA?.['#security']?.BOSS) ? WORK.DATA['#security'].BOSS : []).filter(b => b && b !== uid);
|
|
799
|
+
if (!bosses.length)
|
|
800
|
+
throw new Error('Администратор системы не назначен');
|
|
801
|
+
|
|
802
|
+
const { sendMessage } = await import('../server/chat-threads.js');
|
|
803
|
+
const who = accountNode.DATA?.label || accountNode.DATA?.email || accountNode.DATA?.phone || uid;
|
|
804
|
+
const text = `[Обращение отключённого пользователя — ${who}]:\n${rawMsg}`;
|
|
805
|
+
let sentCount = 0;
|
|
806
|
+
for (const bossUid of bosses) {
|
|
807
|
+
const bossNode = await usersRoot.get_item('//' + bossUid).catch(() => null);
|
|
808
|
+
if (!bossNode)
|
|
809
|
+
continue;
|
|
810
|
+
await sendMessage(bossNode, {
|
|
811
|
+
session: sysSession(),
|
|
812
|
+
uid,
|
|
813
|
+
kind: 'dm',
|
|
814
|
+
peerId: bossUid,
|
|
815
|
+
message: text,
|
|
816
|
+
meta: { appealDisabled: true },
|
|
817
|
+
});
|
|
818
|
+
sentCount++;
|
|
819
|
+
}
|
|
820
|
+
if (!sentCount)
|
|
821
|
+
throw new Error('Не удалось доставить сообщение администратору');
|
|
822
|
+
appealsByUid.set(uid, now);
|
|
823
|
+
return { ok: true, message: 'Обращение отправлено администратору.' };
|
|
824
|
+
},
|
|
825
|
+
|
|
455
826
|
/**
|
|
456
827
|
* Токены доступа внешних ИИ-клиентов по MCP (modules/mcp). Только вошедший пользователь — не сессия самого MCP.
|
|
457
828
|
* mcp_token_create({ role?, label? }) → { token, id, role, label }: токен показывается один раз.
|
|
@@ -521,7 +892,7 @@ async function ensureBootstrapBoss(uid, params = {}) {
|
|
|
521
892
|
data['#security'] ??= {};
|
|
522
893
|
data['#security'].BOSS ??= [];
|
|
523
894
|
data['#security'].BOSS.add(uid);
|
|
524
|
-
await WORK.save({ post: WORK.constructor.toScript(data), session:
|
|
895
|
+
await WORK.save({ post: WORK.constructor.toScript(data), session: sysSession(), sockets: params.sockets });
|
|
525
896
|
WORK.reset();
|
|
526
897
|
return true;
|
|
527
898
|
}
|