-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
401 lines (369 loc) · 14.4 KB
/
Copy pathbackground.js
File metadata and controls
401 lines (369 loc) · 14.4 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
* CryptoDripster — © testguard.app (https://testguard.app)
* Developed and owned by testguard.app. Do not remove this notice (see LICENSE).
*/
// ===== Default settings =====
const DEFAULTS = {
wallet: "", // no default recipient — the user must enter their own wallet
amount: "5",
intervalHours: 8,
keepTabOpen: false,
requestsPerRun: 2,
};
const ALARM_NAME = "faucetAlarm";
const MAX_LOGS = 100; // how many log entries to keep
const NOTIF_ICON = "icons/icon128.png";
// Pause between the two consecutive claims in a single run.
const REQUEST_PAUSE_MS = 45000; // 45s
// Extra time added to the scheduled interval. The 45s pause (plus page
// load/processing overhead) pushes the second claim a bit past the alarm's
// fire time, so without a buffer the gap between one run's last claim and the
// next run's first claim could drop below intervalHours. This buffer keeps the
// effective gap at/above the configured interval (so it never falls under 8h).
const SCHEDULE_BUFFER_MINUTES = 2;
// ===== Logs =====
async function addLog(message, level = "info") {
const entry = { time: new Date().toISOString(), level, message };
const { logs = [] } = await chrome.storage.local.get("logs");
logs.push(entry);
await chrome.storage.local.set({ logs: logs.slice(-MAX_LOGS) });
console.log(`[faucet] ${level}: ${message}`);
}
// ===== Config =====
async function getConfig() {
const data = await chrome.storage.local.get([
"wallet",
"amount",
"intervalHours",
"keepTabOpen",
"requestsPerRun",
]);
return {
wallet: data.wallet || DEFAULTS.wallet,
amount: data.amount || DEFAULTS.amount,
intervalHours: Number(data.intervalHours) || DEFAULTS.intervalHours,
keepTabOpen: data.keepTabOpen === true,
requestsPerRun: Number(data.requestsPerRun) || DEFAULTS.requestsPerRun,
};
}
function shortWallet(w) {
return w && w.length > 12 ? `${w.slice(0, 4)}...${w.slice(-4)}` : w;
}
// Classify the faucet's response text as success / error / unknown
function classifyMessage(msg) {
if (!msg) return null;
if (/limit|empty|\brate\b|too many|fail|error|denied|insufficient|exceeded|try again|unable|invalid/i.test(msg))
return "error";
if (/airdrop|success|confirm|sent|\bSOL\b/i.test(msg)) return "success";
return null;
}
// ===== Last-run status =====
async function setStatus(result, detail) {
const now = new Date().toLocaleString("en-GB");
await chrome.storage.local.set({ lastRun: now, lastResult: result, lastDetail: detail || "" });
notify(result, detail, now);
}
function notify(result, detail, now) {
const map = {
success: ["✅", "Solana Faucet"],
error: ["⚠️", "Solana Faucet"],
captcha: ["⏳", "Captcha required"],
};
const [icon, title] = map[result] || ["•", "Solana Faucet"];
chrome.notifications.create({
type: "basic",
iconUrl: NOTIF_ICON,
title: `${icon} ${title}`,
message: `${detail || ""} • ${now}`,
});
}
// ===== Scheduler (alarm) =====
async function createAlarm(delayMinutes) {
const { intervalHours } = await getConfig();
await chrome.alarms.clear(ALARM_NAME);
await chrome.alarms.create(ALARM_NAME, {
delayInMinutes: delayMinutes,
periodInMinutes: intervalHours * 60 + SCHEDULE_BUFFER_MINUTES,
});
}
chrome.runtime.onInstalled.addListener(async () => {
await addLog("Extension installed/updated — new code is active", "info");
// No automatic run on install: scheduling starts only after you save a
// wallet address in the popup (which sends a "reschedule" message).
});
chrome.runtime.onStartup.addListener(async () => {
// Resume the schedule on browser startup only if a wallet is configured.
const { wallet, intervalHours } = await getConfig();
if (!wallet) return;
const existing = await chrome.alarms.get(ALARM_NAME);
if (!existing) await createAlarm(intervalHours * 60 + SCHEDULE_BUFFER_MINUTES);
});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === ALARM_NAME) runFaucet("scheduled", false);
});
// Interpret a single fillAndSubmit result: log it and return { status, detail }.
async function interpretResult(result, label) {
const tag = label ? ` [${label}]` : "";
if (!result) {
await addLog(`Page script returned no result${tag}`, "error");
return { status: "error", detail: "No response from the page" };
}
if (result.captcha) {
await addLog(
`⏳ Cloudflare check did not pass automatically within 20s${tag}. If there is a captcha in the tab, solve it manually and click "Confirm Airdrop".`,
"info"
);
return { status: "captcha", detail: "Cloudflare check stuck — check the tab" };
}
if (result.error) {
await addLog(`Page error${tag}: ${result.error}`, "error");
return { status: "error", detail: result.error };
}
if (result.confirmClicked) {
const msg = (result.message || "").trim();
const verdict = classifyMessage(msg);
if (msg) await addLog(`Faucet response${tag}: ${msg}`, verdict === "error" ? "error" : "success");
else await addLog(`Confirm clicked${tag}, but the faucet showed no response`, "info");
return verdict === "error"
? { status: "error", detail: msg }
: { status: "success", detail: msg || "Request sent" };
}
await addLog(
`Partial result${tag} — wallet: ${result.walletFilled}, ` +
`amount: ${result.amountSelected}, confirm: ${result.confirmClicked}`,
"error"
);
return { status: "error", detail: "Could not click Confirm" };
}
// ===== Main logic =====
async function runFaucet(trigger = "manual", active = false) {
const { wallet, amount, keepTabOpen, requestsPerRun } = await getConfig();
// Basic Solana address validation (base58, 32–44 chars)
if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(wallet || "")) {
await addLog(`Invalid wallet address: "${wallet}"`, "error");
await setStatus("error", "Invalid wallet");
return;
}
const n = Math.max(1, Math.min(5, requestsPerRun || 1));
await addLog(`Run (${trigger}): ${amount} SOL × ${n} → ${shortWallet(wallet)}`, "info");
let tab;
let captchaNeeded = false;
let successCount = 0;
let lastDetail = "";
try {
tab = await chrome.tabs.create({ url: "https://faucet.solana.com/", active });
await waitForTabLoad(tab.id);
await sleep(3000); // give the page's JS time to render
// Send the airdrop request n times in a row (the faucet allows up to 2 per window).
for (let i = 1; i <= n; i++) {
if (i > 1) {
await addLog(`Waiting ${REQUEST_PAUSE_MS / 1000}s before request ${i}/${n}…`, "info");
await sleep(REQUEST_PAUSE_MS); // 45s pause between the consecutive claims
}
const injection = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: fillAndSubmit,
args: [wallet, amount],
});
const result = injection && injection[0] ? injection[0].result : null;
const r = await interpretResult(result, n > 1 ? `${i}/${n}` : "");
lastDetail = r.detail;
if (r.status === "captcha") {
captchaNeeded = true;
break;
}
if (r.status === "success") successCount++;
if (r.status === "error") break; // e.g. rate limit — no point continuing
}
if (captchaNeeded) {
await setStatus("captcha", lastDetail || "Cloudflare check stuck — check the tab");
} else if (successCount === 0) {
await setStatus("error", lastDetail || "No request went through");
} else if (successCount >= n) {
await setStatus("success", n > 1 ? `Sent ${n}/${n} requests` : lastDetail || "Request sent");
} else {
await setStatus("success", `Sent ${successCount}/${n} (last: ${lastDetail})`);
}
} catch (e) {
await addLog(`Exception: ${e && e.message ? e.message : e}`, "error");
await setStatus("error", String(e && e.message ? e.message : e));
} finally {
if (tab) {
// Keep the tab open if a captcha is needed (manual run) or if the user
// turned on "keep the tab open".
const keepOpen = keepTabOpen || (captchaNeeded && active);
if (keepOpen) {
if (active) {
try {
await chrome.tabs.update(tab.id, { active: true });
} catch (_) {
/* tab already closed */
}
}
await addLog("Faucet tab left open — finish manually", "info");
} else {
await sleep(active ? 6000 : 3000); // time to see the message before closing
try {
await chrome.tabs.remove(tab.id);
} catch (_) {
/* tab already closed */
}
}
}
}
}
// Runs IN THE CONTEXT of the faucet.solana.com page.
// Fills the wallet and amount, clicks Confirm, then waits for the real
// outcome (the Cloudflare check usually passes automatically).
async function fillAndSubmit(walletAddress, amount) {
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const byText = (txt) =>
Array.from(document.querySelectorAll("button")).find((b) => b.textContent.trim() === txt);
const result = {
walletFilled: false,
amountSelected: false,
confirmClicked: false,
captcha: false,
message: "",
error: null,
};
try {
const walletInput =
document.querySelector('input[placeholder="Wallet Address"]') ||
document.querySelector('input[type="text"]');
if (!walletInput) {
result.error = "Wallet address field not found";
return result;
}
const setter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value"
).set;
setter.call(walletInput, walletAddress);
walletInput.dispatchEvent(new Event("input", { bubbles: true }));
walletInput.dispatchEvent(new Event("change", { bubbles: true }));
result.walletFilled = true;
await wait(800);
const amountBtn = byText("Amount");
if (amountBtn) {
amountBtn.click();
await wait(800);
const opt = byText(String(amount));
if (opt) {
opt.click();
result.amountSelected = true;
}
await wait(800);
}
const confirmBtn = Array.from(document.querySelectorAll("button")).find((b) =>
b.textContent.includes("Confirm Airdrop")
);
if (!confirmBtn) {
result.error = '"Confirm Airdrop" button not found';
return result;
}
const toastSel =
'[role="status"],[role="alert"],[class*="toast" i],[class*="notification" i]';
const captchaRe = /captcha|cloudflare verification|complete the (captcha|verification)/i;
const successRe = /airdropp?ed|success|sent|confirmed|transaction|signature/i;
const errorRe = /error|fail|limit|empty|\brate\b|too many|denied|insufficient|exceeded|unable|invalid|too new|not eligible|try again/i;
const readToasts = () =>
Array.from(document.querySelectorAll(toastSel))
.map((n) => (n.innerText || "").trim())
.filter(Boolean);
// Toasts already on screen (e.g. left over from a previous request) — ignore them.
const preToasts = new Set(readToasts());
confirmBtn.click();
result.confirmClicked = true;
// After Confirm the faucet may show a temporary Cloudflare check
// ("Please complete the captcha…") that USUALLY passes automatically
// within a few seconds. So don't give up immediately — wait for the
// real outcome.
const deadline = Date.now() + 20000; // headroom for the Cloudflare auto-check
let sawCaptcha = false;
let captchaGoneAt = 0;
let lastToast = ""; // remember the newest non-captcha toast in case it auto-dismisses
while (Date.now() < deadline) {
await wait(800);
const toasts = readToasts().filter((t) => !preToasts.has(t)); // only new toasts
if (toasts[0] && !captchaRe.test(toasts[0])) lastToast = toasts[0];
const body = document.body.innerText || "";
// Explicit success in a new toast — done
const ok = toasts.find((t) => successRe.test(t));
if (ok) {
result.message = ok.slice(0, 300);
return result;
}
// Explicit (non-captcha) error in a new toast — done
const err = toasts.find((t) => errorRe.test(t) && !captchaRe.test(t));
if (err) {
result.message = err.slice(0, 300);
return result;
}
// Captcha/Cloudflare on screen — wait for it to auto-pass, don't give up
if (captchaRe.test(body) || readToasts().some((t) => captchaRe.test(t))) {
sawCaptcha = true;
captchaGoneAt = 0;
continue;
}
// Captcha gone without an explicit toast — allow a little time, treat as success
if (sawCaptcha) {
if (!captchaGoneAt) captchaGoneAt = Date.now();
else if (Date.now() - captchaGoneAt > 5000) {
result.message = "Cloudflare check passed automatically, request sent";
return result;
}
}
}
// Timed out: if Cloudflare/captcha is STILL on screen — manual action needed
if (captchaRe.test(document.body.innerText || "")) {
result.captcha = true;
result.message = "Cloudflare check did not pass automatically — manual action needed";
} else {
const toasts = readToasts().filter((t) => !preToasts.has(t));
result.message = toasts[0]
? toasts[0].slice(0, 300)
: lastToast
? lastToast.slice(0, 300)
: sawCaptcha
? "Cloudflare check passed automatically, request sent"
: "";
}
} catch (e) {
result.error = String(e && e.message ? e.message : e);
}
return result;
}
// ===== Helpers =====
function waitForTabLoad(tabId) {
return new Promise((resolve) => {
const timeout = setTimeout(() => {
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}, 20000); // don't wait forever
function listener(id, info) {
if (id === tabId && info.status === "complete") {
clearTimeout(timeout);
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
}
chrome.tabs.onUpdated.addListener(listener);
});
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// ===== Messages from the popup =====
chrome.runtime.onMessage.addListener((msg) => {
if (msg.action === "runNow") {
runFaucet("manual", true); // manual run — show the tab so the faucet is visible
} else if (msg.action === "reschedule") {
(async () => {
const { intervalHours } = await getConfig();
// next run after the full interval (+ buffer so the gap never dips below it)
await createAlarm(intervalHours * 60 + SCHEDULE_BUFFER_MINUTES);
await addLog(`Interval changed: every ${intervalHours}h (+${SCHEDULE_BUFFER_MINUTES}m buffer)`, "info");
})();
}
});