axm0121 commited on
Commit
cd4da2c
·
verified ·
1 Parent(s): e999c2e

Deploy standalone direct-bind Space runtime

Browse files

Deploy the PORT-aware Docker runtime, static asset allowlist, and standalone HTTP service.

Files changed (3) hide show
  1. direct-bind.css +102 -0
  2. direct-bind.js +1218 -0
  3. index.html +3 -3
direct-bind.css ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root { color-scheme: dark; --bg:#07111f; --panel:#101e31; --panel2:#0b192b; --line:#29415c; --text:#e7f0fb; --muted:#8da6c0; --accent:#62dfbd; --blue:#70b7ff; --danger:#ff7186; }
2
+ * { box-sizing:border-box; }
3
+ body { margin:0; min-height:100vh; background:radial-gradient(circle at 85% 0,#12384e 0,transparent 32rem),linear-gradient(135deg,#06101d,#0b1728 58%,#081321); color:var(--text); font:15px/1.55 "Microsoft YaHei","PingFang SC",system-ui,sans-serif; }
4
+ .shell { width:min(1180px,calc(100% - 32px)); margin:0 auto; padding:58px 0 70px; }
5
+ .hero { margin:0 0 22px; }
6
+ .eyebrow { color:var(--accent); font-size:12px; font-weight:800; letter-spacing:.16em; }
7
+ h1 { margin:8px 0 6px; font-size:clamp(30px,5vw,50px); line-height:1.08; }
8
+ .hero p { max-width:900px; margin:0; color:var(--muted); }
9
+ .card { border:1px solid var(--line); border-radius:22px; background:rgba(16,30,49,.94); box-shadow:0 22px 70px #0005; }
10
+ .batch-card { padding:22px; }
11
+ .steps { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin-bottom:18px; }
12
+ .steps span { padding:11px 12px; text-align:center; border:1px solid var(--line); border-radius:13px; color:var(--muted); background:#0b192b; font-weight:800; }
13
+ .steps span.active { border-color:var(--accent); color:var(--accent); background:#10283a; }
14
+ .steps span.done { border-color:#2e7769; color:var(--accent); }
15
+ .setup-grid { display:grid; grid-template-columns:1fr 1.08fr; gap:14px; }
16
+ .batch-section { padding:18px; border:1px solid #223a55; border-radius:16px; background:rgba(12,27,45,.72); }
17
+ .section-title { display:flex; justify-content:space-between; align-items:flex-start; gap:12px; margin-bottom:15px; }
18
+ .section-title b { font-size:17px; }
19
+ .section-title small { display:block; margin-top:4px; color:var(--muted); }
20
+ .tag { display:inline-flex; align-items:center; border:1px solid #2c796d; border-radius:999px; padding:4px 10px; color:var(--accent); font-size:11px; white-space:nowrap; }
21
+ .card-fields-grid { display:grid; grid-template-columns:2fr 1fr 1fr; gap:10px; }
22
+ .card-field span { display:block; margin-bottom:6px; color:var(--muted); }
23
+ .card-field-box { min-height:48px; padding:14px; border:1px solid #2e806f; border-radius:11px; background:#091728; }
24
+ .billing-head { display:flex; justify-content:space-between; align-items:baseline; gap:10px; margin:16px 0 8px; padding-top:13px; border-top:1px solid #223a55; }
25
+ .billing-head small { color:var(--muted); font-size:11px; text-align:right; }
26
+ .billing-auto-status { padding:10px 12px; border:1px dashed #35516d; border-radius:10px; color:var(--muted); background:#091728; font-size:12px; }
27
+ .billing-auto-status.is-test { border-color:#2c796d; color:var(--accent); }
28
+ .billing-auto-status.is-live { border-color:#9b7440; color:#f4ca72; }
29
+ .billing-auto-status.error { border-color:#8f3f52; color:var(--danger); }
30
+ .billing-grid[hidden] { display:none; }
31
+ .billing-grid { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:9px; }
32
+ .billing-field { display:block; min-width:0; }
33
+ .billing-field span { display:block; margin-bottom:5px; color:var(--muted); font-size:12px; }
34
+ .billing-field input { width:100%; min-width:0; }
35
+ .billing-field.billing-wide { grid-column:span 2; }
36
+ .inline-state { min-height:25px; margin:11px 0 8px; color:var(--muted); }
37
+ .inline-state.ok { color:var(--accent); }
38
+ .inline-state.error { color:var(--danger); }
39
+ .inline-state.warn { color:#f4ca72; }
40
+ .at-title-actions { display:flex; align-items:center; gap:7px; flex-wrap:wrap; justify-content:flex-end; }
41
+ .at-list { display:grid; gap:8px; max-height:240px; overflow:auto; }
42
+ .at-row { display:grid; grid-template-columns:54px 1fr auto; gap:9px; align-items:center; padding:9px 10px; border:1px solid #2b806f; border-radius:10px; background:#0a192a; }
43
+ .at-row__label { color:var(--accent); font:12px ui-monospace,Consolas,monospace; }
44
+ .at-entry { width:100%; min-width:0; border:1px solid #263f5b; border-radius:8px; padding:9px 10px; background:#071321; color:var(--text); font:12px ui-monospace,Consolas,monospace; }
45
+ .at-entry:focus, .proxy-pool-input:focus, input:focus { outline:none; border-color:var(--blue); box-shadow:0 0 0 3px #70b7ff22; }
46
+ .at-row__remove { border:0; border-radius:8px; padding:7px 9px; color:#ff9aaa; background:#3a1e2c; cursor:pointer; }
47
+ .proxy-pool-section { margin-top:14px; }
48
+ .dual-proxy-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
49
+ .proxy-pool-card { padding:13px; border:1px solid #263f5b; border-radius:13px; background:#091728; }
50
+ .proxy-pool-head { display:flex; justify-content:space-between; align-items:center; gap:8px; }
51
+ .proxy-pool-card small, .proxy-pool-note { color:var(--muted); }
52
+ .proxy-pool-card small { display:block; margin:5px 0 9px; }
53
+ .proxy-pool-input { width:100%; min-height:120px; resize:vertical; border:1px solid #223b58; border-radius:11px; padding:12px; background:#071321; color:var(--text); font:12px/1.5 ui-monospace,Consolas,monospace; }
54
+ .proxy-pool-note { margin-top:9px; font-size:12px; }
55
+ .action-row { display:flex; align-items:center; gap:10px; margin-top:16px; padding:12px; border:1px solid #253d59; border-radius:15px; background:#0c1b2d; }
56
+ .concurrency-control { display:flex; align-items:center; gap:8px; margin-right:auto; color:var(--muted); }
57
+ input { border:1px solid #2a4665; border-radius:9px; padding:9px 10px; background:#081626; color:var(--text); }
58
+ .concurrency-control input { width:66px; }
59
+ button { border:0; border-radius:10px; padding:11px 16px; color:#04101b; background:linear-gradient(100deg,#5bdcbb,#65b1ff); cursor:pointer; font-weight:900; white-space:nowrap; }
60
+ button.secondary { color:var(--text); background:#233a57; }
61
+ button.small { padding:7px 10px; font-size:12px; }
62
+ button:disabled { opacity:.42; cursor:not-allowed; }
63
+ .progress-wrap { margin:15px 0 16px; }
64
+ .progress-meta { display:flex; justify-content:space-between; color:var(--muted); font-size:13px; margin-bottom:6px; }
65
+ .progress-track { height:8px; overflow:hidden; border-radius:99px; background:#0a1422; }
66
+ .progress-track i { display:block; width:0; height:100%; border-radius:inherit; background:linear-gradient(90deg,#61dfbd,#70b7ff); transition:width .25s ease; }
67
+ .result-section { min-height:190px; }
68
+ .mini-actions { display:flex; gap:7px; flex-wrap:wrap; justify-content:flex-end; }
69
+ .task-rows { display:grid; gap:8px; }
70
+ .task-row { display:grid; grid-template-columns:1fr auto; gap:10px; align-items:center; padding:12px 13px; border:1px solid #29435f; border-radius:11px; background:#091728; }
71
+ .task-row.is-error { border-color:#814055; }
72
+ .task-row__account { font-weight:800; }
73
+ .task-row__stage { margin-top:4px; color:var(--muted); font-size:13px; }
74
+ .task-row__link { margin-top:5px; color:var(--accent); word-break:break-all; font:12px ui-monospace,Consolas,monospace; }
75
+ .batch-summary { margin-top:14px; padding:14px 16px; border:1px solid #814055; border-radius:12px; background:#091728; color:#ff7186; font-weight:800; }
76
+ .batch-summary.is-success { border-color:#2b806f; color:#61dfbd; }
77
+ .batch-summary.is-stopped { border-color:#806b2b; color:#ffc966; }
78
+ @media(max-width:820px){ .setup-grid,.dual-proxy-grid { grid-template-columns:1fr; } .action-row { flex-wrap:wrap; } .concurrency-control { width:100%; margin-right:0; } }
79
+ @media(max-width:560px){ .shell { width:min(100% - 16px,1180px); padding-top:25px; } .batch-card { padding:12px; } .steps { grid-template-columns:repeat(2,1fr); } .card-fields-grid,.billing-grid { grid-template-columns:1fr; } .billing-field.billing-wide { grid-column:span 1; } .at-row { grid-template-columns:45px 1fr auto; } }
80
+
81
+ /* account import/list workflow */
82
+ .account-import-input { width:100%; min-height:158px; resize:vertical; border:1px solid #2b806f; border-radius:12px; padding:13px; background:#071321; color:var(--text); font:12px/1.55 ui-monospace,Consolas,monospace; }
83
+ .account-import-input:focus { outline:none; border-color:var(--blue); box-shadow:0 0 0 3px #70b7ff22; }
84
+ .import-actions { display:flex; gap:9px; margin-top:11px; flex-wrap:wrap; }
85
+ .account-list-actions { align-items:center; }
86
+ .export-csv-button { border:1px solid #d7dcd5; border-radius:12px; background:#f7f8f4; color:#52605a; box-shadow:none; }
87
+ .export-csv-button:hover { background:#fff; }
88
+ .select-all-control { display:inline-flex; align-items:center; gap:7px; color:var(--muted); font-weight:700; }
89
+ .select-all-control input,.account-select { width:17px; height:17px; accent-color:var(--accent); }
90
+ .account-empty { padding:32px 14px; text-align:center; color:var(--muted); border:1px dashed #29435f; border-radius:12px; }
91
+ .account-row { grid-template-columns:auto minmax(0,1fr) auto; align-items:center; }
92
+ .account-row__summary { display:grid; grid-template-columns:minmax(360px,32%) minmax(300px,1fr) auto; gap:14px; align-items:center; min-width:0; }
93
+ .task-row__account { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
94
+ .account-row__current-step { min-width:0; margin:0; overflow:hidden; color:#91abc5; text-overflow:ellipsis; white-space:nowrap; }
95
+ .account-row__current-step.is-error { color:var(--danger); }
96
+ button.task-row__link { display:inline; margin:0; padding:0; border:0; border-radius:0; background:none; color:var(--accent); font:12px ui-monospace,Consolas,monospace; white-space:nowrap; }
97
+ button.task-row__link:hover { text-decoration:underline; }
98
+ .account-row-actions { display:flex; align-items:center; gap:9px; }
99
+ .account-row-actions .at-row__remove { padding:8px 11px; }
100
+ @media(max-width:680px){ .account-row { grid-template-columns:auto 1fr; } .account-row__summary { grid-template-columns:1fr; gap:3px; } .account-row-actions { grid-column:2; justify-content:flex-start; } }
101
+ .task-row__proxy { margin-top:5px; color:#7fa4c5; font:11px ui-monospace,Consolas,monospace; word-break:break-all; }
102
+ .task-row__billing { margin-top:6px; color:#f4ca72; font:11px ui-monospace,Consolas,monospace; word-break:break-word; }
direct-bind.js ADDED
@@ -0,0 +1,1218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function () {
2
+ 'use strict';
3
+
4
+ const $ = (id) => document.getElementById(id);
5
+ const PROXY_DRAFT_KEY = 'direct-bind:proxy-draft:v5';
6
+ const ACCOUNT_LIST_KEY = 'direct-bind:account-list:v2';
7
+ const CARD_DECLINE_MESSAGE = '绑卡未完成:发卡行拒绝了卡片,账号没有新增支付方式。';
8
+ const TASK_POLL_MS = 400;
9
+ const MAX_BATCH_CONCURRENCY = 50;
10
+ const MAX_PROXY_FALLBACKS = 4;
11
+ const ACCOUNT_SAVE_DEBOUNCE_MS = 120;
12
+ let stripeJsPromise = null;
13
+ let accountSaveTimer = 0;
14
+ let accountRenderFrame = 0;
15
+ const billingFetchPromises = new Map();
16
+ const state = {
17
+ stripe: null,
18
+ publishableKey: '',
19
+ elements: {},
20
+ complete: { number: false, expiry: false, cvc: false },
21
+ mounted: false,
22
+ running: false,
23
+ stop: false,
24
+ accounts: [],
25
+ nextId: 1,
26
+ bindProxyCursor: 0,
27
+ promoProxyCursor: 0,
28
+ };
29
+
30
+ // Open-source cleanup migration: discard drafts created by earlier private
31
+ // builds, which may contain access tokens, proxy credentials and task state.
32
+ try {
33
+ for (let index = localStorage.length - 1; index >= 0; index -= 1) {
34
+ const key = localStorage.key(index) || '';
35
+ if (key.startsWith('direct-bind:') && ![PROXY_DRAFT_KEY, ACCOUNT_LIST_KEY].includes(key)) {
36
+ localStorage.removeItem(key);
37
+ }
38
+ }
39
+ } catch (_) {}
40
+
41
+ function splitValues(value) {
42
+ return [...new Set(String(value || '').split(/[\r\n,;]+/).map((item) => item.trim()).filter(Boolean))];
43
+ }
44
+
45
+ function parseProxyPool(value) {
46
+ const source = String(value || '').trim();
47
+ if (!source) return [];
48
+ let values = [];
49
+ if (source.startsWith('[')) {
50
+ try {
51
+ const parsed = JSON.parse(source);
52
+ if (Array.isArray(parsed)) values = parsed;
53
+ } catch (_) {}
54
+ }
55
+ if (!values.length) values = source.split(/[\s,;,;]+/);
56
+ return [...new Set(values
57
+ .map((item) => String(item || '').trim().replace(/^["']|["']$/g, ''))
58
+ .filter(Boolean))].slice(0, 500);
59
+ }
60
+
61
+ function extractTokens(text) {
62
+ const source = String(text || '');
63
+ const namedAccessTokens = [...source.matchAll(
64
+ /["']access_token["']\s*:\s*["'](eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*)["']/gi,
65
+ )].map((match) => match[1]);
66
+ if (namedAccessTokens.length) return [...new Set(namedAccessTokens.filter((token) => decodeAccount(token).accountId))];
67
+ const jwtMatches = source.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g);
68
+ const candidates = jwtMatches?.length
69
+ ? [...new Set(jwtMatches)]
70
+ : splitValues(source).map((item) => item.replace(/^["']|["']$/g, '')).filter(Boolean);
71
+ return candidates.filter((token) => Boolean(decodeAccount(token).accountId));
72
+ }
73
+
74
+ function decodeAccount(token) {
75
+ try {
76
+ const part = String(token).split('.')[1];
77
+ if (!part) return {};
78
+ const raw = part.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(part.length / 4) * 4, '=');
79
+ const claims = JSON.parse(decodeURIComponent(Array.from(atob(raw), (ch) => `%${ch.charCodeAt(0).toString(16).padStart(2, '0')}`).join('')));
80
+ const profile = claims['https://api.openai.com/profile'] || {};
81
+ const auth = claims['https://api.openai.com/auth'] || {};
82
+ return {
83
+ email: String(profile.email || claims.email || ''),
84
+ accountId: String(auth.chatgpt_account_id || auth.account_id || claims.chatgpt_account_id || claims.account_id || ''),
85
+ };
86
+ } catch (_) {
87
+ return {};
88
+ }
89
+ }
90
+
91
+ function maskToken(value) {
92
+ const text = String(value || '');
93
+ return text.length > 24 ? `${text.slice(0, 12)}…${text.slice(-8)}` : text;
94
+ }
95
+
96
+ async function copyText(value) {
97
+ const text = String(value || '').trim();
98
+ if (!text) return false;
99
+ try {
100
+ await navigator.clipboard.writeText(text);
101
+ return true;
102
+ } catch (_) {
103
+ const field = document.createElement('textarea');
104
+ field.value = text;
105
+ field.setAttribute('readonly', '');
106
+ field.style.position = 'fixed';
107
+ field.style.opacity = '0';
108
+ document.body.appendChild(field);
109
+ field.select();
110
+ const copied = document.execCommand('copy');
111
+ field.remove();
112
+ return copied;
113
+ }
114
+ }
115
+
116
+ function csvCell(value) {
117
+ return `"${String(value ?? '').replace(/"/g, '""')}"`;
118
+ }
119
+
120
+ function exportAccountsCsv() {
121
+ if (!state.accounts.length) return false;
122
+ const rows = [
123
+ ['账号', '账号ID', '状态', '当前步骤', 'Checkout链接', '错误'],
124
+ ...state.accounts.map((account) => [
125
+ account.email || '',
126
+ account.accountId || '',
127
+ accountStatusLabel(account),
128
+ account.stage || '',
129
+ account.link || '',
130
+ account.error || '',
131
+ ]),
132
+ ];
133
+ const csv = `\uFEFF${rows.map((row) => row.map(csvCell).join(',')).join('\r\n')}`;
134
+ const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }));
135
+ const download = document.createElement('a');
136
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
137
+ download.href = url;
138
+ download.download = `账号任务-${stamp}.csv`;
139
+ document.body.appendChild(download);
140
+ download.click();
141
+ download.remove();
142
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);
143
+ return true;
144
+ }
145
+
146
+ function translateError(value) {
147
+ const text = String(value || '').replace(/\s+/g, ' ').trim();
148
+ const lower = text.toLowerCase();
149
+ if (!text) return '任务执行失败。';
150
+ if (lower.includes('curl: (35)') || lower.includes('tls connect error') || lower.includes('openssl_internal:invalid library')) {
151
+ return '代理 TLS 握手失败,请检查代理协议、地址、端口和有效期。';
152
+ }
153
+ if (lower.includes('impersonating') && lower.includes('is not supported')) {
154
+ return '当前浏览器 TLS 指纹版本不受运行库支持,系统已自动切换兼容版本,请重试。';
155
+ }
156
+ if (lower.includes('card_declined') || lower.includes('your card was declined')) {
157
+ return CARD_DECLINE_MESSAGE;
158
+ }
159
+ if (lower.includes('secret_key_required')) {
160
+ return '支付接口权限不匹配,当前步骤没有获得所需的服务端权限。';
161
+ }
162
+ if (lower.includes('invalidated') || lower.includes('token expired') || lower.includes('at invalid') || lower.includes('http 401')) {
163
+ return '账号凭证已失效,请删除后重新导入。';
164
+ }
165
+ if (lower.includes('at does not contain an account id') || lower.includes('at 缺少账号 id')) {
166
+ return '该条不是可用的 AT(缺少账号 ID),请导入 access_token。';
167
+ }
168
+ if (lower.includes('missing or invalid paymentmethod') || lower.includes('paymentmethod 创建失败')) {
169
+ return '卡片支付方式创建失败,请重新填写卡片。';
170
+ }
171
+ if (lower.includes('proxy') && (lower.includes('connect') || lower.includes('failed') || lower.includes('error'))) {
172
+ return '代理连接失败,请检查代理格式、节点状态和网络。';
173
+ }
174
+ if (lower.includes('timeout') || lower.includes('timed out') || lower.includes('任务超时')) {
175
+ return '请求超时,请检查代理速度后重试。';
176
+ }
177
+ if (lower.includes('http 403')) return '请求被拒绝(HTTP 403),请检查账号状态和接口权限。';
178
+ if (lower.includes('http 402')) return '支付请求被拒绝(HTTP 402),请检查卡片状态。';
179
+ if (lower.includes('failed to perform, curl')) return '网络请求失败,请检查代理和本机网络。';
180
+ if (/[\u4e00-\u9fff]/.test(text)) return text;
181
+ return `任务失败:${text.slice(0, 220)}`;
182
+ }
183
+
184
+ function normalizedBilling(value = {}, email = '') {
185
+ return {
186
+ name: String(value.name || '').trim(),
187
+ line1: String(value.line1 || '').trim(),
188
+ line2: String(value.line2 || '').trim(),
189
+ city: String(value.city || '').trim(),
190
+ state: String(value.state || '').trim().toUpperCase(),
191
+ postal_code: String(value.postal_code || '').trim().toUpperCase(),
192
+ country: String(value.country || 'US').trim().toUpperCase(),
193
+ email: String(email || value.email || '').trim(),
194
+ };
195
+ }
196
+
197
+ function billingIssues(billing) {
198
+ const issues = [];
199
+ if (!billing.name) issues.push('持卡人姓名');
200
+ if (!billing.line1) issues.push('账单地址');
201
+ if (!billing.city) issues.push('城市');
202
+ if (!/^[A-Z]{2}$/.test(billing.country)) issues.push('两位国家代码');
203
+ if (!billing.postal_code) issues.push('邮编');
204
+ if (billing.country === 'US') {
205
+ if (!billing.state) issues.push('州代码');
206
+ if (!/^\d{5}(?:-\d{4})?$/.test(billing.postal_code)) issues.push('美国 ZIP 格式');
207
+ }
208
+ return issues;
209
+ }
210
+
211
+ function ensureStripeJs() {
212
+ if (typeof window.Stripe === 'function') return Promise.resolve(window.Stripe);
213
+ if (stripeJsPromise) return stripeJsPromise;
214
+ stripeJsPromise = new Promise((resolve, reject) => {
215
+ document.querySelectorAll('script[data-direct-stripe-loader]').forEach((node) => node.remove());
216
+ const script = document.createElement('script');
217
+ script.src = 'https://js.stripe.com/v3/';
218
+ script.async = true;
219
+ script.dataset.directStripeLoader = '1';
220
+ const timer = window.setTimeout(() => {
221
+ script.remove();
222
+ reject(new Error('Stripe 安全组件加载超时,请检查浏览器网络或拦截扩展后重试'));
223
+ }, 20000);
224
+ script.addEventListener('load', () => {
225
+ window.clearTimeout(timer);
226
+ if (typeof window.Stripe === 'function') resolve(window.Stripe);
227
+ else reject(new Error('Stripe 安全组件脚本已返回,但组件没有初始化'));
228
+ }, { once: true });
229
+ script.addEventListener('error', () => {
230
+ window.clearTimeout(timer);
231
+ reject(new Error('Stripe 安全组件加载失败,请检查浏览器网络或拦截扩展后重试'));
232
+ }, { once: true });
233
+ document.head.appendChild(script);
234
+ }).catch((error) => {
235
+ stripeJsPromise = null;
236
+ throw error;
237
+ });
238
+ return stripeJsPromise;
239
+ }
240
+
241
+ function isStoredCardDecline(value) {
242
+ const text = String(value || '').toLowerCase();
243
+ return text.includes('card_declined')
244
+ || text.includes('your card was declined')
245
+ || text.includes('银行卡被拒绝')
246
+ || text.includes('发卡行拒绝');
247
+ }
248
+
249
+ async function fetchBillingForAccount(account) {
250
+ const key = account.id || account.token;
251
+ if (billingFetchPromises.has(key)) return billingFetchPromises.get(key);
252
+ const request = (async () => {
253
+ const response = await fetch('/api/address', {
254
+ method: 'POST',
255
+ headers: { 'Content-Type': 'application/json' },
256
+ body: '{}',
257
+ });
258
+ const payload = await response.json().catch(() => ({}));
259
+ if (!response.ok || payload.ok === false || !payload.billing) {
260
+ throw new Error(payload.error || `地址获取失败:HTTP ${response.status}`);
261
+ }
262
+ account.billing = normalizedBilling(payload.billing, account.email);
263
+ account.billingMode = 'auto';
264
+ return true;
265
+ })().finally(() => billingFetchPromises.delete(key));
266
+ billingFetchPromises.set(key, request);
267
+ return request;
268
+ }
269
+
270
+ async function assignBillingAddresses(accounts) {
271
+ if (!accounts.length) return;
272
+ $('billingAutoStatus').className = 'billing-auto-status is-test';
273
+ $('billingAutoStatus').textContent = `正在为 ${accounts.length} 个账号分别获取 DE 账单地址…`;
274
+ let cursor = 0;
275
+ async function worker() {
276
+ while (cursor < accounts.length) {
277
+ const account = accounts[cursor++];
278
+ await fetchBillingForAccount(account);
279
+ }
280
+ }
281
+ await Promise.all(Array.from({ length: Math.min(8, accounts.length) }, worker));
282
+ renderAccounts();
283
+ refresh();
284
+ $('billingAutoStatus').textContent = `已为 ${accounts.length} 个账号分别分配接口账单地址。`;
285
+ appendLog(`${accounts.length} 个账号的独立 DE 接口地址已就绪。`);
286
+ }
287
+
288
+ function setStep(id, status) {
289
+ const node = $(id);
290
+ if (node) node.className = status || '';
291
+ }
292
+
293
+ function log(message) {
294
+ void message;
295
+ }
296
+
297
+ function appendLog(message) {
298
+ void message;
299
+ }
300
+
301
+ function hideBatchSummary() {
302
+ const node = $('batchSummary');
303
+ node.hidden = true;
304
+ node.className = 'batch-summary';
305
+ node.textContent = '';
306
+ }
307
+
308
+ function showBatchSummary(label, success, failed, stopped = false) {
309
+ const node = $('batchSummary');
310
+ node.hidden = false;
311
+ node.className = `batch-summary ${stopped ? 'is-stopped' : failed ? '' : 'is-success'}`;
312
+ node.textContent = stopped
313
+ ? `${label}已停止:${success} 个成功,${failed} 个失败或未执行。`
314
+ : `${label}完成:${success} 个成功,${failed} 个失败。`;
315
+ }
316
+
317
+ function saveProxyDraft() {
318
+ try {
319
+ localStorage.setItem(PROXY_DRAFT_KEY, JSON.stringify({
320
+ bind: $('bindProxyPool').value,
321
+ promo: $('promoProxyPool').value,
322
+ concurrency: $('batchConcurrency').value,
323
+ }));
324
+ } catch (_) {}
325
+ }
326
+
327
+ function loadProxyDraft() {
328
+ try {
329
+ const draft = JSON.parse(localStorage.getItem(PROXY_DRAFT_KEY) || '{}');
330
+ if (typeof draft.bind === 'string') $('bindProxyPool').value = draft.bind;
331
+ if (typeof draft.promo === 'string') $('promoProxyPool').value = draft.promo;
332
+ if (draft.concurrency != null) $('batchConcurrency').value = draft.concurrency;
333
+ } catch (_) {}
334
+ }
335
+
336
+ function saveAccountsNow() {
337
+ if (accountSaveTimer) {
338
+ window.clearTimeout(accountSaveTimer);
339
+ accountSaveTimer = 0;
340
+ }
341
+ try {
342
+ localStorage.setItem(ACCOUNT_LIST_KEY, JSON.stringify({
343
+ nextId: state.nextId,
344
+ items: state.accounts.map((account) => ({
345
+ id: account.id,
346
+ token: account.token,
347
+ email: account.email || '',
348
+ accountId: account.accountId || '',
349
+ selected: Boolean(account.selected),
350
+ status: account.status || 'idle',
351
+ stage: account.stage || '待执行',
352
+ error: account.error || '',
353
+ link: account.link || '',
354
+ taskId: account.taskId || '',
355
+ bindProxyLabel: account.bindProxyLabel || '',
356
+ promoProxyLabel: account.promoProxyLabel || '',
357
+ fingerprint: account.fingerprint || '',
358
+ fingerprintId: account.fingerprintId || '',
359
+ fingerprintTls: account.fingerprintTls || '',
360
+ fingerprintRegion: account.fingerprintRegion || '',
361
+ fingerprintTimezone: account.fingerprintTimezone || '',
362
+ steps: Array.isArray(account.steps) ? account.steps : [],
363
+ billingMode: account.billingMode || '',
364
+ billing: account.billing ? normalizedBilling(account.billing, account.email) : null,
365
+ })),
366
+ }));
367
+ } catch (_) {}
368
+ }
369
+
370
+ function saveAccounts() {
371
+ if (accountSaveTimer) window.clearTimeout(accountSaveTimer);
372
+ accountSaveTimer = window.setTimeout(saveAccountsNow, ACCOUNT_SAVE_DEBOUNCE_MS);
373
+ }
374
+
375
+ function scheduleRenderAccounts() {
376
+ if (accountRenderFrame) return;
377
+ accountRenderFrame = window.requestAnimationFrame(() => {
378
+ accountRenderFrame = 0;
379
+ renderAccounts();
380
+ });
381
+ }
382
+
383
+ function loadAccounts() {
384
+ try {
385
+ const saved = JSON.parse(localStorage.getItem(ACCOUNT_LIST_KEY) || '{}');
386
+ const items = Array.isArray(saved.items) ? saved.items : [];
387
+ state.accounts = items
388
+ .filter((item) => item && typeof item.token === 'string' && item.token.trim())
389
+ .map((item) => ({ item, decoded: decodeAccount(item.token.trim()) }))
390
+ .filter(({ decoded }) => Boolean(decoded.accountId))
391
+ .map(({ item, decoded }, index) => ({
392
+ id: String(item.id || `account-${index + 1}`),
393
+ token: item.token.trim(),
394
+ email: String(decoded.email || item.email || ''),
395
+ accountId: String(decoded.accountId || item.accountId || ''),
396
+ selected: item.selected !== false,
397
+ status: ['idle', 'running', 'success', 'error'].includes(item.status) ? item.status : 'idle',
398
+ stage: isStoredCardDecline(item.error)
399
+ ? '绑卡失败'
400
+ : String(item.stage || '待执行').replace(/^注册指纹已就绪$/, '环境已就绪'),
401
+ error: isStoredCardDecline(item.error)
402
+ ? CARD_DECLINE_MESSAGE
403
+ : item.error ? translateError(item.error) : '',
404
+ link: String(item.link || ''),
405
+ taskId: String(item.taskId || ''),
406
+ bindProxyLabel: String(item.bindProxyLabel || ''),
407
+ promoProxyLabel: String(item.promoProxyLabel || ''),
408
+ fingerprint: String(item.fingerprint || ''),
409
+ fingerprintId: String(item.fingerprintId || ''),
410
+ fingerprintTls: String(item.fingerprintTls || ''),
411
+ fingerprintRegion: String(item.fingerprintRegion || ''),
412
+ fingerprintTimezone: String(item.fingerprintTimezone || ''),
413
+ steps: Array.isArray(item.steps) ? item.steps.map((step) => ({
414
+ key: String(step?.key || ''),
415
+ label: String(step?.label || ''),
416
+ status: ['pending', 'running', 'done', 'error'].includes(step?.status) ? step.status : 'pending',
417
+ detail: step?.status === 'error' && step?.detail
418
+ ? translateError(step.detail)
419
+ : String(step?.detail || ''),
420
+ })) : [],
421
+ billingMode: String(item.billingMode || ''),
422
+ billing: item.billing && typeof item.billing === 'object'
423
+ ? normalizedBilling(item.billing, item.email)
424
+ : null,
425
+ }));
426
+ state.nextId = Math.max(Number(saved.nextId) || 1, state.accounts.length + 1);
427
+ if (state.accounts.length !== items.length) saveAccountsNow();
428
+ } catch (_) {
429
+ state.accounts = [];
430
+ state.nextId = 1;
431
+ }
432
+ }
433
+
434
+ function selectedAccounts() {
435
+ return state.accounts.filter((account) => account.selected);
436
+ }
437
+
438
+ function maskProxy(value) {
439
+ const text = String(value || '').trim();
440
+ if (!text) return '';
441
+ try {
442
+ const normalized = text.includes('://') ? text : `http://${text}`;
443
+ const url = new URL(normalized);
444
+ return `${url.protocol}//${url.username ? '***@' : ''}${url.hostname}${url.port ? `:${url.port}` : ''}`;
445
+ } catch (_) {
446
+ const parts = text.split(':');
447
+ return parts.length >= 2 ? `${parts[0]}:${parts[1]}` : '代理节点';
448
+ }
449
+ }
450
+
451
+ function initialAccountSteps(mode) {
452
+ const definitions = [
453
+ ['proxy', '分配代理'],
454
+ ];
455
+ if (mode !== 'link_only') definitions.push(['card_method', '生成支付方式']);
456
+ definitions.push(['fingerprint', '加载指纹'], ['first_link', '首次提链']);
457
+ if (mode === 'bind_only') definitions.push(['bind', '绑卡']);
458
+ else if (mode === 'link_pay') definitions.push(
459
+ ['payment_prepare', '验证支付方式'],
460
+ ['second_link', '刷新支付链接'],
461
+ ['payment', '提交支付'],
462
+ ['verify', '结果校验'],
463
+ );
464
+ else if (mode !== 'link_only') definitions.push(
465
+ ['bind', '绑卡'],
466
+ ['second_link', '二次提链'],
467
+ ['payment', '提交支付'],
468
+ ['verify', '结果校验'],
469
+ );
470
+ return definitions.map(([key, label]) => ({
471
+ key,
472
+ label,
473
+ status: key === 'proxy' ? 'done' : 'pending',
474
+ detail: key === 'proxy' ? (mode === 'link_only' ? '提链代理已分配' : '双代理已分配') : '等待执行',
475
+ }));
476
+ }
477
+
478
+ function setAccountStep(account, key, status, detail) {
479
+ const steps = Array.isArray(account.steps) ? account.steps : [];
480
+ let step = steps.find((item) => item.key === key);
481
+ if (!step) {
482
+ step = { key, label: key, status: 'pending', detail: '等待执行' };
483
+ steps.push(step);
484
+ }
485
+ step.status = status;
486
+ step.detail = detail || step.detail;
487
+ account.steps = steps;
488
+ }
489
+
490
+ function failRunningAccountStep(account, detail) {
491
+ const steps = Array.isArray(account.steps) ? account.steps : [];
492
+ const running = [...steps].reverse().find((step) => step.status === 'running');
493
+ if (running) {
494
+ running.status = 'error';
495
+ running.detail = detail;
496
+ }
497
+ }
498
+
499
+ function assignProxies(accounts, bindPool, promoPool, mode) {
500
+ const bindStart = bindPool.length ? state.bindProxyCursor % bindPool.length : 0;
501
+ const promoStart = state.promoProxyCursor % promoPool.length;
502
+ accounts.forEach((account, index) => {
503
+ account.bindProxy = bindPool.length ? bindPool[(bindStart + index) % bindPool.length] : '';
504
+ account.promoProxy = promoPool[(promoStart + index) % promoPool.length];
505
+ account.bindProxyPool = bindPool.length
506
+ ? bindPool.map((_, offset) => bindPool[(bindStart + index + offset) % bindPool.length]).slice(0, MAX_PROXY_FALLBACKS)
507
+ : [];
508
+ account.promoProxyPool = promoPool
509
+ .map((_, offset) => promoPool[(promoStart + index + offset) % promoPool.length])
510
+ .slice(0, MAX_PROXY_FALLBACKS);
511
+ account.bindProxyLabel = maskProxy(account.bindProxy);
512
+ account.promoProxyLabel = maskProxy(account.promoProxy);
513
+ account.status = 'running';
514
+ account.stage = mode === 'link_only' ? '提链代理分配完成,等待并发启动' : '代理分配完成,等待并发启动';
515
+ account.error = '';
516
+ account.steps = initialAccountSteps(mode);
517
+ });
518
+ if (bindPool.length) state.bindProxyCursor = (bindStart + accounts.length) % bindPool.length;
519
+ state.promoProxyCursor = (promoStart + accounts.length) % promoPool.length;
520
+ renderAccounts();
521
+ saveAccounts();
522
+ }
523
+
524
+ function accountStatusLabel(account) {
525
+ if (account.status === 'success') return '完成';
526
+ if (account.status === 'error') return '失败';
527
+ if (account.status === 'running') return '运行中';
528
+ return '待执行';
529
+ }
530
+
531
+ function renderAccounts() {
532
+ if (accountRenderFrame) {
533
+ window.cancelAnimationFrame(accountRenderFrame);
534
+ accountRenderFrame = 0;
535
+ }
536
+ const root = $('taskRows');
537
+ root.innerHTML = '';
538
+ $('accountEmpty').hidden = state.accounts.length > 0;
539
+
540
+ state.accounts.forEach((account, index) => {
541
+ const row = document.createElement('div');
542
+ row.className = `task-row account-row ${account.status === 'error' ? 'is-error' : ''}`;
543
+ row.dataset.accountId = account.id;
544
+
545
+ const checkbox = document.createElement('input');
546
+ checkbox.type = 'checkbox';
547
+ checkbox.className = 'account-select';
548
+ checkbox.checked = account.selected;
549
+ checkbox.disabled = state.running;
550
+ checkbox.addEventListener('change', () => {
551
+ account.selected = checkbox.checked;
552
+ refresh();
553
+ renderAccounts();
554
+ });
555
+
556
+ const meta = document.createElement('div');
557
+ meta.className = 'task-row__meta account-row__summary';
558
+ const accountName = document.createElement('div');
559
+ accountName.className = 'task-row__account';
560
+ accountName.textContent = account.email || `账号 ${String(index + 1).padStart(2, '0')}`;
561
+ accountName.title = maskToken(account.token);
562
+ const stage = document.createElement('div');
563
+ stage.className = `task-row__stage account-row__current-step ${account.error ? 'is-error' : ''}`;
564
+ const stageLabel = account.stage || '任务失败';
565
+ const errorText = String(account.error || '');
566
+ stage.textContent = errorText
567
+ ? errorText.startsWith(stageLabel) ? errorText : `${stageLabel}:${errorText}`
568
+ : account.stage || '待执行';
569
+ const diagnostics = [
570
+ `AT:${maskToken(account.token)}`,
571
+ account.bindProxyLabel ? `绑卡/支付代理:${account.bindProxyLabel}` : '',
572
+ account.promoProxyLabel ? `提链代理:${account.promoProxyLabel}` : '',
573
+ account.fingerprint ? `指纹:${account.fingerprint}` : '',
574
+ account.billing ? `账单:${account.billing.city || ''}, ${account.billing.state || ''} ${account.billing.postal_code || ''}` : '',
575
+ ].filter(Boolean);
576
+ stage.title = diagnostics.join('\n');
577
+ meta.append(accountName, stage);
578
+ if (account.link) {
579
+ const link = document.createElement('button');
580
+ link.type = 'button';
581
+ link.className = 'task-row__link';
582
+ link.textContent = '复制链接';
583
+ link.title = account.link;
584
+ link.addEventListener('click', async () => {
585
+ const copied = await copyText(account.link);
586
+ link.textContent = copied ? '已复制' : '复制失败';
587
+ window.setTimeout(() => {
588
+ if (link.isConnected) link.textContent = '复制链接';
589
+ }, 1200);
590
+ });
591
+ meta.appendChild(link);
592
+ }
593
+
594
+ const actions = document.createElement('div');
595
+ actions.className = 'account-row-actions';
596
+ const tag = document.createElement('span');
597
+ tag.className = 'tag';
598
+ tag.textContent = accountStatusLabel(account);
599
+ const remove = document.createElement('button');
600
+ remove.type = 'button';
601
+ remove.className = 'at-row__remove';
602
+ remove.textContent = '删除';
603
+ remove.disabled = state.running;
604
+ remove.addEventListener('click', () => {
605
+ state.accounts = state.accounts.filter((item) => item.id !== account.id);
606
+ renderAccounts();
607
+ refresh();
608
+ appendLog('账号已从列表删除。');
609
+ });
610
+ actions.append(tag, remove);
611
+ row.append(checkbox, meta, actions);
612
+ root.appendChild(row);
613
+ });
614
+
615
+ const selected = selectedAccounts().length;
616
+ $('selectAllAccounts').checked = Boolean(state.accounts.length) && selected === state.accounts.length;
617
+ $('selectAllAccounts').indeterminate = selected > 0 && selected < state.accounts.length;
618
+ saveAccounts();
619
+ }
620
+
621
+ async function allocateAccountFingerprint(account, { quiet = false, deferRender = false } = {}) {
622
+ const previousStage = account.stage;
623
+ if (account.status === 'idle') account.stage = '正在分配注册指纹';
624
+ if (!deferRender) scheduleRenderAccounts();
625
+ try {
626
+ const bind = parseProxyPool($('bindProxyPool').value);
627
+ const accountIndex = Math.max(0, state.accounts.indexOf(account));
628
+ const response = await fetch('/api/fingerprint/allocate', {
629
+ method: 'POST',
630
+ headers: { 'Content-Type': 'application/json' },
631
+ body: JSON.stringify({
632
+ access_token: account.token,
633
+ bind_proxy_pool: bind.length ? [bind[accountIndex % bind.length]] : [],
634
+ }),
635
+ });
636
+ const payload = await response.json().catch(() => ({}));
637
+ if (!response.ok || payload.ok === false) {
638
+ throw new Error(payload.error || `指纹分配失败:HTTP ${response.status}`);
639
+ }
640
+ account.email = payload.email || account.email;
641
+ account.accountId = payload.account_id || account.accountId;
642
+ account.fingerprint = String(payload.fingerprint || '');
643
+ account.fingerprintId = String(payload.fingerprint_id || '');
644
+ account.fingerprintTls = String(payload.tls || '');
645
+ account.fingerprintRegion = String(payload.region || '');
646
+ account.fingerprintTimezone = String(payload.timezone || '');
647
+ if (account.status === 'idle') account.stage = '环境已就绪';
648
+ account.error = '';
649
+ if (!quiet) appendLog(`${account.email || account.id}:注册指纹 ${account.fingerprintId} 已分配。`);
650
+ } catch (error) {
651
+ if (account.status === 'idle') account.stage = previousStage || '待执行';
652
+ account.error = translateError(error?.message || error);
653
+ }
654
+ saveAccounts();
655
+ if (!deferRender) scheduleRenderAccounts();
656
+ }
657
+
658
+ async function allocateFingerprints(accounts, { quiet = false } = {}) {
659
+ if (!accounts.length) return;
660
+ const previousStages = new Map();
661
+ accounts.forEach((account) => {
662
+ previousStages.set(account.id, account.stage);
663
+ if (account.status === 'idle') account.stage = '正在批量分配注册指纹';
664
+ });
665
+ scheduleRenderAccounts();
666
+ const bind = parseProxyPool($('bindProxyPool').value);
667
+ for (let offset = 0; offset < accounts.length; offset += 500) {
668
+ const chunk = accounts.slice(offset, offset + 500);
669
+ try {
670
+ const response = await fetch('/api/fingerprint/allocate-batch', {
671
+ method: 'POST',
672
+ headers: { 'Content-Type': 'application/json' },
673
+ body: JSON.stringify({
674
+ accounts: chunk.map((account) => {
675
+ const accountIndex = Math.max(0, state.accounts.indexOf(account));
676
+ return {
677
+ client_id: account.id,
678
+ access_token: account.token,
679
+ bind_proxy_pool: bind.length ? [bind[accountIndex % bind.length]] : [],
680
+ };
681
+ }),
682
+ }),
683
+ });
684
+ const payload = await response.json().catch(() => ({}));
685
+ if (!response.ok || payload.ok === false || !Array.isArray(payload.items)) {
686
+ throw new Error(payload.error || `批量指纹分配失败:HTTP ${response.status}`);
687
+ }
688
+ const byId = new Map(payload.items.map((item) => [String(item?.client_id || ''), item]));
689
+ chunk.forEach((account) => {
690
+ const item = byId.get(account.id) || {};
691
+ if (item.ok === false || !item.fingerprint_id) {
692
+ account.stage = previousStages.get(account.id) || '待执行';
693
+ account.error = translateError(item.error || '批量指纹分配结果缺失');
694
+ return;
695
+ }
696
+ account.email = item.email || account.email;
697
+ account.accountId = item.account_id || account.accountId;
698
+ account.fingerprint = String(item.fingerprint || '');
699
+ account.fingerprintId = String(item.fingerprint_id || '');
700
+ account.fingerprintTls = String(item.tls || '');
701
+ account.fingerprintRegion = String(item.region || '');
702
+ account.fingerprintTimezone = String(item.timezone || '');
703
+ if (account.status === 'idle') account.stage = '环境已就绪';
704
+ account.error = '';
705
+ });
706
+ } catch (error) {
707
+ const message = translateError(error?.message || error);
708
+ chunk.forEach((account) => {
709
+ account.stage = previousStages.get(account.id) || '待执行';
710
+ account.error = message;
711
+ });
712
+ }
713
+ }
714
+ saveAccounts();
715
+ renderAccounts();
716
+ refresh();
717
+ if (!quiet) appendLog(`${accounts.length} 个账号的固定指纹已批量分配。`);
718
+ }
719
+
720
+ async function hydrateMissingFingerprints() {
721
+ // 已落盘且为 US 的兼容指纹直接复用;只修复缺失或旧 TR/chrome144 数据。
722
+ const pending = state.accounts.filter((account) => (
723
+ !account.fingerprintId
724
+ || !account.fingerprintTls
725
+ || String(account.fingerprintRegion || '').toUpperCase() !== 'US'
726
+ || String(account.fingerprintTls || '').toLowerCase() === 'chrome144'
727
+ || /chrome\/144/i.test(String(account.fingerprint || ''))
728
+ ));
729
+ if (!pending.length) return;
730
+ await allocateFingerprints(pending, { quiet: true });
731
+ if (pending.length) appendLog(`已同步 ${pending.length} 个账号的注册指纹与 TLS 兼容版本。`);
732
+ }
733
+
734
+ async function hydrateMissingBillingAddresses() {
735
+ const pending = state.accounts.filter((account) => (
736
+ account.billingMode !== 'auto'
737
+ || billingIssues(normalizedBilling(account.billing || {}, account.email)).length > 0
738
+ ));
739
+ if (pending.length) await assignBillingAddresses(pending);
740
+ }
741
+
742
+ async function importAccounts(text) {
743
+ const values = extractTokens(text);
744
+ const existing = new Set(state.accounts.map((account) => account.token));
745
+ const imported = [];
746
+ let added = 0;
747
+ values.forEach((token) => {
748
+ if (!token || existing.has(token)) return;
749
+ const decoded = decodeAccount(token);
750
+ state.accounts.push({
751
+ id: `account-${state.nextId++}`,
752
+ token,
753
+ email: decoded.email || '',
754
+ accountId: decoded.accountId || '',
755
+ selected: true,
756
+ status: 'idle',
757
+ stage: '待执行',
758
+ error: '',
759
+ link: '',
760
+ taskId: '',
761
+ bindProxyLabel: '',
762
+ promoProxyLabel: '',
763
+ fingerprint: '',
764
+ fingerprintId: '',
765
+ fingerprintTls: '',
766
+ fingerprintRegion: '',
767
+ fingerprintTimezone: '',
768
+ steps: [],
769
+ billingMode: '',
770
+ billing: null,
771
+ });
772
+ imported.push(state.accounts[state.accounts.length - 1]);
773
+ existing.add(token);
774
+ added += 1;
775
+ });
776
+ $('accountImportInput').value = '';
777
+ updateImportCount();
778
+ renderAccounts();
779
+ refresh();
780
+ log(added ? `已导入 ${added} 个账号,导入框已清空。` : '没有发现新的账号。');
781
+ if (imported.length) {
782
+ await Promise.all([
783
+ allocateFingerprints(imported),
784
+ assignBillingAddresses(imported),
785
+ ]);
786
+ }
787
+ }
788
+
789
+ function updateImportCount() {
790
+ $('atCount').textContent = `${extractTokens($('accountImportInput').value).length} 条待导入`;
791
+ }
792
+
793
+ function updateAccount(account, values) {
794
+ Object.assign(account, values);
795
+ saveAccounts();
796
+ scheduleRenderAccounts();
797
+ }
798
+
799
+ function refresh() {
800
+ const bind = parseProxyPool($('bindProxyPool').value);
801
+ const promo = parseProxyPool($('promoProxyPool').value);
802
+ const selected = selectedAccounts();
803
+ const billingMissingAccounts = state.publishableKey
804
+ ? selected.filter((account) => billingIssues(normalizedBilling(account.billing || {}, account.email)).length > 0)
805
+ : [];
806
+ $('bindProxyCount').textContent = `${bind.length} PROXY`;
807
+ $('promoProxyCount').textContent = `${promo.length} PROXY`;
808
+ const basicReady = Boolean(selected.length && bind.length && promo.length);
809
+ const linkOnlyReady = Boolean(selected.length && promo.length);
810
+ const cardInputReady = state.mounted && Object.values(state.complete).every(Boolean);
811
+ const billingReady = !state.publishableKey || billingMissingAccounts.length === 0;
812
+ const ready = basicReady && cardInputReady && billingReady;
813
+ $('loadCardButton').disabled = state.mounted || state.running;
814
+ ['batchBindLinkButton', 'fullFlowButton', 'linkPayButton'].forEach((id) => {
815
+ $(id).disabled = !ready || state.running;
816
+ });
817
+ $('linkOnlyButton').disabled = !linkOnlyReady || state.running;
818
+ $('deleteSelectedButton').disabled = state.running || !selected.length;
819
+ $('exportCsvButton').disabled = !state.accounts.length;
820
+ $('clearButton').disabled = state.running || !state.accounts.length;
821
+ $('selectAllAccounts').disabled = state.running || !state.accounts.length;
822
+ $('cardReady').className = `inline-state ${ready ? 'ok' : ''}`;
823
+ if (ready) $('cardReady').textContent = `卡片输入已就绪;已选择 ${selected.length} 个账号。`;
824
+ else if (!basicReady) $('cardReady').textContent = '请先导入并选择账号,填写双代理池后再加载卡片。';
825
+ else if (!billingReady) $('cardReady').textContent = `还有 ${billingMissingAccounts.length} 个账号的账单地址未就绪。`;
826
+ return { accounts: selected, bind, promo, basicReady, linkOnlyReady, cardInputReady, billingReady, billingMissingAccounts, ready };
827
+ }
828
+
829
+ async function mountCard() {
830
+ const data = refresh();
831
+ if (state.mounted) return;
832
+ if (!data.basicReady) {
833
+ const missing = [];
834
+ if (!data.accounts.length) missing.push('已选择账号');
835
+ if (!data.bind.length) missing.push('绑卡代理池');
836
+ if (!data.promo.length) missing.push('提链代理池');
837
+ $('cardReady').className = 'inline-state error';
838
+ $('cardReady').textContent = `加载卡片前还缺少:${missing.join('、')}`;
839
+ appendLog($('cardReady').textContent);
840
+ return;
841
+ }
842
+ $('loadCardButton').disabled = true;
843
+ $('cardReady').textContent = '正在并行加载 Stripe、安全地址与 Checkout…';
844
+ try {
845
+ const missingBilling = state.accounts.filter((account) => (
846
+ billingIssues(normalizedBilling(account.billing || {}, account.email)).length > 0
847
+ ));
848
+ const previewBind = data.bind[state.bindProxyCursor % data.bind.length];
849
+ const previewPromo = data.promo[state.promoProxyCursor % data.promo.length];
850
+ const checkoutPromise = fetch('/api/card-bind/session', {
851
+ method: 'POST',
852
+ headers: { 'Content-Type': 'application/json' },
853
+ body: JSON.stringify({
854
+ access_token: data.accounts[0].token,
855
+ bind_proxy_pool: [previewBind],
856
+ promo_proxy_pool: [previewPromo],
857
+ }),
858
+ });
859
+ const billingPromise = assignBillingAddresses(missingBilling).catch((error) => {
860
+ const message = translateError(error.message);
861
+ $('billingAutoStatus').className = 'billing-auto-status error';
862
+ $('billingAutoStatus').textContent = `自动账单地址获取失败:${message}`;
863
+ appendLog(message);
864
+ return false;
865
+ });
866
+ const [, response] = await Promise.all([
867
+ ensureStripeJs(),
868
+ checkoutPromise,
869
+ ]);
870
+ void billingPromise;
871
+ const payload = await response.json().catch(() => ({}));
872
+ if (!response.ok || payload.ok === false) throw new Error(payload.error || `预检失败:HTTP ${response.status}`);
873
+ data.accounts[0].fingerprint = String(payload.fingerprint || data.accounts[0].fingerprint || '');
874
+ data.accounts[0].fingerprintId = String(payload.fingerprint_id || data.accounts[0].fingerprintId || '');
875
+ data.accounts[0].fingerprintTls = String(payload.fingerprint_tls || data.accounts[0].fingerprintTls || '');
876
+ data.accounts[0].fingerprintRegion = String(payload.fingerprint_region || data.accounts[0].fingerprintRegion || '');
877
+ data.accounts[0].fingerprintTimezone = String(payload.fingerprint_timezone || data.accounts[0].fingerprintTimezone || '');
878
+ saveAccounts();
879
+ renderAccounts();
880
+ const key = String(payload.publishable_key || '');
881
+ if (!key.startsWith('pk_')) throw new Error('Checkout 没有返回有效的 Stripe 公钥');
882
+ state.publishableKey = key;
883
+ state.stripe = window.Stripe(key);
884
+ const elements = state.stripe.elements();
885
+ const style = {
886
+ base: { fontSize: '15px', color: '#e7f0fb', '::placeholder': { color: '#70869e' } },
887
+ invalid: { color: '#ff7186' },
888
+ };
889
+ state.elements.number = elements.create('cardNumber', { showIcon: true, style });
890
+ state.elements.expiry = elements.create('cardExpiry', { style });
891
+ state.elements.cvc = elements.create('cardCvc', { style });
892
+ [['number', 'cardNumberElement'], ['expiry', 'cardExpiryElement'], ['cvc', 'cardCvcElement']].forEach(([name, id]) => {
893
+ state.elements[name].mount(`#${id}`);
894
+ state.elements[name].on('change', (event) => {
895
+ state.complete[name] = Boolean(event.complete);
896
+ if (event.error) $('cardReady').textContent = translateError(event.error.message);
897
+ refresh();
898
+ });
899
+ });
900
+ state.mounted = true;
901
+ setStep('stepCard', 'done');
902
+ setStep('stepAt', 'active');
903
+ $('cardReady').textContent = `安全卡片输入框已加载:${payload.country || 'PH'}/${payload.currency || 'PHP'}`;
904
+ appendLog('卡片输入框已加载,后续任务由独立 HTTP 服务处理。');
905
+ refresh();
906
+ } catch (error) {
907
+ const message = translateError(error.message);
908
+ $('loadCardButton').disabled = false;
909
+ $('cardReady').className = 'inline-state error';
910
+ $('cardReady').textContent = message;
911
+ appendLog(message);
912
+ }
913
+ }
914
+
915
+ async function createPaymentMethod(account) {
916
+ if (!state.stripe || !state.elements.number) throw new Error('卡片输入框尚未加载');
917
+ const billing = normalizedBilling(account?.billing || {}, account?.email || '');
918
+ const issues = billingIssues(billing);
919
+ if (issues.length) throw new Error(`${account?.email || account?.id || '当前账号'} 的账单地址缺少:${issues.join('、')}`);
920
+ const result = await state.stripe.createPaymentMethod({
921
+ type: 'card',
922
+ card: state.elements.number,
923
+ billing_details: {
924
+ name: billing.name,
925
+ email: billing.email || undefined,
926
+ address: {
927
+ line1: billing.line1,
928
+ line2: billing.line2 || undefined,
929
+ city: billing.city,
930
+ state: billing.state || undefined,
931
+ postal_code: billing.postal_code,
932
+ country: billing.country,
933
+ },
934
+ },
935
+ });
936
+ if (result.error) throw new Error(result.error.message || 'PaymentMethod 创建失败');
937
+ const paymentMethod = result.paymentMethod || {};
938
+ if (!paymentMethod.id) throw new Error('PaymentMethod 创建失败');
939
+ return { id: paymentMethod.id, last4: paymentMethod.card?.last4 || '', billing };
940
+ }
941
+
942
+ async function prepareAccountCard(account) {
943
+ updateAccount(account, { status: 'running', stage: '正在准备同批同步起跑', error: '' });
944
+ setAccountStep(account, 'card_method', 'running', '正在通过安全卡片输入框生成支付方式');
945
+ renderAccounts();
946
+ const browserCard = await createPaymentMethod(account);
947
+ setAccountStep(account, 'card_method', 'done', `支付方式已生成 ····${browserCard.last4 || ''}`);
948
+ updateAccount(account, { stage: '支付方式已生成,等待同批账号同步起跑' });
949
+ return browserCard;
950
+ }
951
+
952
+ function accountFlowPayload(account, mode, browserCard) {
953
+ const payload = {
954
+ access_token: account.token,
955
+ flow_mode: mode,
956
+ promo_proxy_pool: account.promoProxyPool?.length ? account.promoProxyPool : [account.promoProxy],
957
+ };
958
+ if (mode !== 'link_only') Object.assign(payload, {
959
+ payment_method_id: browserCard.id,
960
+ card_last4: browserCard.last4,
961
+ billing: browserCard.billing,
962
+ bind_proxy_pool: account.bindProxyPool?.length ? account.bindProxyPool : [account.bindProxy],
963
+ });
964
+ return payload;
965
+ }
966
+
967
+ async function pollAccountTask(account, taskId) {
968
+ updateAccount(account, { stage: '同批任务已放行,正在同步执行', taskId });
969
+ for (let i = 0; i < Math.ceil(1800000 / TASK_POLL_MS); i += 1) {
970
+ await new Promise((resolve) => setTimeout(resolve, TASK_POLL_MS));
971
+ if (state.stop) throw new Error('任务已停止');
972
+ const poll = await fetch(`/api/standalone-flow/task/${taskId}?t=${Date.now()}`, { cache: 'no-store' });
973
+ const data = await poll.json().catch(() => ({}));
974
+ const task = data.task || {};
975
+ const result = task.result || {};
976
+ if (Array.isArray(task.steps)) account.steps = task.steps;
977
+ if (task.status === 'done') {
978
+ updateAccount(account, {
979
+ email: result.email || account.email,
980
+ status: 'success',
981
+ stage: task.stage || '任务完成',
982
+ link: result.checkout_link || '',
983
+ error: '',
984
+ taskId: '',
985
+ fingerprint: result.fingerprint || account.fingerprint || '',
986
+ steps: Array.isArray(task.steps) ? task.steps : account.steps,
987
+ });
988
+ return result;
989
+ }
990
+ if (task.status === 'error') {
991
+ account.taskId = '';
992
+ account.stage = task.stage || '任务执行失败';
993
+ account.steps = Array.isArray(task.steps) ? task.steps : account.steps;
994
+ saveAccounts();
995
+ throw new Error(task.error || '任务执行失败');
996
+ }
997
+ const nextStage = task.stage || '任务处理中';
998
+ if (nextStage !== account.stage) {
999
+ updateAccount(account, {
1000
+ stage: nextStage,
1001
+ steps: Array.isArray(task.steps) ? task.steps : account.steps,
1002
+ });
1003
+ }
1004
+ }
1005
+ throw new Error('任务轮询超时');
1006
+ }
1007
+
1008
+ async function submitAlignedWave(entries, mode) {
1009
+ entries.forEach(({ account }) => updateAccount(account, {
1010
+ stage: `本批 ${entries.length} 个账号已就绪,等待统一放行`,
1011
+ }));
1012
+ const response = await fetch('/api/standalone-flow/quick-checkout-batch', {
1013
+ method: 'POST',
1014
+ headers: { 'Content-Type': 'application/json' },
1015
+ body: JSON.stringify({
1016
+ start_delay_ms: 250,
1017
+ tasks: entries.map(({ account, browserCard }) => ({
1018
+ client_id: account.id,
1019
+ payload: accountFlowPayload(account, mode, browserCard),
1020
+ })),
1021
+ }),
1022
+ });
1023
+ const payload = await response.json().catch(() => ({}));
1024
+ if (!response.ok || payload.ok === false || !Array.isArray(payload.items)) {
1025
+ throw new Error(payload.error || `同步批次创建失败:HTTP ${response.status}`);
1026
+ }
1027
+ const byId = new Map(payload.items.map((item) => [String(item.client_id || ''), item.task_id]));
1028
+ entries.forEach(({ account }) => {
1029
+ const taskId = String(byId.get(account.id) || '');
1030
+ if (!taskId) throw new Error(`${account.email || account.id} 缺少同步任务 ID`);
1031
+ account.taskId = taskId;
1032
+ account.stage = `同步批次 ${String(payload.start_group || '').slice(0, 8)} 已排队`;
1033
+ });
1034
+ renderAccounts();
1035
+ return Promise.allSettled(entries.map(({ account }) => pollAccountTask(account, account.taskId)));
1036
+ }
1037
+
1038
+ function setModeSteps(mode, status) {
1039
+ ['stepCard', 'stepAt', 'stepBind', 'stepLink'].forEach((id) => setStep(id, ''));
1040
+ if (mode !== 'link_only') setStep('stepCard', 'done');
1041
+ setStep('stepAt', 'done');
1042
+ if (mode === 'bind_only') setStep('stepBind', status);
1043
+ else if (mode === 'link_pay' || mode === 'link_only') setStep('stepLink', status);
1044
+ else {
1045
+ setStep('stepBind', status);
1046
+ setStep('stepLink', status);
1047
+ }
1048
+ }
1049
+
1050
+ function updateProgress(done, total, label) {
1051
+ const percent = total ? Math.round((done * 100) / total) : 0;
1052
+ $('progressText').textContent = `${label} ${done}/${total}`;
1053
+ $('progressPercent').textContent = `${percent}%`;
1054
+ $('progressBar').style.width = `${percent}%`;
1055
+ }
1056
+
1057
+ async function runBatch(mode, label) {
1058
+ const data = refresh();
1059
+ if ((mode === 'link_only' ? !data.linkOnlyReady : !data.ready) || state.running) return;
1060
+ const accounts = [...data.accounts];
1061
+ state.running = true;
1062
+ state.stop = false;
1063
+ hideBatchSummary();
1064
+ $('stopButton').disabled = false;
1065
+ renderAccounts();
1066
+ refresh();
1067
+ setModeSteps(mode, 'active');
1068
+ const limit = Math.max(1, Math.min(MAX_BATCH_CONCURRENCY, Number($('batchConcurrency').value) || 1));
1069
+ updateProgress(0, accounts.length, '正在分配代理');
1070
+ assignProxies(accounts, data.bind, data.promo, mode);
1071
+ appendLog(`已为 ${accounts.length} 个账号分配${mode === 'link_only' ? '提链代理' : '双代理'},每批 ${Math.min(limit, accounts.length)} 个账号同步起跑。`);
1072
+ updateProgress(0, accounts.length, `${label}同步并发`);
1073
+ let done = 0;
1074
+ let success = 0;
1075
+
1076
+ function recordFailure(account, error) {
1077
+ const message = translateError(error?.message || error);
1078
+ failRunningAccountStep(account, message);
1079
+ const preciseStage = String(account.stage || '');
1080
+ const failedStep = [...(account.steps || [])].reverse().find((step) => step.status === 'error');
1081
+ updateAccount(account, {
1082
+ status: 'error',
1083
+ stage: failedStep?.label
1084
+ ? `${failedStep.label}失败`
1085
+ : preciseStage.includes('失败') ? preciseStage : `${label}失败`,
1086
+ error: message,
1087
+ });
1088
+ appendLog(`${account.email || account.id}:${message}`);
1089
+ }
1090
+
1091
+ for (let offset = 0; offset < accounts.length && !state.stop; offset += limit) {
1092
+ const wave = accounts.slice(offset, offset + limit);
1093
+ const prepared = [];
1094
+ updateProgress(done, accounts.length, `正在准备同步批次 ${Math.floor(offset / limit) + 1}`);
1095
+ for (const account of wave) {
1096
+ if (state.stop) break;
1097
+ try {
1098
+ if (mode === 'link_only') {
1099
+ updateAccount(account, { status: 'running', stage: '提链代理已就绪,等待同批同步起跑', error: '' });
1100
+ prepared.push({ account, browserCard: null });
1101
+ } else {
1102
+ const browserCard = await prepareAccountCard(account);
1103
+ prepared.push({ account, browserCard });
1104
+ }
1105
+ } catch (error) {
1106
+ recordFailure(account, error);
1107
+ done += 1;
1108
+ updateProgress(done, accounts.length, label);
1109
+ }
1110
+ }
1111
+ if (!prepared.length || state.stop) continue;
1112
+ appendLog(`同步批次 ${Math.floor(offset / limit) + 1}:${prepared.length} 个账号已就绪,统一放行。`);
1113
+ try {
1114
+ const settled = await submitAlignedWave(prepared, mode);
1115
+ settled.forEach((result, index) => {
1116
+ const account = prepared[index].account;
1117
+ if (result.status === 'fulfilled') success += 1;
1118
+ else recordFailure(account, result.reason);
1119
+ done += 1;
1120
+ updateProgress(done, accounts.length, label);
1121
+ });
1122
+ } catch (error) {
1123
+ prepared.forEach(({ account }) => {
1124
+ recordFailure(account, error);
1125
+ done += 1;
1126
+ updateProgress(done, accounts.length, label);
1127
+ });
1128
+ }
1129
+ }
1130
+ if (state.stop) {
1131
+ accounts.filter((account) => account.status === 'running' && !account.taskId).forEach((account) => {
1132
+ account.status = 'idle';
1133
+ account.stage = '已停止,尚未执行';
1134
+ });
1135
+ }
1136
+ state.running = false;
1137
+ $('stopButton').disabled = true;
1138
+ if (success === accounts.length && !state.stop) setModeSteps(mode, 'done');
1139
+ $('progressText').textContent = state.stop ? `${label}已停止` : `${label}完成`;
1140
+ showBatchSummary(
1141
+ mode === 'bind_only' ? '批量绑卡' : mode === 'link_only' ? '批量提链' : '批量支付',
1142
+ success,
1143
+ Math.max(0, accounts.length - success),
1144
+ state.stop,
1145
+ );
1146
+ renderAccounts();
1147
+ refresh();
1148
+ }
1149
+
1150
+ $('accountImportInput').addEventListener('input', updateImportCount);
1151
+ $('importAtButton').addEventListener('click', () => { void importAccounts($('accountImportInput').value); });
1152
+ $('importAtFileButton').addEventListener('click', () => $('atFileInput').click());
1153
+ $('atFileInput').addEventListener('change', async (event) => {
1154
+ const file = event.target.files?.[0];
1155
+ if (file) await importAccounts(await file.text());
1156
+ event.target.value = '';
1157
+ });
1158
+ $('selectAllAccounts').addEventListener('change', (event) => {
1159
+ state.accounts.forEach((account) => { account.selected = event.target.checked; });
1160
+ renderAccounts();
1161
+ refresh();
1162
+ });
1163
+ $('deleteSelectedButton').addEventListener('click', () => {
1164
+ const count = selectedAccounts().length;
1165
+ state.accounts = state.accounts.filter((account) => !account.selected);
1166
+ renderAccounts();
1167
+ refresh();
1168
+ appendLog(`已删除 ${count} 个账号。`);
1169
+ });
1170
+ $('clearButton').addEventListener('click', () => {
1171
+ const count = state.accounts.length;
1172
+ state.accounts = [];
1173
+ renderAccounts();
1174
+ refresh();
1175
+ $('progressBar').style.width = '0%';
1176
+ $('progressPercent').textContent = '0%';
1177
+ hideBatchSummary();
1178
+ appendLog(`账号列表已清空,共移除 ${count} 个账号。`);
1179
+ });
1180
+ $('exportCsvButton').addEventListener('click', () => {
1181
+ appendLog(exportAccountsCsv() ? 'CSV 已导出。' : '当前没有可导出的账号。');
1182
+ });
1183
+ $('loadCardButton').addEventListener('click', mountCard);
1184
+ $('bindProxyPool').addEventListener('input', () => { saveProxyDraft(); refresh(); });
1185
+ $('promoProxyPool').addEventListener('input', () => { saveProxyDraft(); refresh(); });
1186
+ $('batchConcurrency').addEventListener('input', saveProxyDraft);
1187
+ $('validateButton').addEventListener('click', () => {
1188
+ const data = refresh();
1189
+ const issues = [];
1190
+ if (!state.accounts.length) issues.push('尚未导入账号');
1191
+ else if (!data.accounts.length) issues.push('尚未选择账号');
1192
+ if (!data.bind.length) issues.push('缺少代理池 1');
1193
+ if (!data.promo.length) issues.push('缺少代理池 2');
1194
+ if (!state.mounted) issues.push('卡片输入框尚未加载');
1195
+ if (!data.billingReady) issues.push(`还有 ${data.billingMissingAccounts.length} 个账号账单地址未就绪`);
1196
+ $('progressText').textContent = issues.length
1197
+ ? `检查输入:${issues.join(';')}`
1198
+ : `检查通过:已选择 ${data.accounts.length} 个账号。`;
1199
+ });
1200
+ $('fullFlowButton').addEventListener('click', () => runBatch('full', '提链 + 绑卡 + 提链 + 支付'));
1201
+ $('batchBindLinkButton').addEventListener('click', () => runBatch('bind_only', '提链 + 绑卡'));
1202
+ $('linkPayButton').addEventListener('click', () => runBatch('link_pay', '提链 + 支付'));
1203
+ $('linkOnlyButton').addEventListener('click', () => runBatch('link_only', '提链'));
1204
+ $('stopButton').addEventListener('click', () => {
1205
+ state.stop = true;
1206
+ $('stopButton').disabled = true;
1207
+ appendLog('已停止后续账号任务。');
1208
+ });
1209
+ window.addEventListener('pagehide', saveAccountsNow);
1210
+
1211
+ loadProxyDraft();
1212
+ loadAccounts();
1213
+ updateImportCount();
1214
+ renderAccounts();
1215
+ refresh();
1216
+ log(state.accounts.length ? `已恢复 ${state.accounts.length} 个账号及其状态。` : '先在上方导入账号,再填写代理与卡片。');
1217
+ void Promise.all([hydrateMissingFingerprints(), hydrateMissingBillingAddresses()]);
1218
+ }());
index.html CHANGED
@@ -4,7 +4,7 @@
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width,initial-scale=1">
6
  <title>直卡绑卡 · 提链 · 协议支付</title>
7
- <link rel="stylesheet" href="/static/direct-bind.css?v=20260804-34">
8
  </head>
9
  <body>
10
  <main class="shell batch-shell">
@@ -36,7 +36,7 @@
36
  <div class="billing-head"><b>账单地址</b><small>每个账号分别从地址接口自动获取</small></div>
37
  <div id="billingAutoStatus" class="billing-auto-status">等待加载卡片后自动获取,无需填写</div>
38
  <div id="cardReady" class="inline-state">请先导入账号并填写代理池,再加载安全卡片输入框</div>
39
- <button id="loadCardButton" class="secondary load-card-button" type="button" disabled>加载安全卡片输入框</button>
40
  </section>
41
 
42
  <section class="batch-section account-import-section">
@@ -105,7 +105,7 @@
105
  <div id="batchSummary" class="batch-summary" hidden></div>
106
  </section>
107
  </main>
108
- <script src="/static/direct-bind.js?v=20260804-51"></script>
109
  </body>
110
  </html>
111
 
 
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width,initial-scale=1">
6
  <title>直卡绑卡 · 提链 · 协议支付</title>
7
+ <link rel="stylesheet" href="/static/direct-bind.css?v=20260804-35">
8
  </head>
9
  <body>
10
  <main class="shell batch-shell">
 
36
  <div class="billing-head"><b>账单地址</b><small>每个账号分别从地址接口自动获取</small></div>
37
  <div id="billingAutoStatus" class="billing-auto-status">等待加载卡片后自动获取,无需填写</div>
38
  <div id="cardReady" class="inline-state">请先导入账号并填写代理池,再加载安全卡片输入框</div>
39
+ <button id="loadCardButton" class="secondary load-card-button" type="button">加载安全卡片输入框</button>
40
  </section>
41
 
42
  <section class="batch-section account-import-section">
 
105
  <div id="batchSummary" class="batch-summary" hidden></div>
106
  </section>
107
  </main>
108
+ <script src="/static/direct-bind.js?v=20260804-52"></script>
109
  </body>
110
  </html>
111