-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcursorRegistration.js
More file actions
345 lines (289 loc) · 11.5 KB
/
cursorRegistration.js
File metadata and controls
345 lines (289 loc) · 11.5 KB
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// ========================
// Cursor Registration Automation
// ========================
console.log('[SAF Cursor] Script loaded on:', window.location.href);
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function randomDelay(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Получить все корневые элементы включая shadow DOM
function collectRoots() {
const roots = [document];
const stack = [document.documentElement];
while (stack.length) {
const node = stack.pop();
if (!node) continue;
if (node.shadowRoot) {
roots.push(node.shadowRoot);
}
const children = node.children || [];
for (let i = 0; i < children.length; i++) {
stack.push(children[i]);
}
}
return roots;
}
function isVisible(el) {
if (!el) return false;
const rect = el.getBoundingClientRect();
const style = window.getComputedStyle(el);
if (style.visibility === 'hidden' || style.display === 'none') return false;
if (el.disabled) return false;
if (rect.width <= 0 || rect.height <= 0) return false;
if (el.type === 'hidden') return false;
return true;
}
async function setNativeValue(el, value, useTyping = false) {
if (!el) return;
try {
el.focus();
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
await sleep(randomDelay(150, 300));
const tag = el.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA') {
const proto = tag === 'INPUT'
? window.HTMLInputElement.prototype
: window.HTMLTextAreaElement.prototype;
const valueSetter = Object.getOwnPropertyDescriptor(proto, 'value').set;
if (useTyping && value && value.length < 30) {
el.value = '';
for (let i = 0; i < value.length; i++) {
valueSetter.call(el, el.value + value[i]);
el.dispatchEvent(new Event('input', { bubbles: true }));
await sleep(randomDelay(50, 120));
}
} else {
valueSetter.call(el, value);
el.dispatchEvent(new Event('input', { bubbles: true }));
}
el.dispatchEvent(new Event('change', { bubbles: true }));
await sleep(randomDelay(150, 250));
el.blur();
await sleep(randomDelay(200, 300));
}
} catch (error) {
console.error('[SAF Cursor] Error setting value:', error);
el.value = value;
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
}
}
function showNotification(message, type = 'info') {
const existing = document.getElementById('cursor-registration-notification');
if (existing) existing.remove();
const notification = document.createElement('div');
notification.id = 'cursor-registration-notification';
notification.textContent = message;
const colors = {
info: '#3498db',
success: '#2ecc71',
warning: '#f39c12',
error: '#e74c3c'
};
Object.assign(notification.style, {
position: 'fixed',
top: '20px',
right: '20px',
background: colors[type] || colors.info,
color: 'white',
padding: '15px 20px',
borderRadius: '8px',
boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
zIndex: '9999999',
fontSize: '14px',
fontWeight: '600',
maxWidth: '300px',
animation: 'slideIn 0.3s ease-out'
});
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn {
from { transform: translateX(400px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
`;
if (!document.getElementById('cursor-notification-style')) {
style.id = 'cursor-notification-style';
document.head.appendChild(style);
}
document.body.appendChild(notification);
setTimeout(() => {
notification.style.transition = 'all 0.3s ease-out';
notification.style.transform = 'translateX(400px)';
notification.style.opacity = '0';
setTimeout(() => notification.remove(), 300);
}, 5000);
}
async function getRandomPersonData() {
// Генерируем случайные данные
const firstNames = ['John', 'Michael', 'David', 'James', 'Robert', 'William', 'Richard', 'Thomas', 'Charles', 'Daniel'];
const lastNames = ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis', 'Rodriguez', 'Martinez'];
const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
return { firstName, lastName };
}
async function fillRegistrationForm() {
try {
console.log('[SAF Cursor] Filling registration form...');
showNotification('📝 Filling registration form...', 'info');
await sleep(1500);
// Получаем случайные данные
const person = await getRandomPersonData();
const randomEmail = `${person.firstName.toLowerCase()}.${person.lastName.toLowerCase()}${Math.floor(Math.random() * 9999)}@gmail.com`;
console.log('[SAF Cursor] Generated data:', { firstName: person.firstName, lastName: person.lastName, email: randomEmail });
// Ищем поля формы
const firstNameField = document.querySelector('input[name="first_name"], input[autocomplete="given-name"]');
const lastNameField = document.querySelector('input[name="last_name"], input[autocomplete="family-name"]');
const emailField = document.querySelector('input[name="email"], input[type="email"], input[autocomplete="email"]');
console.log('[SAF Cursor] Found fields:', {
firstName: !!firstNameField,
lastName: !!lastNameField,
email: !!emailField
});
if (firstNameField && isVisible(firstNameField)) {
console.log('[SAF Cursor] Filling first name...');
await setNativeValue(firstNameField, person.firstName, true);
showNotification(`👤 Name: ${person.firstName}`, 'info');
}
if (lastNameField && isVisible(lastNameField)) {
console.log('[SAF Cursor] Filling last name...');
await setNativeValue(lastNameField, person.lastName, true);
showNotification(`👥 Last name: ${person.lastName}`, 'info');
}
if (emailField && isVisible(emailField)) {
console.log('[SAF Cursor] Filling email...');
await setNativeValue(emailField, randomEmail, false);
showNotification(`📧 Email: ${randomEmail}`, 'info');
}
// Сохраняем credentials
chrome.storage.local.set({
lastCursorCredentials: {
email: randomEmail,
firstName: person.firstName,
lastName: person.lastName,
timestamp: Date.now()
}
});
await sleep(1000);
showNotification('✅ Form filled successfully!', 'success');
console.log('[SAF Cursor] Registration form completed!');
} catch (error) {
console.error('[SAF Cursor] Error filling form:', error);
showNotification('❌ Error: ' + error.message, 'error');
}
}
function findSignUpButton() {
const SIGNUP_TEXTS = [
'регистрация',
'sign up',
'register',
'create account',
'sign-up'
];
try {
const roots = collectRoots();
const selectors = ['a', 'button', '[role="button"]', '[role="link"]', '.Link', '.Button'];
for (const root of roots) {
for (const sel of selectors) {
const nodes = root.querySelectorAll(sel);
for (let i = 0; i < nodes.length; i++) {
const el = nodes[i];
if (!isVisible(el)) continue;
const combined = [
el.textContent || '',
el.getAttribute('aria-label') || '',
el.getAttribute('title') || '',
el.getAttribute('href') || '',
el.getAttribute('data-testid') || ''
].join(' ').toLowerCase();
if (!combined) continue;
// Проверяем на совпадение с текстами регистрации
if (SIGNUP_TEXTS.some(t => combined.includes(t))) {
const clickable = el.closest('a, button, [role="button"], [role="link"]') || el;
console.log('[SAF Cursor] Found sign-up element:', {
tag: el.tagName,
text: el.textContent.trim().slice(0, 50),
href: el.href || 'no href'
});
return clickable;
}
}
}
}
} catch (error) {
console.error('[SAF Cursor] Error in findSignUpButton:', error);
}
return null;
}
async function startRegistration() {
try {
console.log('[SAF Cursor] Starting registration process...');
showNotification('🤖 Starting registration...', 'info');
await sleep(2000);
const currentUrl = window.location.href;
console.log('[SAF Cursor] Current URL:', currentUrl);
// Ищем кнопку/ссылку регистрации
console.log('[SAF Cursor] Looking for sign-up link...');
showNotification('🔍 Looking for Sign Up...', 'info');
const signUpButton = findSignUpButton();
if (signUpButton) {
console.log('[SAF Cursor] Found Sign Up button!');
showNotification('✅ Found Sign Up!', 'success');
await sleep(500);
signUpButton.scrollIntoView({ behavior: 'smooth', block: 'center' });
await sleep(300);
// Убираем target="_blank" если есть
if (signUpButton.hasAttribute('target')) {
signUpButton.removeAttribute('target');
}
console.log('[SAF Cursor] Clicking Sign Up button...');
signUpButton.click();
console.log('[SAF Cursor] Clicked!');
// Ждем загрузки формы
await sleep(3000);
// Заполняем форму
await fillRegistrationForm();
} else {
console.log('[SAF Cursor] Sign Up button not found. Checking if already on registration form...');
showNotification('🔍 Checking for registration form...', 'info');
await sleep(1000);
// Возможно уже на странице регистрации
const emailField = document.querySelector('input[name="email"], input[type="email"]');
if (emailField && isVisible(emailField)) {
console.log('[SAF Cursor] Already on registration form!');
await fillRegistrationForm();
} else {
console.log('[SAF Cursor] No registration form found');
showNotification('⚠️ Registration form not found', 'warning');
// Debug - показываем все найденные элементы
const roots = collectRoots();
for (const root of roots) {
const allLinks = root.querySelectorAll('a');
console.log('[SAF Cursor] Links in root:', Array.from(allLinks).slice(0, 10).map(a => ({
text: a.textContent.trim().slice(0, 30),
href: a.href
})));
}
}
}
} catch (error) {
console.error('[SAF Cursor] Error in registration:', error);
showNotification('❌ Error: ' + error.message, 'error');
}
}
// Слушатель сообщений
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('[SAF Cursor] Received message:', request.action);
if (request.action === 'startCursorRegistration') {
console.log('[SAF Cursor] Starting registration on:', window.location.href);
startRegistration();
sendResponse({ success: true });
}
return true;
});
// Автозапуск через 3 секунды если есть параметр
if (window.location.href.includes('authenticator.cursor.sh')) {
console.log('[SAF Cursor] On authenticator page, waiting for auto-start...');
}