Spaces:
Configuration error

File size: 7,165 Bytes
5871ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
'use strict';
/**
 * AuthMe Handler — التعامل مع AuthMeReloaded
 * يكتشف لو السيرفر محتاج تسجيل، ويسجل دخول تلقائي
 */
const { EventEmitter } = require('events');
const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms)));
const rand = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a;

// ═══ رسائل AuthMe ═══
const AUTHME_MESSAGES = {
  // تسجيل جديد
  register: [
    'Please register with',
    'سجل كلمة المرور',
    'To register type',
    'اكتب كلمة المرور',
    'register <password> <password>',
    'التسجيل:',
  ],
  // تسجيل دخول
  login: [
    'Please login with',
    'سجل الدخول',
    'To login type',
    'اكتب كلمة المرور للدخول',
    'login <password>',
    'الدخول:',
  ],
  // نجاح
  success: [
    'Successfully registered',
    'تم التسجيل بنجاح',
    'Successfully logged in',
    'تم تسجيل الدخول',
    'Du wurdest erfolgreich',
    'Registration complete',
  ],
  // خطأ
  error: [
    'Wrong password',
    'كلمة المرور خاطئة',
    'Invalid password',
    'كلمة المرور غير صحيحة',
    'already logged in',
    'محصل دخول بالفعل',
    'You are already authenticated',
  ],
  // تحقق
  needVerify: [
    'verify',
    'تحقق',
    'confirm',
    'أكد',
  ],
};

class AuthMeHandler extends EventEmitter {
  constructor(bot, config = {}) {
    super();
    this.bot = bot;
    this.config = {
      password: config.password || '123456',
      loginCommand: config.loginCommand || '/login',
      registerCommand: config.registerCommand || '/register',
      authDelay: config.authDelay || rand(1500, 3500),
      maxRetries: config.maxRetries || 3,
      autoLogin: config.autoLogin !== false,
      autoRegister: config.autoRegister !== false,
    };
    this._state = 'unknown'; // unknown, needRegister, needLogin, logged, error
    this._retries = 0;
    this._authenticated = false;
    this._authTimer = null;
    this._chatHandler = null;
    this._log('INIT', `AuthMe Handler جاهز — كلمة السر: ${this.config.password}`);
  }

  _log(tag, msg) {
    const ts = new Date().toISOString().replace('T', ' ').slice(0, 19);
    console.log(`[${ts}] [AUTHME] ${tag}  ${msg}`);
  }

  // ═══ بدء الاستماع ═══
  start() {
    if (!this.bot) return;

    // استمع لرسائل الشات
    this._chatHandler = (msg) => this._onMessage(msg);
    this.bot.on('messagestr', this._chatHandler);

    // بعد الاتصال، استنى شوية وابدأ التحقق
    this._authTimer = setTimeout(() => {
      this._checkAuthState();
    }, this.config.authDelay);

    this._log('START', 'بدء مراقبة AuthMe');
  }

  // ═══ إيقاف ═══
  stop() {
    if (this._authTimer) { clearTimeout(this._authTimer); this._authTimer = null; }
    if (this.bot && this._chatHandler) {
      this.bot.removeListener('messagestr', this._chatHandler);
    }
    this._authenticated = false;
    this._state = 'unknown';
    this._log('STOP', 'إيقاف AuthMe Handler');
  }

  // ═══ استقبال رسالة ═══
  _onMessage(msg) {
    if (!msg || this._authenticated) return;
    const text = msg.toString().replace(/<[^>]+>/g, '').trim().toLowerCase();

    // فحص لو رسالة AuthMe
    if (this._isAuthMessage(text, AUTHME_MESSAGES.register)) {
      this._log('📝', 'محتاج تسجيل جديد');
      this._state = 'needRegister';
      this._handleRegister();
    } else if (this._isAuthMessage(text, AUTHME_MESSAGES.login)) {
      this._log('🔐', 'محتاج تسجيل دخول');
      this._state = 'needLogin';
      this._handleLogin();
    } else if (this._isAuthMessage(text, AUTHME_MESSAGES.success)) {
      this._log('✅', 'تم التسجيل/الدخول بنجاح!');
      this._state = 'logged';
      this._authenticated = true;
      this._retries = 0;
      this.emit('authenticated');
    } else if (this._isAuthMessage(text, AUTHME_MESSAGES.error)) {
      this._log('❌', `خطأ في كلمة المرور (${this._retries + 1}/${this.config.maxRetries})`);
      this._retries++;
      if (this._retries < this.config.maxRetries) {
        setTimeout(() => {
          if (this._state === 'needLogin') this._handleLogin();
          else if (this._state === 'needRegister') this._handleRegister();
        }, rand(2000, 4000));
      } else {
        this._log('💀', 'فشل التسجيل عدة مرات!');
        this._state = 'error';
        this.emit('authFailed');
      }
    }
  }

  // ═══ فحص رسالة AuthMe ═══
  _isAuthMessage(text, patterns) {
    return patterns.some(p => text.includes(p.toLowerCase()));
  }

  // ═══ فحص حالة التحقق ═══
  _checkAuthState() {
    if (this._authenticated || !this.bot) return;

    // جرّب تسجيل الدخول مباشرة
    if (this.config.autoLogin) {
      this._log('🔄', 'محاولة تسجيل دخول تلقائي...');
      this._handleLogin();
    }
  }

  // ═══ تسجيل دخول ═══
  async _handleLogin() {
    if (!this.bot || this._authenticated) return;

    const cmd = `${this.config.loginCommand} ${this.config.password}`;
    this._log('🔐', `يكتب: ${cmd}`);

    await sleep(rand(500, 1500));
    try {
      this.bot.chat(cmd);
      this.emit('loginAttempt', this.config.password);
    } catch(e) {
      this._log('❌', `خطأ في الإرسال: ${e.message}`);
    }
  }

  // ═══ تسجيل جديد ═══
  async _handleRegister() {
    if (!this.bot || this._authenticated || !this.config.autoRegister) return;

    const cmd = `${this.config.registerCommand} ${this.config.password} ${this.config.password}`;
    this._log('📝', `يكتب: ${cmd}`);

    await sleep(rand(500, 1500));
    try {
      this.bot.chat(cmd);
      this.emit('registerAttempt', this.config.password);
    } catch(e) {
      this._log('❌', `خطأ في الإرسال: ${e.message}`);
    }
  }

  // ═══ تغيير كلمة المرور ═══
  async changePassword(oldPass, newPass) {
    if (!this.bot) return;
    try {
      this.bot.chat(`/changepassword ${oldPass} ${newPass}`);
      this.config.password = newPass;
      this._log('🔑', 'تم تغيير كلمة المرور');
      this.emit('passwordChanged', newPass);
    } catch(_) {}
  }

  // ═══ فحص لو مسجل دخول ═══
  isAuthenticated() {
    return this._authenticated;
  }

  // ═══ حالة AuthMe ═══
  getState() {
    return {
      state: this._state,
      authenticated: this._authenticated,
      retries: this._retries,
      password: this.config.password,
    };
  }

  // ═══ إعادة المحاولة ═══
  retry() {
    this._retries = 0;
    this._authenticated = false;
    this._state = 'unknown';
    this._checkAuthState();
  }

  destroy() {
    this.stop();
    this.removeAllListeners();
  }
}

module.exports = { AuthMeHandler, AUTHME_MESSAGES };