#!/usr/bin/env node /* ------------------------------------------------------------------------- * 项目名称:绿地尊享会(每日签到 + 连签奖励) * 脚本文件:lvdi_zunxiang_signin.js * 更新说明: * 2026-12-02 Mist 仓库首发:H5 免签通道 + 账号密码登录 + CK 自动续期 + 滑块自解 * ------------------------------------------------------------------------- * Author : Mist * 声明 : 仅供个人学习与技术研究,仅用于自己有权操作的账号,风险自负 * ------------------------------------------------------------------------- * cron "10 8 * * *" lvdi_zunxiang_signin.js * new Env('绿地尊享会(签到)'); */ 'use strict'; const fs = require('fs'); const path = require('path'); const os = require('os'); const https = require('https'); const http = require('http'); const zlib = require('zlib'); const crypto = require('crypto'); // ============================================================================ // 一、配置项 // ============================================================================ const ENV_ACCOUNT = 'ld_account'; // 手机号#密码(多账号换行) const ENV_CK = 'ld_ck'; // 手动塞 memberToken(可选,一行一个) const ENV_OCR = 'ld_ocr'; // http://IP:6688|账号|密码(可选,滑块兜底) const ENV_SIGNCODE = 'ld_signcode'; // 签到活动码,默认 LDJFQD const ENV_OPENID = 'ld_openid'; // 指定 openid(一般不用填) const ENV_RELOGIN = 'ld_relogin'; // auto / always / never const ENV_DELAY = 'ld_delay'; // 多账号间隔,默认 5-10 秒 const ENV_CLAIM = 'ld_claim'; // 连签奖励自动领取,默认 on const ENV_PUSH = 'TYpush'; // off 关闭推送 const ENV_PUSH_MD = 'ld_push_md'; // on 用 markdown 推送 const ENV_DEBUG = 'ld_debug'; // on 打印调试 // ── 站点常量(全部来自抓包,别乱改)──────────────────────────────────────── const HOST = 'wx4a359c7b9ddf878b.wx.gcihotel.net'; const H5_APPID = 'wx4a359c7b9ddf878b'; // H5 侧 appid const MP_APPID = 'wx17d27ce1cca04bd7'; // 小程序侧 appid(登录接口要用这个) const COMPONENT_APPID = 'wxe715bd146a4e468b'; // 第三方平台(绿地)appid const HOTEL_GROUP_CODE = 'GIHG'; const HOTEL_GROUP_ID = '1'; const HOTEL_CODE = '0'; const DEFAULT_SIGN_CODE = 'LDJFQD'; const CK_CACHE_NAME = '.ldzx_ck.json'; const OCR_CACHE_NAME = '.ldzx_ocr.json'; const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' + 'Chrome/144.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI ' + 'MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) ' + 'UnifiedPCWindowsWechat(0xf2541f37) XWEB/25799 miniProgram/wx17d27ce1cca04bd7'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const rand = (a, b) => a + Math.random() * (b - a); const DEBUG = /^(1|on|true|yes)$/i.test(String(process.env[ENV_DEBUG] || '')); // ============================================================================ // 二、终端输出(和 youzan_signin.js 保持同一套风格) // ============================================================================ function strWidth(s) { let w = 0; for (const ch of String(s)) { const c = ch.codePointAt(0); w += (c >= 0x1100 && ( c <= 0x115f || c === 0x2329 || c === 0x232a || (c >= 0x2e80 && c <= 0xa4cf && c !== 0x303f) || (c >= 0xac00 && c <= 0xd7a3) || (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe6f) || (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6) || (c >= 0x1f300 && c <= 0x1f64f) || (c >= 0x1f900 && c <= 0x1f9ff) || (c >= 0x20000 && c <= 0x3fffd) )) ? 2 : 1; } return w; } const padR = (s, n) => { s = String(s); const d = n - strWidth(s); return s + ' '.repeat(d > 0 ? d : 0); }; const line = (w = 58) => '─'.repeat(w); function boxTitle(t, w = 54) { console.log(''); console.log('┌' + '─'.repeat(w) + '┐'); const d = w - strWidth(t); const l = Math.floor((d - 2) / 2); console.log('│ ' + ' '.repeat(Math.max(0, l)) + t + ' '.repeat(Math.max(0, d - 2 - l)) + ' │'); console.log('└' + '─'.repeat(w) + '┘'); } const section = (t, w = 58) => { console.log(''); console.log('▌' + t + ' ' + line(Math.max(4, w - strWidth(t) - 2))); }; const kv = (k, v) => console.log(` ${padR(k, 12)} ${v}`); const maskPhone = (p) => String(p || '').replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2'); const maskToken = (t) => { const s = String(t || ''); return s.length <= 16 ? s : s.slice(0, 12) + '…' + s.slice(-6); }; // ============================================================================ // 三、HTTP 与响应解析 // ============================================================================ function request(opts) { return new Promise((resolve, reject) => { const u = new URL(opts.url); const lib = u.protocol === 'https:' ? https : http; const headers = { 'User-Agent': UA, Accept: '*/*', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate', ...(opts.headers || {}), }; let body = null; if (opts.data !== undefined && opts.data !== null) { body = Buffer.from(typeof opts.data === 'string' ? opts.data : JSON.stringify(opts.data), 'utf8'); headers['Content-Length'] = body.length; if (!headers['Content-Type']) headers['Content-Type'] = 'application/json'; } const req = lib.request( { protocol: u.protocol, hostname: u.hostname, port: u.port || (u.protocol === 'https:' ? 443 : 80), path: u.pathname + u.search, method: opts.method || 'GET', headers, timeout: opts.timeout || 20000, }, (res) => { const cs = []; res.on('data', (c) => cs.push(c)); res.on('end', () => { let buf = Buffer.concat(cs); const enc = String(res.headers['content-encoding'] || '').toLowerCase(); try { if (enc.includes('gzip')) buf = zlib.gunzipSync(buf); else if (enc.includes('deflate')) buf = zlib.inflateSync(buf); else if (enc.includes('br') && zlib.brotliDecompressSync) buf = zlib.brotliDecompressSync(buf); } catch (e) { /* 忽略 */ } resolve({ status: res.statusCode, headers: res.headers, text: buf.toString('utf8') }); }); } ); req.on('timeout', () => req.destroy(new Error('请求超时'))); req.on('error', reject); if (body) req.write(body); req.end(); }); } /** * 这个后端的响应有两种形态: * ① 纯 JSON {"msg":"","result":1,...} * ② Base64(JSON) eyJtc2ciOiIiLCJyZXN1bHQiOjEs... ← 小程序/H5 渠道常见 * 两种都兼容,省得猜客户端版本。 */ function parseApi(text) { const t = String(text || '').trim(); if (!t) return null; if (t[0] === '{' || t[0] === '[') { try { return JSON.parse(t); } catch (e) { /* 继续 */ } } try { const d = Buffer.from(t, 'base64').toString('utf8'); if (d[0] === '{' || d[0] === '[') return JSON.parse(d); } catch (e) { /* 忽略 */ } return null; } /** 统一拼 query,空值也保留(服务端有 Required 校验,少参数直接 500 报文) */ function qs(obj) { return Object.entries(obj) .filter(([, v]) => v !== undefined && v !== null) .map(([k, v]) => `${k}=${encodeURIComponent(String(v))}`) .join('&'); } /** 带 memberToken 的 API 调用(H5 域名,免网关签名) */ async function api(acc, apiPath, { method = 'GET', query = null, data = null, timeout = 20000 } = {}) { const q = Object.assign({}, query || {}); if (acc && acc.token) q.memberToken = acc.token; const url = `https://${HOST}${apiPath}` + (Object.keys(q).length ? '?' + qs(q) : ''); const headers = { Referer: `https://${HOST}/wechat/?/`, Origin: `https://${HOST}`, }; if (acc && acc.token) headers.memberToken = acc.token; const r = await request({ url, method, data, headers, timeout }); return { status: r.status, raw: r.text, data: parseApi(r.text) }; } // ============================================================================ // 四、加密 / 编码 // ============================================================================ /** 密码 = 明文 Base64(抓包实证,不是 AES 也不是 RSA) */ function b64(text) { return Buffer.from(String(text), 'utf8').toString('base64'); } /** AES-128-ECB / PKCS7 / Base64 —— 复刻前端 chunk0.js 里的 aes() */ function aesEcb(plain, key) { const k = Buffer.from(String(key), 'utf8'); if (k.length !== 16) throw new Error('secretKey 长度不是 16:' + key); const c = crypto.createCipheriv('aes-128-ecb', k, null); c.setAutoPadding(true); // PKCS7 return Buffer.concat([c.update(Buffer.from(String(plain), 'utf8')), c.final()]).toString('base64'); } /** 反解,调试用 */ function aesEcbDecrypt(cipherB64, key) { const k = Buffer.from(String(key), 'utf8'); const d = crypto.createDecipheriv('aes-128-ecb', k, null); d.setAutoPadding(true); return Buffer.concat([d.update(Buffer.from(cipherB64, 'base64')), d.final()]).toString('utf8'); } function uuid32() { return crypto.randomBytes(16).toString('hex'); } // ============================================================================ // 五、PNG 解码(不引三方库,青龙里啥都没装也能跑) // ============================================================================ /** * 只支持 8bit、非隔行的 PNG —— 滑块图固定是 310×155 / 47×155 的 RGBA, * 够用。返回 {width, height, channels, data:Buffer(RGBA 或 RGB)} */ function decodePng(buf) { if (buf.readUInt32BE(0) !== 0x89504e47) throw new Error('不是 PNG'); let pos = 8; let w = 0, h = 0, bd = 8, ct = 6, interlace = 0; const idat = []; while (pos + 8 <= buf.length) { const len = buf.readUInt32BE(pos); const type = buf.toString('ascii', pos + 4, pos + 8); const data = buf.slice(pos + 8, pos + 8 + len); if (type === 'IHDR') { w = data.readUInt32BE(0); h = data.readUInt32BE(4); bd = data[8]; ct = data[9]; interlace = data[12]; } else if (type === 'IDAT') { idat.push(data); } else if (type === 'IEND') break; pos += 12 + len; } if (!w || !h) throw new Error('PNG 头解析失败'); if (bd !== 8) throw new Error('不支持的位深 ' + bd); if (interlace) throw new Error('不支持隔行 PNG'); const chMap = { 0: 1, 2: 3, 4: 2, 6: 4 }; const channels = chMap[ct]; if (!channels) throw new Error('不支持的 PNG 颜色类型 ' + ct); const raw = zlib.inflateSync(Buffer.concat(idat)); const bpp = channels; const stride = w * bpp; const out = Buffer.alloc(h * stride); let p = 0; for (let y = 0; y < h; y++) { const f = raw[p++]; const src = raw.slice(p, p + stride); p += stride; const curOff = y * stride; const prevOff = (y - 1) * stride; for (let i = 0; i < stride; i++) { const a = i >= bpp ? out[curOff + i - bpp] : 0; const b = y > 0 ? out[prevOff + i] : 0; const c = i >= bpp && y > 0 ? out[prevOff + i - bpp] : 0; let v = src[i]; switch (f) { case 0: break; case 1: v = (v + a) & 255; break; case 2: v = (v + b) & 255; break; case 3: v = (v + ((a + b) >> 1)) & 255; break; case 4: { const pp = a + b - c; const pa = Math.abs(pp - a), pb = Math.abs(pp - b), pc = Math.abs(pp - c); const pr = pa <= pb && pa <= pc ? a : pb <= pc ? b : c; v = (v + pr) & 255; break; } default: throw new Error('未知 PNG 滤波类型 ' + f); } out[curOff + i] = v; } } return { width: w, height: h, channels, data: out }; } function toGray(img) { const { width: w, height: h, channels: c, data } = img; const g = new Float32Array(w * h); for (let i = 0; i < w * h; i++) { const o = i * c; g[i] = c >= 3 ? 0.299 * data[o] + 0.587 * data[o + 1] + 0.114 * data[o + 2] : data[o]; } return g; } /** 拼图条里真素材的包围盒(alpha > 40 才算) */ function pieceBox(img) { const { width: w, height: h, channels: c, data } = img; if (c !== 2 && c !== 4) return { x: 0, y: 0, w, h }; const ai = c === 4 ? 3 : 1; let x0 = w, x1 = -1, y0 = h, y1 = -1; for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { if (data[(y * w + x) * c + ai] > 40) { if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; } } } if (x1 < 0) return { x: 0, y: 0, w, h }; return { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 }; } /** * 缺口定位:灰度 NCC 滑窗 * · 粗搜在 1/2 分辨率上做(≈12M 次乘加,几十毫秒) * · 再回全分辨率在最优位置 ±3 内精修 * 返回 {x, y, score},x 就是缺口左边缘(也是要提交给服务端的坐标) */ function matchGap(bgImg, pieceImg) { const bgW = bgImg.width, bgH = bgImg.height; const bg = toGray(bgImg); const box = pieceBox(pieceImg); const pg = toGray(pieceImg); const pc = pieceImg.channels; // 模板 + 掩码(只统计有 alpha 的像素,避免拼图条透明区干扰) const tw = box.w, th = box.h; const tpl = new Float32Array(tw * th); const msk = new Uint8Array(tw * th); for (let y = 0; y < th; y++) { for (let x = 0; x < tw; x++) { const si = (y + box.y) * pieceImg.width + (x + box.x); let ok = true; if (pc === 4) ok = pieceImg.data[si * pc + 3] > 40; else if (pc === 2) ok = pieceImg.data[si * pc + 1] > 40; tpl[y * tw + x] = pg[si]; msk[y * tw + x] = ok ? 1 : 0; } } // ── 粗搜:2 倍降采样 ── const S = 2; const cw = Math.floor(bgW / S), chh = Math.floor(bgH / S); const bgS = new Float32Array(cw * chh); for (let y = 0; y < chh; y++) { for (let x = 0; x < cw; x++) { const i0 = (y * S) * bgW + x * S; bgS[y * cw + x] = (bg[i0] + bg[i0 + 1] + bg[i0 + bgW] + bg[i0 + bgW + 1]) / 4; } } const twS = Math.max(2, Math.floor(tw / S)), thS = Math.max(2, Math.floor(th / S)); const tplS = new Float32Array(twS * thS); const mskS = new Uint8Array(twS * thS); let nS = 0, sumPS = 0, sumPPS = 0; for (let y = 0; y < thS; y++) { for (let x = 0; x < twS; x++) { let sum = 0, cnt = 0, mc = 0; for (let dy = 0; dy < S; dy++) { for (let dx = 0; dx < S; dx++) { const sx = Math.min(tw - 1, x * S + dx), sy = Math.min(th - 1, y * S + dy); if (msk[sy * tw + sx]) { sum += tpl[sy * tw + sx]; cnt++; } mc++; } } const v = cnt ? sum / cnt : 0; tplS[y * twS + x] = v; mskS[y * twS + x] = cnt >= Math.ceil(mc * 0.6) ? 1 : 0; if (mskS[y * twS + x]) { nS++; sumPS += v; sumPPS += v * v; } } } let best = { score: -1, x: 0, y: 0 }; for (let y = 0; y <= chh - thS; y++) { for (let x = 0; x <= cw - twS; x++) { let sumR = 0, sumRR = 0, sumPR = 0; for (let ty = 0; ty < thS; ty++) { const bo = (y + ty) * cw + x; const to = ty * twS; for (let tx = 0; tx < twS; tx++) { if (!mskS[to + tx]) continue; const r = bgS[bo + tx]; const t = tplS[to + tx]; sumR += r; sumRR += r * r; sumPR += t * r; } } if (!nS) continue; const num = nS * sumPR - sumPS * sumR; const den = Math.sqrt((nS * sumPPS - sumPS * sumPS) * (nS * sumRR - sumR * sumR)) + 1e-6; const score = num / den; if (score > best.score) best = { score, x, y }; } } // ── 精修:全分辨率 ±3 ── let n = 0, sumP = 0, sumPP = 0; for (let i = 0; i < tw * th; i++) { if (msk[i]) { n++; sumP += tpl[i]; sumPP += tpl[i] * tpl[i]; } } const cx = best.x * S, cy = best.y * S; let fine = { score: -1, x: cx, y: cy }; for (let y = Math.max(0, cy - 3); y <= Math.min(bgH - th, cy + 3); y++) { for (let x = Math.max(0, cx - 3); x <= Math.min(bgW - tw, cx + 3); x++) { let sumR = 0, sumRR = 0, sumPR = 0; for (let ty = 0; ty < th; ty++) { const bo = (y + ty) * bgW + x; const to = ty * tw; for (let tx = 0; tx < tw; tx++) { if (!msk[to + tx]) continue; const r = bg[bo + tx]; sumR += r; sumRR += r * r; sumPR += tpl[to + tx] * r; } } if (!n) continue; const num = n * sumPR - sumP * sumR; const den = Math.sqrt((n * sumPP - sumP * sumP) * (n * sumRR - sumR * sumR)) + 1e-6; const score = num / den; if (score > fine.score) fine = { score, x, y }; } } return { x: fine.x, y: fine.y, score: fine.score, size: { w: tw, h: th }, coarse: best }; } // ============================================================================ // 六、OCR 兜底(AntiCAP /api/slider/match) // ============================================================================ function parseOcrConfig() { const raw = String(process.env[ENV_OCR] || '').trim(); if (!raw) return { base: '', token: '', user: '', pass: '' }; const parts = raw.split('|').map((x) => x.trim()); let base = parts[0] || ''; if (base && !/^https?:\/\//i.test(base)) base = 'http://' + base.replace(/^\/+/, ''); base = base.replace(/\/+$/, ''); if (parts.length >= 3) return { base, user: parts[1], pass: parts.slice(2).join('|'), token: '' }; if (parts.length === 2) return { base, token: parts[1], user: '', pass: '' }; return { base, token: '', user: '', pass: '' }; } async function fetchOcrToken(base, user, pass) { try { const body = new URLSearchParams({ username: user, password: pass, grant_type: 'password' }).toString(); const r = await request({ url: base + '/api/login', method: 'POST', data: body, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 15000, }); const d = (() => { try { return JSON.parse(r.text); } catch (e) { return null; } })(); if (d && d.access_token) return { ok: true, token: d.access_token, balance: d.balance }; return { ok: false, msg: d ? String(d.detail || d.msg || JSON.stringify(d)).slice(0, 80) : `HTTP ${r.status}` }; } catch (e) { return { ok: false, msg: e.message }; } } async function ensureOcrToken(ocr) { if (!ocr.base) return { token: '' }; if (ocr.token) return { token: ocr.token }; if (!ocr.user || !ocr.pass) return { token: '' }; let cache = {}; try { if (fs.existsSync(OCR_CACHE_NAME)) cache = JSON.parse(fs.readFileSync(OCR_CACHE_NAME, 'utf8')); } catch (e) { /* 忽略 */ } const key = ocr.base + '|' + ocr.user; const ent = cache[key]; if (ent && ent.token && Date.now() - ent.savedAt < 50 * 86400000) return { token: ent.token, cached: true }; const r = await fetchOcrToken(ocr.base, ocr.user, ocr.pass); if (r.ok) { cache[key] = { token: r.token, savedAt: Date.now() }; try { fs.writeFileSync(OCR_CACHE_NAME, JSON.stringify(cache, null, 2), 'utf8'); } catch (e) { /* 忽略 */ } return { token: r.token, fresh: true, balance: r.balance }; } return { token: '', error: r.msg }; } /** 用 OCR 服务识别缺口 x */ async function ocrGap(ocr, token, bgB64, pieceB64) { if (!ocr.base || !token) return null; try { const r = await request({ url: ocr.base + '/api/slider/match', method: 'POST', data: JSON.stringify({ target_base64: 'data:image/png;base64,' + pieceB64, background_base64: 'data:image/png;base64,' + bgB64, }), headers: { Authorization: 'Bearer ' + token }, timeout: 30000, }); const d = (() => { try { return JSON.parse(r.text); } catch (e) { return null; } })(); const t = d && d.result && d.result.target; if (Array.isArray(t) && t.length >= 1 && Number.isFinite(Number(t[0]))) { return Number(t[0]); } if (DEBUG) console.log(' [ocr] 返回异常:' + r.text.slice(0, 160)); return null; } catch (e) { if (DEBUG) console.log(' [ocr] 异常:' + e.message); return null; } } // ============================================================================ // 七、账号解析 + CK 缓存 // ============================================================================ /** ld_account: 一行一个「手机号#密码」,也支持 手机号----密码 / 手机号,密码 */ function parseAccounts(raw) { const out = []; for (const ln of String(raw || '').split(/[\n\r]+/)) { const s = ln.trim(); if (!s || s.startsWith('#')) continue; let phone = '', password = ''; if (s.includes('#')) { const i = s.indexOf('#'); phone = s.slice(0, i); password = s.slice(i + 1); } else if (s.includes('----')) { const i = s.indexOf('----'); phone = s.slice(0, i); password = s.slice(i + 4); } else if (s.includes(',')) { const i = s.indexOf(','); phone = s.slice(0, i); password = s.slice(i + 1); } else phone = s; phone = phone.replace(/[^\d]/g, ''); password = String(password).trim(); if (!phone && !password) continue; out.push({ phone, password, token: '' }); } return out; } let _cachePath = null; function resolveCachePath() { if (_cachePath) return _cachePath; const cands = []; if (process.env.LD_CACHE_DIR) cands.push(process.env.LD_CACHE_DIR); cands.push(__dirname); cands.push('/ql/data'); cands.push('/ql/scripts'); cands.push(path.join(os.tmpdir(), 'gcihotel-ck')); for (const d of cands) { try { fs.mkdirSync(d, { recursive: true }); const probe = path.join(d, '.ld_write_test'); fs.writeFileSync(probe, '1'); fs.unlinkSync(probe); _cachePath = path.join(d, CK_CACHE_NAME); return _cachePath; } catch (e) { /* 换下一个 */ } } _cachePath = path.join(__dirname, CK_CACHE_NAME); return _cachePath; } function readCache() { try { const p = resolveCachePath(); if (!fs.existsSync(p)) return {}; // 去掉 BOM:有人用记事本/PowerShell 改过缓存文件会带 BOM, // 直接 JSON.parse 会失败,表现为「缓存莫名失效、每次都重新登录」 const raw = fs.readFileSync(p, 'utf8').replace(/^\uFEFF/, ''); return JSON.parse(raw) || {}; } catch (e) { return {}; } } function writeCache(obj) { try { fs.writeFileSync(resolveCachePath(), JSON.stringify(obj, null, 2), 'utf8'); } catch (e) { /* 忽略 */ } } // ============================================================================ // 八、业务接口 // ============================================================================ /** * 密码登录 → memberToken * * ⚠️ 这里的重试是有代价的(实测踩过): * 密码连错 6 次账号会被冻结 30 分钟,返回 * {"result":304004,"msg":"您当前账号密码连续错误6次,账号已被冻结,30分钟后自动解冻"} * 密码错误是 * {"result":304005,"msg":"登录信息有误,请重新核对后再试"} * 所以「凭据类」错误一律不重试,只有网络抖动才重试, * 并且把冻结状态写进缓存,30 分钟内不再碰这个号。 * * @returns {{ok:boolean, msg?:string, fatal?:boolean, frozen?:boolean, data?:object}} */ async function loginByPassword(acc) { if (!acc.phone || !acc.password) return { ok: false, msg: '没填手机号或密码', fatal: true }; const query = { loginId: acc.phone, loginPassword: b64(acc.password), hotelGroupCode: HOTEL_GROUP_CODE, hotelGroupId: HOTEL_GROUP_ID, appid: MP_APPID, componentAppid: COMPONENT_APPID, hotelCode: HOTEL_CODE, }; let last = '未知错误'; let tryCount = 0; // 最多 2 次:第 1 次 + 网络异常时 1 次 for (let i = 0; i < 2; i++) { tryCount++; try { const r = await api(null, '/api/member/memberLogin.json', { method: 'POST', query, data: {} }); if (!r.data) { last = `响应无法解析(HTTP ${r.status})`; } else if (Number(r.data.result) === 1 && r.data.retVal) { const v = r.data.retVal; if (!v.memberToken) { last = '登录成功但没拿到 memberToken'; } else { return { ok: true, data: { token: v.memberToken, memberId: v.memberId, name: v.name || v.nickName || '会员', nickName: v.nickName || v.name || '', cardId: v.cardId || '', cardNo: v.cardNo || '', cardLevelDescript: v.cardLevelDescript || '', pointBalance: v.pointBalance, couponNum: v.couponNum, mobile: v.mobile || acc.phone, memberLevel: v.memberLevel || '', raw: v, }, }; } } else { const code = Number(r.data.result); const msg = String(r.data.msg || '').trim(); // 账号冻结:30 分钟,别再试了,越试越糟 if (code === 304004 || /冻结|锁定|封/i.test(msg)) { return { ok: false, msg: msg || '账号被冻结', fatal: true, frozen: true, code }; } // 密码/账号不对:不重试 if (code === 304005 || /登录信息有误|密码|账号不存在|未注册/i.test(msg)) { return { ok: false, msg: msg || '账号或密码错误', fatal: true, code }; } // 要求图形验证码:不重试(重试只会更糟) if (code === 304006 || /图形验证码|请输入验证码|校验码/i.test(msg)) { return { ok: false, msg: msg || '需要图形验证码', fatal: true, code }; } last = msg || `result=${code}`; } } catch (e) { last = '网络异常:' + e.message; } if (i < 1) await sleep(800 + Math.random() * 700); } return { ok: false, msg: `${last}(已尝试 ${tryCount} 次)` }; } /** 查签到记录 */ async function getRecord(acc, signCode) { const r = await api(acc, '/api/wechat/platform/sign/wechatSignRecord.json', { query: { signCode, appid: H5_APPID, componentAppid: COMPONENT_APPID, memberId: acc.memberId || '', openid: acc.openid || '', }, }); if (!r.data) return { ok: false, msg: `响应无法解析(HTTP ${r.status})`, raw: r.raw }; if (Number(r.data.result) !== 1) { return { ok: false, msg: String(r.data.msg || `result=${r.data.result}`), raw: r.raw }; } const v = r.data.retVal || {}; return { ok: true, data: v, hasSigned: String(v.hasSignedToday || '').toUpperCase() === 'T', ladderDays: Number(v.signLadderDays || 0), monthDays: Number(v.totalSignedOfMonth || 0), today: v.wechatSignRecordToday || null, awards: Array.isArray(v.awardList) ? v.awardList : [], daysList: v.signDaysList || {}, }; } /** 签到活动配置(拿 signCode / 规则,顺便判断活动有没有开) */ async function getSignConfig() { try { const r = await api(null, '/api/wechat/platform/sign/wechatSignConfig.json', { query: { appid: H5_APPID, componentAppid: COMPONENT_APPID }, }); if (r.data && Number(r.data.result) === 1 && r.data.retVal) { const v = r.data.retVal; return { ok: true, code: v.code || DEFAULT_SIGN_CODE, isHalt: String(v.isHalt || 'F'), rule: String(v.rule || '') }; } return { ok: false, msg: r.data ? r.data.msg : 'no data' }; } catch (e) { return { ok: false, msg: e.message }; } } /** 取一张滑块图 */ async function fetchCaptcha() { const data = JSON.stringify({ captchaType: 'blockPuzzle', clientUid: 'slider-' + uuid32().replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5'), ts: Date.now(), }); const r = await request({ url: `https://${HOST}/baseapi/captcha/get`, method: 'POST', data, headers: { Referer: `https://${HOST}/wechat/?/` }, }); const d = parseApi(r.text); if (!d || d.repCode !== '0000' || !d.repData) { throw new Error(`取图失败 repCode=${d && d.repCode} ${(d && d.repMsg) || ''}`); } const v = d.repData; if (!v.originalImageBase64 || !v.jigsawImageBase64) throw new Error('取图失败:图片为空'); return { bg: v.originalImageBase64, piece: v.jigsawImageBase64, token: v.token, secretKey: v.secretKey, }; } /** 提交滑块坐标,返回 {ok, repCode, repMsg} */ async function checkCaptcha(cap, x, y = 5) { const point = JSON.stringify({ x: Math.round(x), y }); const pointJson = aesEcb(point, cap.secretKey); const body = JSON.stringify({ captchaType: 'blockPuzzle', pointJson, token: cap.token }); const r = await request({ url: `https://${HOST}/baseapi/captcha/check`, method: 'POST', data: body, headers: { Referer: `https://${HOST}/wechat/?/` }, }); const d = parseApi(r.text); const ok = !!(d && d.repCode === '0000' && (!d.repData || d.repData.result !== false)); return { ok, repCode: d && d.repCode, repMsg: (d && d.repMsg) || '', pointJson }; } /** * 解一张滑块并通过服务端校验 * * 每轮都换新图,最多 5 轮。识别顺序: * · 默认 本地模板匹配 → 分数太低才叫 OCR * · ocrFirst true 时先 OCR,失败再本地(OCR 慢 3 秒,但对付花背景更稳) * * @returns {{ok:boolean, verification?:string, msg?:string, via?:string, x?:number}} */ async function solveCaptcha(ctx, acc, ocrFirst = false) { const maxTry = 5; for (let i = 1; i <= maxTry; i++) { let cap; try { cap = await fetchCaptcha(); } catch (e) { ctx.log(` 滑块取图失败(第 ${i} 次):${e.message}`); await sleep(800 * i); continue; } let x = null; let via = ''; const tryLocal = () => { try { const bgImg = decodePng(Buffer.from(cap.bg, 'base64')); const pImg = decodePng(Buffer.from(cap.piece, 'base64')); const m = matchGap(bgImg, pImg); if (DEBUG) console.log(` [local] x=${m.x} y=${m.y} score=${m.score.toFixed(3)}`); // 0.45 是实测的下限:真图通常 0.90+,认错时普遍 <0.5 if (m.score >= 0.45) { x = m.x; via = '本地匹配'; } } catch (e) { if (DEBUG) console.log(' [local] 解码失败:' + e.message); } }; const tryOcr = async () => { if (!ctx.ocrToken) return; const v = await ocrGap(ctx.ocr, ctx.ocrToken, cap.bg, cap.piece); if (v !== null) { x = v; via = 'OCR'; } }; if (ocrFirst) { await tryOcr(); if (x === null) tryLocal(); } else { tryLocal(); if (x === null) await tryOcr(); } if (x === null) { // 两种都识别不出来:蒙一个靠中间的坐标,下一轮会换图再来 x = Math.floor(rand(60, 240)); via = '随机'; } const chk = await checkCaptcha(cap, x); if (chk.ok) { // ★ captchaVerification 是前端自己算的:AES(token + "---" + {x,y}) // 服务端只负责解开核对,所以这里直接造,不需要浏览器 const verification = aesEcb(`${cap.token}---${JSON.stringify({ x: Math.round(x), y: 5 })}`, cap.secretKey); ctx.log(` ✓ 滑块通过(${via},x=${Math.round(x)})`); return { ok: true, verification, x: Math.round(x), via }; } ctx.log(` ✗ 滑块没过(${via},x=${Math.round(x)},repCode=${chk.repCode})`); await sleep(500 + Math.random() * 500); } return { ok: false, msg: `滑块连续 ${maxTry} 次未通过` }; } /** * 提交签到 * * 前端发的 body 是 Base64(JSON),服务端 JSON / Base64 两种都收(都试过)。 * 这里直接发 JSON,少一层。 * * @param {string|undefined} verification 滑块验证串;不传则整个 captcha 字段都不带 */ async function doSign(acc, signCode, verification) { // memberName 只是展示字段,但别把乱码发上去(缓存文件被别的工具改坏过的话) let memberName = acc.memberName || acc.name || ''; if (!memberName || /\uFFFD/.test(memberName) || /[\u00c0-\u00ff]{2,}/.test(memberName)) { memberName = '微信用户'; } const body = { signCode, memberId: acc.memberId, memberName, appid: H5_APPID, componentAppid: COMPONENT_APPID, hotelGroupCode: HOTEL_GROUP_CODE, memberToken: acc.token, }; // ★ openid 的坑(面板实测踩到的): // openid 唯一稳定的来源是「签到记录」里的 wechatSignRecordToday.openid, // 而这个字段【只有当天已经签过时才存在】。今天没签 → 拿不到 openid。 // 此时如果传 openid:"",服务端直接回 // {"msg":"不正常请求,参数校验不通过!","result":0} // 但【整个字段都不传】时,服务端会正常走到业务逻辑(返回「已经签到过了」)。 // 所以:拿不到就干脆不带,而不是传空串。 if (acc.openid) body.openid = acc.openid; if (verification) { body.captchaChannel = 'AJ'; body.captchaVerification = verification; } const r = await api(acc, '/api/wechat/platform/sign/wechatSign.json', { method: 'POST', data: body }); return r; } /** 积分余额 */ async function getPoints(acc) { try { const r = await api(acc, '/api/member/listPoint.json', { query: { cardId: acc.cardId || '', firstResult: 0, pageSize: 10, hotelGroupId: HOTEL_GROUP_ID, hotelGroupCode: HOTEL_GROUP_CODE, memberId: acc.memberId, }, }); if (r.data && Number(r.data.result) === 1 && r.data.retVal) { const v = r.data.retVal; return { ok: true, balance: Number(v.pointBalance), total: v.totalRows }; } return { ok: false, msg: r.data ? r.data.msg : 'no data' }; } catch (e) { return { ok: false, msg: e.message }; } } /** 领取连签奖励(7/14/21/28 天那种),返回领到的名字 */ async function claimAwards(acc, signCode, rec) { const got = []; const list = []; for (const [day, arr] of Object.entries(rec.daysList || {})) { if (!Array.isArray(arr)) continue; for (const it of arr) { if (String(it.isAward).toUpperCase() === 'T' && String(it.isReceive).toUpperCase() === 'F' && it.uuid) { list.push({ day, uuid: it.uuid, awardType: it.awardType }); } } } for (const a of list) { try { const r = await api(acc, '/api/wechat/platform/sign/getWechatSignAward.json', { query: { signCode, openid: acc.openid || '', memberId: acc.memberId, appid: H5_APPID, componentAppid: COMPONENT_APPID, hotelGroupCode: HOTEL_GROUP_CODE, awardRecordUuid: a.uuid, }, }); if (r.data && Number(r.data.result) === 1) got.push(`${a.day} 奖励`); else if (DEBUG) console.log(' [award] 领取失败:' + (r.data && r.data.msg)); } catch (e) { /* 忽略 */ } await sleep(400 + Math.random() * 400); } return got; } // ============================================================================ // 九、单账号主流程 // ============================================================================ /** * @param {object} acc {phone, password, token} * @param {number} idx 序号 * @param {object} cache CK 缓存对象 */ async function runAccount(acc, idx, cache, signCode) { const r = { index: idx, phone: acc.phone, label: maskPhone(acc.phone) || `账号${idx}`, login: null, record: null, sign: null, points: { before: null, after: null }, awards: [], error: '', logs: [], }; const log = (s) => { r.logs.push(s); console.log(s); }; // ── ① 登录 / 复用 CK ──────────────────────────────────────────────── // // token 的三个来源(优先级):环境变量 ld_ck > 本地缓存 > 密码登录 // 缓存里存了 memberId/cardId,所以「用缓存」只需要 1 个请求就能验证有效性 const mode = String(process.env[ENV_RELOGIN] || 'auto').toLowerCase(); const cached = (acc.phone && cache[acc.phone]) || null; if (!acc.token && cached && cached.token) acc.token = cached.token; if (cached) { if (!acc.memberId) acc.memberId = cached.memberId || ''; if (!acc.cardId) acc.cardId = cached.cardId || ''; if (!acc.name) acc.name = cached.name || ''; } const canLogin = !!(acc.phone && acc.password) && mode !== 'never'; const tryUseToken = async () => { if (!acc.token || !acc.memberId) return false; const rec = await getRecord(acc, signCode); if (rec.ok) { r.record = rec; return true; } if (DEBUG) console.log(` [ck] 缓存 token 不可用:${rec.msg}`); return false; }; let used = false; if (acc.token && acc.memberId && mode !== 'always') used = await tryUseToken(); if (!used) { if (!canLogin) { r.error = acc.token ? 'CK 不可用,且没有手机号+密码可以重新登录' : '没有任何凭证:既没有 ld_ck,也没有缓存,还没有手机号+密码'; log(` ❌ ${r.error}`); return r; } // 上次登录被判「账号冻结」→ 别再撞了,等它自己解冻 if (cached && cached.frozenUntil && cached.frozenUntil > Date.now()) { const mins = Math.ceil((cached.frozenUntil - Date.now()) / 60000); log(` ⏸️ 账号在冻结期(约 ${mins} 分钟后解冻),不试密码登录`); // 冻结只锁密码登录,不锁已签发的 token —— 缓存 CK 还是可以顶一下 if (cached.token && cached.memberId) { acc.token = cached.token; acc.memberId = cached.memberId; if (!acc.cardId && cached.cardId) acc.cardId = cached.cardId; const recF = await getRecord(acc, signCode); if (recF.ok) { r.record = recF; r.ckSource = '缓存 CK(冻结期兜底)'; log(' ✓ 缓存 CK 仍有效,继续签到'); } } if (!r.record) { r.error = `账号仍在冻结期(约 ${mins} 分钟后解冻),本次不登录`; log(` ❌ ${r.error}`); return r; } } if (!r.record) { log(' 🔐 正在用手机号+密码登录…'); const lg = await loginByPassword(acc); if (!lg.ok) { log(` ❌ 登录失败:${friendlyMsg(lg.msg)}`); if (lg.frozen) { cache[acc.phone] = Object.assign({}, cached || {}, { frozenUntil: Date.now() + 31 * 60 * 1000, frozenAt: Date.now(), }); writeCache(cache); log(' ⏳ 已记录冻结状态,30 分钟内不会再尝试登录这个号'); } if (/304005|登录信息有误/.test(lg.msg)) { log(' 💡 密码填错了,改对 ld_account 再跑;连错 6 次会冻结 30 分钟'); } // ── 兜底:密码登录挂了,但缓存的 memberToken 可能还是好的。 // 「账号冻结」只锁密码登录,不锁已签发的 token(实测有效), // 所以老 CK 能救回来就继续跑,别白瞎一次签到机会。 if (acc.token && acc.memberId) { log(' 🔄 试着用缓存 CK 顶一下…'); const recT = await getRecord(acc, signCode); if (recT.ok) { r.record = recT; r.ckSource = '缓存 CK(登录失败兜底)'; r.error = ''; log(' ✓ 缓存 CK 仍然有效,继续签到'); } } if (!r.record) { r.error = lg.msg; return r; } } else { const d = lg.data; acc.token = d.token; acc.memberId = d.memberId; acc.cardId = d.cardId; acc.cardNo = d.cardNo; acc.name = d.name; acc.memberName = d.name; acc.pointBalance = d.pointBalance; acc.cardLevelDescript = d.cardLevelDescript; acc.couponNum = d.couponNum; r.login = d; r.points.before = d.pointBalance; r.ckSource = '密码登录'; cache[acc.phone] = { token: d.token, memberId: d.memberId, cardId: d.cardId, cardNo: d.cardNo, name: d.name, savedAt: Date.now(), }; writeCache(cache); log(` 🔑 登录成功(${maskPhone(d.mobile)} · ${d.cardLevelDescript || '会员'})`); } } } else { r.ckSource = '缓存有效'; log(' 🔑 沿用本地缓存 CK(未重新登录)'); } if (!r.login) { // 用缓存跑起来时,补一次余额 const pt = await getPoints(acc); if (pt.ok) r.points.before = pt.balance; } // ── ② 签到状态 ────────────────────────────────────────────────────── if (!r.record) r.record = await getRecord(acc, signCode); const rec = r.record; if (!rec.ok) { r.error = rec.msg || '签到状态查询失败'; log(` ❌ 查询签到状态失败:${friendlyMsg(r.error)}`); return r; } // ── openid 的来源(这是本脚本最容易翻车的地方,务必看注释)────────────── // // 签到接口【必须】带一个真实 openid,否则服务端回 // {"msg":"不正常请求,参数校验不通过!","result":0} ← 参数校验失败 // 或者更坑的 // {"msg":"已经签到过了~","result":0} ← 骗你说签过了,其实没签 // // 而这个 openid 只能由小程序端 wx.login 拿 code 去微信换 // (/microSoftWare/getOpenidSessionKeyV2.json,code 由微信签发,脚本造不出来), // 服务端【没有】任何"按 memberId 反查 openid"的接口(bindOpenId 必须显式传 openid, // memberLoginOpen 也必须显式传 openid,都查不回来)。 // // 所以获取顺序: // ① ld_openid 环境变量(最可靠,推荐首次手动填一次) // ② 本地缓存(填过一次就一直复用,openid 是账号绑定关系,不会变) // ③ 签到记录里的 wechatSignRecordToday.openid(只有当天已签时才存在) // 拿到就写进缓存,以后不用再管。 const boundOpenid = (rec.today && rec.today.openid) || ''; acc.openid = String(process.env[ENV_OPENID] || '').trim() || (cached && cached.openid) || '' || boundOpenid || ''; if (acc.openid && cached && cached.openid !== acc.openid) { cache[acc.phone] = Object.assign({}, cached || {}, { openid: acc.openid }); writeCache(cache); } if (!acc.openid) { log(' ⚠️ 没有 openid,签到接口大概率会失败'); log(' 解决办法:把小程序抓包里 wechatSign 请求的 openid 填到 ld_openid,只填一次'); } if (rec.hasSigned) { log(` 💤 今日已签(连续 ${rec.ladderDays} 天 · 本月 ${rec.monthDays} 天)`); r.sign = { already: true, points: Number((rec.today && rec.today.points) || 0), ladderDays: rec.ladderDays, monthDays: rec.monthDays, }; } else { log(` 📅 今日未签(连续 ${rec.ladderDays} 天 · 本月 ${rec.monthDays} 天)`); // ── ③ 滑块 + 签到(多策略递增,失败自动重来)── // // 策略表(按成本从低到高): // 1~2 captcha 本地模板匹配过滑块 → 签 // 3 noverify 不带 captchaVerification 直接签 // (实测这个接口缺字段时不会报「验证码」错误, // 会往下走到业务逻辑;如果哪天平台把校验关掉, // 这条路就是零成本通道) // 4~5 captcha-ocr 先用 AntiCAP 识别,再签 const plan = ['captcha', 'captcha', 'noverify', 'captcha-ocr', 'captcha-ocr']; let signed = null; for (let i = 0; i < plan.length && !signed; i++) { const mode = plan[i]; if (i > 0) { log(` ↻ 第 ${i + 1} 次尝试(${mode === 'noverify' ? '免滑块' : mode === 'captcha-ocr' ? 'OCR 识别' : '重新识别'})…`); await sleep(1200 + Math.random() * 1500); } let verification = undefined; if (mode !== 'noverify') { const cap = await solveCaptcha( { log, ocr: ctxOcr, ocrToken: ctxOcrToken }, acc, mode === 'captcha-ocr' ); if (!cap.ok) { r.error = cap.msg; continue; } verification = cap.verification; } let res; try { res = await doSign(acc, signCode, verification); } catch (e) { r.error = '签到请求异常:' + e.message; continue; } const d = res.data; if (!d) { r.error = `签到响应无法解析(HTTP ${res.status})`; continue; } const msg = String(d.msg || ''); r.lastMsg = msg; if (Number(d.result) === 1) { const v = d.retVal || {}; // 成功返回里各版本字段名不一样,全都兜一遍 const pts = v.points !== undefined ? v.points : v.point !== undefined ? v.point : v.signPoints !== undefined ? v.signPoints : 0; signed = { ok: true, points: Number(pts) || 0, ladderDays: Number(v.signLadderDays || rec.ladderDays + 1), monthDays: v.totalSignedOfMonth !== undefined ? Number(v.totalSignedOfMonth) : rec.monthDays + 1, msg: msg || '签到成功', via: mode, }; break; } // 「已经签过了」—— 正常情况(比如两台设备同时跑), // 但★不能盲信:面板实测遇到过服务端回「已经签到过了~」而 // 签到记录里 hasSignedToday 仍是 false(请求其实没生效)。 // 所以这里回查一次记录再定,宁可多一个请求也不能误报成功。 if (/已.*签|重复|签过/i.test(msg)) { const recChk = await getRecord(acc, signCode); if (recChk.ok && recChk.hasSigned) { signed = { already: true, msg, confirmed: true }; break; } // 服务端嘴上说签过了,记录里却没有 → 当失败,换个策略重来 r.error = `服务端返回「${msg}」但签到记录仍是未签,重试`; log(` ⚠️ ${r.error}`); continue; } // 限流:等一会儿再来 if (/频繁|太快|稍后再试|人流|限流/i.test(msg)) { r.error = msg; await sleep(3000 + Math.random() * 3000); continue; } // 验证码不被认 —— 换策略 if (/验证码|滑块|验证|校验/i.test(msg)) { r.error = msg; log(` ✗ 服务端不认验证码(${msg}),换策略`); continue; } // token 掉了:重登一次再继续(但凭据类错误就赶紧停,别触发冻结) if (/登录|token|未登|失效|重新进入/i.test(msg)) { if (!acc.phone || !acc.password) { r.error = msg; break; } const lg = await loginByPassword(acc); if (lg.ok) { acc.token = lg.data.token; acc.memberId = lg.data.memberId; acc.cardId = lg.data.cardId; acc.name = lg.data.name; acc.memberName = lg.data.name; acc.pointBalance = lg.data.pointBalance; r.login = lg.data; if (r.points.before === null) r.points.before = lg.data.pointBalance; cache[acc.phone] = { token: lg.data.token, memberId: lg.data.memberId, cardId: lg.data.cardId, cardNo: lg.data.cardNo, name: lg.data.name, savedAt: Date.now(), }; writeCache(cache); log(' 🔁 CK 已失效,自动重新登录'); } else if (lg.fatal) { r.error = lg.msg; break; } r.error = msg; continue; } // 其它错误:重试无意义 r.error = msg || `result=${d.result}`; break; } if (signed && signed.already) { log(' 💤 服务端说今天已经签过了'); r.sign = { already: true, points: 0, ladderDays: rec.ladderDays, monthDays: rec.monthDays }; } else if (signed && signed.ok) { r.sign = { ok: true, points: signed.points, ladderDays: signed.ladderDays, monthDays: signed.monthDays, via: signed.via, }; log(` ✅ 签到成功 +${signed.points} 分(连续 ${signed.ladderDays} 天)`); } else { r.sign = { ok: false, msg: r.error || '未知原因' }; log(` ❌ 签到失败:${r.error || '未知原因'}`); } } // ── ④ 领连签奖励(可选)────────────────────────────────────────── const wantClaim = !/^(0|off|false|no)$/i.test(String(process.env[ENV_CLAIM] || 'on')); if (wantClaim) { try { const rec2 = await getRecord(acc, signCode); if (rec2.ok) { r.awards = await claimAwards(acc, signCode, rec2); if (r.awards.length) { log(` 🎁 领取连签奖励:${r.awards.join('、')}`); r.record = rec2; } } } catch (e) { /* 忽略 */ } } // ── ⑤ 积分余额(推送必须带)────────────────────────────────────── const pt = await getPoints(acc); if (pt.ok) { r.points.after = pt.balance; if (r.points.before === null) { // 没登录过(CK 模式)→ 用「当前余额 - 今日所得」反推 const todays = r.sign && r.sign.points ? r.sign.points : 0; r.points.before = Number((pt.balance - todays).toFixed(2)); } } else if (r.points.before !== null) { r.points.after = Number((r.points.before + ((r.sign && r.sign.points) || 0)).toFixed(2)); } // 最终刷新一次签到记录(拿到最新的连续天数 / 本月天数 / 今日实得积分) try { const rec3 = await getRecord(acc, signCode); if (rec3.ok) { r.record = rec3; // 签到成功后服务端会把 openid 回显在记录里,顺手存下来, // 这样下次(哪怕跨月、缓存被清)也不用手填 ld_openid 了 const oid = (rec3.today && rec3.today.openid) || ''; if (oid && (!cached || cached.openid !== oid)) { cache[acc.phone] = Object.assign({}, cache[acc.phone] || {}, { openid: oid }); writeCache(cache); acc.openid = oid; } if (r.sign && r.sign.ok) { r.sign.ladderDays = rec3.ladderDays; r.sign.monthDays = rec3.monthDays; // 签到接口的 retVal 有时候是空的,用签到记录里的 points 兜底 const realPts = Number((rec3.today && rec3.today.points) || 0); if (!r.sign.points && realPts) r.sign.points = realPts; } else if (r.sign && r.sign.already) { r.sign.ladderDays = rec3.ladderDays; r.sign.monthDays = rec3.monthDays; r.sign.points = Number((rec3.today && rec3.today.points) || 0); } } } catch (e) { /* 忽略 */ } return r; } // 全局 OCR 上下文(main 里初始化,runAccount 里用) let ctxOcr = { base: '', token: '', user: '', pass: '' }; let ctxOcrToken = ''; // ============================================================================ // 十、推送 // ============================================================================ /** * 名字清洗。 * 缓存文件被非 UTF-8 工具(记事本 / PowerShell 老版本)改写过的话, * 「微信用户」会变成「寰俊鐢ㄦ埛」这种乱码,直接推到手机上很难看, * 所以认不出来就退回「会员」。 */ function cleanName(name) { const s = String(name || '').trim(); if (!s) return ''; // UTF-8 被按 GBK 解释的典型特征:一堆中生僻字 + 常见「鐢ㄦ埛」组合 if (/鐢ㄦ埛|寰俊|鐢|銆|锛|鈥/.test(s)) return '会员'; if (/\uFFFD/.test(s)) return '会员'; return s; } function friendlyMsg(msg) { const m = String(msg || '').trim(); if (!m) return '未知原因'; // 顺序要紧:先认最具体的,再认泛化的 if (/冻结|锁定|封禁/.test(m)) return '账号被临时冻结(30 分钟后自动解冻,别反复登录)'; if (/验证码校验未通过|滑块|captcha/i.test(m)) return '滑块验证没通过'; if (/图形验证码|请输入验证码|图形码/i.test(m)) return '登录被要求图形验证码(隔一会儿再试)'; if (/登录信息有误|密码错误|账号或密码|用户名或密码|密码不正确/i.test(m)) return '账号或密码错误(ld_account 填错会连错冻结,改对再跑)'; if (/不存在|未注册/i.test(m)) return '这个手机号还不是会员(先去小程序注册)'; if (/已.*签|重复|签过/i.test(m)) return '今日已签'; if (/频繁|太快|稍后再试|人流|限流/i.test(m)) return '请求太频繁,被限流了'; if (/登录|token|失效|未登录|重新进入/i.test(m)) return 'CK 失效且重新登录失败'; if (/timeout|超时|ECONN|socket|net::|ENOTFOUND/i.test(m)) return '网络超时'; if (/参数|缺少/i.test(m)) return '接口参数不对(活动码可能变了)'; return m; } function tally(results) { let ok = 0, already = 0, fail = 0; for (const r of results) { if (!r.sign) { fail++; continue; } if (r.sign.ok) ok++; else if (r.sign.already) already++; else fail++; } return { ok, already, fail }; } function buildPush(results, mode = 'text') { const md = mode === 'md'; const B = (s) => (md ? `**${s}**` : String(s)); const HR = md ? '━━━━━━━━━━━━━━' : '────────────────'; const now = new Date().toLocaleString('zh-CN', { hour12: false }); const { ok, already, fail } = tally(results); const L = []; L.push(`🏨 ${B('绿地尊享会 · 每日签到')}`); L.push(''); L.push(`📅 ${now} · ${results.length} 个账号`); L.push(HR); for (const r of results) { L.push(''); L.push(`👤 ${B(r.label)}`); // 凭证 const cred = []; if (r.ckSource) cred.push(r.ckSource); if (r.login && r.login.cardLevelDescript) cred.push(r.login.cardLevelDescript); if (cred.length) L.push(`🔑 ${cred.join(' · ')}`); if (r.error && !r.sign) { L.push(`❌ ${friendlyMsg(r.error)}`); continue; } // 签到结果 const parts = []; if (!r.sign) { parts.push('⚠️ 状态未知'); } else if (r.sign.ok) { parts.push(`✅ 签到成功 +${r.sign.points} 分`); } else if (r.sign.already) { parts.push('💤 今日已签'); } else { parts.push('❌ ' + friendlyMsg(r.sign.msg || r.error)); } if (r.sign && r.sign.ladderDays !== undefined) parts.push(`🔥连签 ${r.sign.ladderDays} 天`); if (r.sign && r.sign.monthDays !== undefined) parts.push(`📆 本月 ${r.sign.monthDays} 天`); L.push(parts.join(' · ')); // 积分余额(必须) const before = r.points.before, after = r.points.after; if (after !== null && after !== undefined) { const delta = before !== null && before !== undefined ? after - before : null; const dTxt = delta === null ? '' : delta > 0 ? `(+${Number(delta.toFixed(2))})` : delta < 0 ? `(${delta})` : '(无变化)'; L.push(`💰 积分余额 ${Number(after.toFixed ? after.toFixed(2) : after)}${dTxt}`); } else if (before !== null && before !== undefined) { L.push(`💰 积分余额 ${before}`); } else { L.push('💰 积分余额 查询失败'); } if (r.awards && r.awards.length) L.push(`🎁 连签奖励已领:${r.awards.join('、')}`); if (r.login && r.login.couponNum !== undefined) L.push(`🎫 优惠券 ${r.login.couponNum} 张`); } L.push(''); L.push(HR); L.push(`📊 ✅ ${ok} 成功 · 💤 ${already} 已签 · ❌ ${fail} 失败`); L.push(''); L.push(md ? '_Mist · 仅供学习_' : 'Mist · 仅供学习'); return L.join('\n'); } function detectPushChannels() { const e = process.env; const found = []; if (e.QYWX_AM) found.push('企业微信应用'); if (e.QYWX_KEY || e.QYWX_BOT_KEY) found.push('企业微信机器人'); if (e.PUSH_PLUS_TOKEN) found.push('PushPlus'); if (e.BARK || e.BARK_PUSH) found.push('Bark'); if (e.SCKEY || e.SERVERCHAN_SENDKEY) found.push('Server酱'); if (e.DD_BOT_TOKEN) found.push('钉钉机器人'); if (e.TG_BOT_TOKEN && e.TG_CHAT_ID) found.push('Telegram'); return found; } function httpCall(url, method = 'GET', body = null, headers = {}, timeout = 20000) { return new Promise((resolve, reject) => { const u = new URL(url); const lib = u.protocol === 'https:' ? https : http; const data = body ? Buffer.from(typeof body === 'string' ? body : JSON.stringify(body), 'utf8') : null; const req = lib.request( { hostname: u.hostname, port: u.port || (u.protocol === 'https:' ? 443 : 80), path: u.pathname + u.search, method, headers: { 'User-Agent': 'Mozilla/5.0', ...(data ? { 'Content-Type': headers['Content-Type'] || 'application/json' } : {}), ...(data ? { 'Content-Length': data.length } : {}), ...headers, }, timeout, }, (res) => { const cs = []; res.on('data', (c) => cs.push(c)); res.on('end', () => resolve({ status: res.statusCode, text: Buffer.concat(cs).toString('utf8') })); } ); req.on('timeout', () => req.destroy(new Error('请求超时'))); req.on('error', reject); if (data) req.write(data); req.end(); }); } async function pushBuiltin(title, text) { const e = process.env; const done = []; const errors = []; const clip = (s, max = 2000) => { if (Buffer.byteLength(s, 'utf8') <= max) return s; let out = ''; for (const ch of s) { if (Buffer.byteLength(out + ch, 'utf8') > max - 20) break; out += ch; } return out + '\n…(内容过长已截断)'; }; if (e.QYWX_AM) { try { const [corpId, secret, touser = '@all', agentId] = String(e.QYWX_AM).split(','); if (!corpId || !secret || !agentId) throw new Error('格式应为 企业ID,应用Secret,接收人,应用AgentId'); const tk = JSON.parse((await httpCall(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${encodeURIComponent(corpId)}&corpsecret=${encodeURIComponent(secret)}`)).text); if (!tk.access_token) throw new Error('拿不到 access_token'); const r = await httpCall(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${tk.access_token}`, 'POST', { touser, msgtype: 'text', agentid: Number(String(agentId).trim()), text: { content: clip(`${title}\n\n${text}`, 2000) }, safe: 0, }); const j = JSON.parse(r.text); if (j.errcode === 0) done.push('企业微信应用'); else throw new Error(j.errmsg || '返回异常'); } catch (err) { errors.push('企业微信应用 → ' + err.message); } } const qywxKey = e.QYWX_KEY || e.QYWX_BOT_KEY; if (qywxKey) { try { const r = await httpCall(`https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${qywxKey}`, 'POST', { msgtype: 'text', text: { content: clip(`${title}\n\n${text}`, 2000) }, }); const j = JSON.parse(r.text); if (j.errcode === 0) done.push('企业微信机器人'); else throw new Error(j.errmsg || '返回异常'); } catch (err) { errors.push('企业微信机器人 → ' + err.message); } } if (e.PUSH_PLUS_TOKEN) { try { const r = await httpCall('https://www.pushplus.plus/send', 'POST', { token: e.PUSH_PLUS_TOKEN, title, content: text, template: 'txt', }); const j = JSON.parse(r.text); if (j.code === 200) done.push('PushPlus'); else throw new Error(j.msg || '返回异常'); } catch (err) { errors.push('PushPlus → ' + err.message); } } if (e.BARK || e.BARK_PUSH) { try { let base = String(e.BARK || e.BARK_PUSH); if (!/^https?:\/\//.test(base)) base = 'https://api.day.app/' + base; base = base.replace(/\/+$/, ''); const short = text.split('\n').filter((x) => x.trim()).slice(0, 10).join(' ').slice(0, 600); const r = await httpCall(`${base}/${encodeURIComponent(title)}/${encodeURIComponent(short)}?group=${encodeURIComponent('绿地尊享签到')}`); if (r.status === 200) done.push('Bark'); else throw new Error(`服务器返回 ${r.status}`); } catch (err) { errors.push('Bark → ' + err.message); } } const sckey = e.SCKEY || e.SERVERCHAN_SENDKEY; if (sckey) { try { const host = /^sct/i.test(sckey) ? 'sctapi.ftqq.com' : 'sc.ftqq.com'; const r = await httpCall(`https://${host}/${sckey}.send`, 'POST', new URLSearchParams({ title, desp: text }).toString(), { 'Content-Type': 'application/x-www-form-urlencoded' }); const j = JSON.parse(r.text); if (j.code === 0 || j.data) done.push('Server酱'); else throw new Error(j.message || '返回异常'); } catch (err) { errors.push('Server酱 → ' + err.message); } } if (e.DD_BOT_TOKEN) { try { let url = `https://oapi.dingtalk.com/robot/send?access_token=${e.DD_BOT_TOKEN}`; if (e.DD_BOT_SECRET) { const ts = Date.now(); const sign = crypto.createHmac('sha256', e.DD_BOT_SECRET).update(`${ts}\n${e.DD_BOT_SECRET}`).digest('base64'); url += `×tamp=${ts}&sign=${encodeURIComponent(sign)}`; } const r = await httpCall(url, 'POST', { msgtype: 'text', text: { content: `${title}\n\n${clip(text, 1800)}` } }); const j = JSON.parse(r.text); if (j.errcode === 0) done.push('钉钉机器人'); else throw new Error(j.errmsg || '返回异常'); } catch (err) { errors.push('钉钉机器人 → ' + err.message); } } if (e.TG_BOT_TOKEN && e.TG_CHAT_ID) { try { const api = e.TG_API_URL ? e.TG_API_URL.replace(/\/+$/, '') : 'https://api.telegram.org'; const r = await httpCall(`${api}/bot${e.TG_BOT_TOKEN}/sendMessage`, 'POST', { chat_id: e.TG_CHAT_ID, text: `${title}\n\n${clip(text, 3500)}`, disable_web_page_preview: true, }); const j = JSON.parse(r.text); if (j.ok) done.push('Telegram'); else throw new Error(j.description || '返回异常'); } catch (err) { errors.push('Telegram → ' + err.message); } } return { done, errors }; } async function push(results) { const want = String(process.env[ENV_PUSH] || 'auto').toLowerCase(); if (['off', '0', 'none'].includes(want)) { console.log(' ⏭️ 已关闭推送'); return; } const title = '绿地尊享会签到'; const wantMd = /^(on|1|true|md|markdown)$/i.test(String(process.env[ENV_PUSH_MD] || '')); const body = buildPush(results, wantMd ? 'md' : 'text'); const channels = detectPushChannels(); if (channels.length) console.log(` 📨 检测到推送渠道:${channels.join('、')}`); if (channels.length) { console.log(` 📨 正在推送(${wantMd ? 'markdown' : '文本'})…`); const { done, errors } = await pushBuiltin(title, body); if (done.length) { console.log(` ✅ 推送成功:${done.join('、')}`); return; } if (errors.length) { console.log(' ⚠️ 内置推送没成功:'); for (const e of errors) console.log(` · ${e}`); console.log(' ↪ 再试试青龙自带的推送…'); } } let hasNotifyModule = false; let notifyErr = ''; try { const notify = require('./sendNotify'); hasNotifyModule = true; if (typeof notify.sendNotify === 'function') { await notify.sendNotify(title, body); console.log(' ✅ 已交给青龙推送'); return; } if (typeof notify === 'function') { await notify(title, body); console.log(' ✅ 已交给青龙推送'); return; } notifyErr = '模块没有导出 sendNotify 函数'; } catch (e) { hasNotifyModule = false; notifyErr = e.message; } if (!channels.length && !hasNotifyModule) { console.log(' ❌ 没有任何可用推送渠道'); if (notifyErr) console.log(` (sendNotify 也没加载上:${notifyErr})`); console.log(' 在青龙里配一个,支持这些变量:'); console.log(' QYWX_AM 企业微信应用(企业ID,Secret,接收人,应用ID)'); console.log(' QYWX_KEY 企业微信机器人 Webhook Key'); console.log(' PUSH_PLUS_TOKEN PushPlus'); console.log(' BARK Bark(填 key 或完整地址)'); console.log(' SCKEY Server酱'); console.log(' DD_BOT_TOKEN 钉钉机器人(配合 DD_BOT_SECRET)'); console.log(' TG_BOT_TOKEN 配合 TG_CHAT_ID'); } } // ============================================================================ // 十一、主流程 // ============================================================================ function printHelp() { boxTitle('❌ 还没配置账号'); console.log(''); console.log(' 青龙 → 环境变量 → 新建:'); console.log(''); console.log(' 【必需】'); console.log(' ld_account = 手机号#密码'); console.log(' (多账号换行)'); console.log(''); console.log(' 【可选】'); console.log(' ld_ck = 已有的 memberToken(一行一个,不填就密码登录)'); console.log(' ld_ocr = http://IP:6688|账号|密码 滑块识别兜底(AntiCAP)'); console.log(' ld_relogin = auto / always / never 默认 auto'); console.log(' ld_delay = 5-10 多账号间隔秒'); console.log(' ld_claim = on/off 连签奖励自动领,默认 on'); console.log(' ld_signcode = LDJFQD 签到活动码,一般不用改'); console.log(' TYpush = off 关闭推送'); console.log(''); console.log(' 用法:node lvdi_zunxiang_signin.js 正常签到'); console.log(' node lvdi_zunxiang_signin.js --dry 只登录查状态,不签到'); console.log(' node lvdi_zunxiang_signin.js --captcha 只测滑块识别(10 次)'); console.log(' node lvdi_zunxiang_signin.js --points 只查积分余额'); console.log(''); } /** 滑块自检:连打 10 张图看通过率 */ async function captchaSelfTest(rounds = 10) { boxTitle('🧩 滑块识别自检'); console.log(''); ctxOcr = parseOcrConfig(); if (ctxOcr.base) { const t = await ensureOcrToken(ctxOcr); if (t.token) { ctxOcrToken = t.token; console.log(` 🔑 OCR 就绪(${ctxOcr.user || 'token'})`); } else { console.log(` ⚠️ OCR 不可用:${t.error || '未知'}`); } } console.log(''); let ok = 0, ocrUsed = 0; const t0 = Date.now(); for (let i = 1; i <= rounds; i++) { const cap = await fetchCaptcha(); const bg = decodePng(Buffer.from(cap.bg, 'base64')); const pg = decodePng(Buffer.from(cap.piece, 'base64')); const m = matchGap(bg, pg); let x = m.x, via = '本地'; if (m.score < 0.45 && ctxOcrToken) { const v = await ocrGap(ctxOcr, ctxOcrToken, cap.bg, cap.piece); if (v !== null) { x = v; via = 'OCR'; ocrUsed++; } } const chk = await checkCaptcha(cap, x); if (chk.ok) ok++; console.log(` #${String(i).padStart(2)} x=${String(x).padStart(3)} score=${m.score.toFixed(3)} ${padR(via, 4)} → ${chk.ok ? '✅' : '❌ ' + chk.repCode}`); await sleep(500); } console.log(''); console.log(` 通过率 ${ok}/${rounds}(OCR 兜底 ${ocrUsed} 次)· 用时 ${((Date.now() - t0) / 1000).toFixed(1)}s`); console.log(''); if (ok === rounds) console.log(' ✅ 识别链路正常,签到不会卡在滑块这一步'); else if (ok >= rounds * 0.8) console.log(' 🟡 大部分能过,脚本里有 5 次重试,实际够用'); else console.log(' ❌ 通过率偏低,建议配上 ld_ocr(AntiCAP)做兜底'); console.log(''); } async function main() { const argv = process.argv.slice(2); const dryRun = argv.includes('--dry'); const pointsOnly = argv.includes('--points'); // 滑块自检模式:没配账号也能跑,用来验证识别链路 if (argv.includes('--captcha')) { await captchaSelfTest(10); return; } const rawAcc = String(process.env[ENV_ACCOUNT] || '').trim(); const rawCk = String(process.env[ENV_CK] || '').trim(); const accounts = parseAccounts(rawAcc); // CK 模式:ld_ck 一行一个 token,按顺序对应账号;没有账号时用占位账号 if (rawCk) { const lines = rawCk.split(/[\n\r]+/).map((s) => s.trim()).filter(Boolean); if (accounts.length) { lines.forEach((tk, i) => { if (accounts[i] && !accounts[i].token) accounts[i].token = tk; }); } else { lines.forEach((tk, i) => accounts.push({ phone: '', password: '', token: tk, label: `CK${i + 1}` })); } } if (!accounts.length) { printHelp(); return; } const signCodeCfg = await getSignConfig(); const signCode = String(process.env[ENV_SIGNCODE] || (signCodeCfg.ok && signCodeCfg.code) || DEFAULT_SIGN_CODE).trim(); console.log(''); console.log(`🏨 绿地尊享会 · 每日签到 · ${accounts.length} 个账号${dryRun ? '(演练模式)' : ''}`); if (signCodeCfg.ok) { const rule = signCodeCfg.rule.replace(/<[^>]+>/g, '').replace(/ /g, ' ').replace(/\s+/g, ' ').trim(); console.log(` 活动 ${signCode}${rule ? ' · ' + rule.slice(0, 46) : ''}`); } else { console.log(` 活动 ${signCode}(配置接口没返回,直接用默认码)`); } console.log(''); // OCR(可选) ctxOcr = parseOcrConfig(); if (ctxOcr.base) { const t = await ensureOcrToken(ctxOcr); if (t.token) { ctxOcrToken = t.token; console.log(` 🔑 滑块 OCR 就绪(${ctxOcr.user || 'token'}${t.balance !== undefined ? ' · 余额 ' + t.balance : ''})`); } else { console.log(` ⚠️ OCR 连不上(${t.error || '未知'}),只用本地识别`); } console.log(''); } const mode = String(process.env[ENV_RELOGIN] || 'auto').toLowerCase(); const delayRaw = String(process.env[ENV_DELAY] || '5-10'); const dm = delayRaw.match(/^(\d+)\s*-\s*(\d+)$/); const dMin = dm ? Number(dm[1]) : Number(delayRaw) || 5; const dMax = dm ? Number(dm[2]) : dMin + 5; console.log(' ' + [ ctxOcrToken ? 'OCR 兜底 已启用' : 'OCR 仅本地匹配', mode === 'always' ? '每次重新登录' : mode === 'never' ? '只用缓存 CK' : '失效才登录', `间隔 ${dMin}-${dMax} 秒`, ].join(' · ')); console.log(''); const cache = readCache(); const results = []; for (let i = 0; i < accounts.length; i++) { const acc = accounts[i]; section(`账号 ${i + 1}/${accounts.length} ${maskPhone(acc.phone) || 'CK 账号'}`); try { if (pointsOnly) { results.push(await pointsOnlyAccount(acc, i + 1, cache, signCode)); } else if (dryRun) { const r = await dryRunAccount(acc, i + 1, cache, signCode); results.push(r); } else { results.push(await runAccount(acc, i + 1, cache, signCode)); } } catch (e) { console.log(' ❌ 运行异常:' + e.message); results.push({ index: i + 1, label: maskPhone(acc.phone) || 'CK 账号', sign: null, error: e.message, points: {}, }); } if (i < accounts.length - 1) { const wait = Math.round(rand(dMin, dMax)); console.log(` ⏳ ${wait} 秒后处理下一个账号…`); await sleep(wait * 1000); } } // ── 汇总 ── // 提前失败(登录失败/查不到状态)的账号没有 sign 字段,这里补一个, // 否则汇总会显示成「未知」,看不出到底是哪一步挂了 for (const r of results) { if (!r.sign) r.sign = { ok: false, msg: r.error || '未知原因' }; if (!r.points) r.points = {}; } const { ok, already, fail } = tally(results); console.log(''); console.log(line(58)); console.log(`📊 ✅ ${ok} 成功 · 💤 ${already} 已签 · ❌ ${fail} 失败`); // 余额小表(青龙日志里一眼能看到) for (const r of results) { const bal = r.points.after !== null && r.points.after !== undefined ? r.points.after : r.points.before !== null && r.points.before !== undefined ? r.points.before : null; const t = r.sign.ok ? `+${r.sign.points}分` : r.sign.already ? '已签' : '失败'; console.log(` ${padR(r.label, 14)} ${padR(t, 8)} 余额 ${bal === null ? '—' : bal}`); if (!r.sign.ok && !r.sign.already) { console.log(` ${' '.repeat(14)} ${friendlyMsg(r.sign.msg || r.error)}`); } } if (!dryRun && !pointsOnly) await push(results); } /** * 拿一个可用会话:优先缓存 token(不消耗登录次数、不受冻结影响), * 缓存不可用才走密码登录。 * @returns {{ok:boolean, msg?:string, via?:string, record?:object}} */ async function resolveSession(acc, cache, signCode) { const key = acc.phone || ('ck:' + (acc.token || '').slice(0, 12)); const cached = acc.phone ? cache[acc.phone] : null; // ① 环境变量 / 参数里显式给的 token if (acc.token && acc.memberId) { const rec = await getRecord(acc, signCode); if (rec.ok) return { ok: true, via: 'ld_ck', record: rec }; } // ② 缓存里的 token if (cached && cached.token && cached.memberId) { const saveToken = acc.token; acc.token = cached.token; acc.memberId = cached.memberId; if (!acc.cardId && cached.cardId) acc.cardId = cached.cardId; if (!acc.name && cached.name) acc.name = cached.name; if (!acc.memberName && cached.name) acc.memberName = cached.name; const rec = await getRecord(acc, signCode); if (rec.ok) return { ok: true, via: '缓存 CK', record: rec }; acc.token = saveToken; } // ③ 密码登录 if (!acc.phone || !acc.password) { return { ok: false, msg: '没有可用的 CK,也没有手机号+密码' }; } if (cached && cached.frozenUntil && cached.frozenUntil > Date.now()) { const mins = Math.ceil((cached.frozenUntil - Date.now()) / 60000); return { ok: false, msg: `账号在冻结期(约 ${mins} 分钟后解冻)` }; } const lg = await loginByPassword(acc); if (!lg.ok) return { ok: false, msg: lg.msg }; const d = lg.data; acc.token = d.token; acc.memberId = d.memberId; acc.cardId = d.cardId; acc.name = d.name; acc.memberName = d.name; acc.pointBalance = d.pointBalance; acc.cardLevelDescript = d.cardLevelDescript; acc.couponNum = d.couponNum; cache[acc.phone] = { token: d.token, memberId: d.memberId, cardId: d.cardId, cardNo: d.cardNo, name: d.name, savedAt: Date.now(), }; writeCache(cache); const rec = await getRecord(acc, signCode); return { ok: true, via: '密码登录', login: d, record: rec.ok ? rec : null }; } /** --points:只查余额(推送给青龙当监控用) */ async function pointsOnlyAccount(acc, idx, cache, signCode) { const r = { index: idx, label: maskPhone(acc.phone), sign: null, points: {}, logs: [] }; const s = await resolveSession(acc, cache, signCode); if (!s.ok) { r.error = s.msg; r.sign = { ok: false, msg: s.msg }; console.log(' ❌ ' + friendlyMsg(s.msg)); return r; } r.login = s.login || null; r.ckSource = s.via; console.log(` 🔑 ${s.via}`); const pt = await getPoints(acc); r.points.after = pt.ok ? pt.balance : (s.login ? s.login.pointBalance : null); r.points.before = r.points.after; const rec = s.record || await getRecord(acc, signCode); r.sign = { already: rec && rec.ok ? rec.hasSigned : false, ok: false, ladderDays: rec && rec.ok ? rec.ladderDays : 0, monthDays: rec && rec.ok ? rec.monthDays : 0, points: 0, }; const lv = (s.login && s.login.cardLevelDescript) || acc.cardLevelDescript || ''; const who = cleanName(acc.name) || '会员'; const tail = lv && lv !== who ? ` · ${lv}` : ''; console.log(` 💰 ${who}${tail} · 积分 ${r.points.after === null ? '—' : r.points.after}` + ` · 今日${r.sign.already ? '已签' : '未签'} · 连签 ${r.sign.ladderDays} 天`); return r; } /** 演练:只登录 + 查状态,不签 */ async function dryRunAccount(acc, idx, cache, signCode) { const r = { index: idx, label: maskPhone(acc.phone), sign: null, points: {}, logs: [] }; const s = await resolveSession(acc, cache, signCode); if (!s.ok) { r.error = s.msg; r.sign = { ok: false, msg: s.msg }; console.log(' ❌ ' + friendlyMsg(s.msg)); return r; } r.login = s.login || null; r.ckSource = s.via; console.log(` 🔑 ${s.via}${s.login ? `:${s.login.name} · ${s.login.cardLevelDescript}` : ''}`); const rec = s.record || await getRecord(acc, signCode); if (!rec || !rec.ok) { r.error = (rec && rec.msg) || '查询失败'; r.sign = { ok: false, msg: r.error }; console.log(' ❌ 查询失败:' + friendlyMsg(r.error)); return r; } console.log(` 📅 今日${rec.hasSigned ? '已签' : '未签'} · 连签 ${rec.ladderDays} 天 · 本月 ${rec.monthDays} 天`); r.sign = { already: rec.hasSigned, ok: false, ladderDays: rec.ladderDays, monthDays: rec.monthDays, points: 0 }; const pt = await getPoints(acc); r.points.after = pt.ok ? pt.balance : (s.login ? s.login.pointBalance : null); r.points.before = r.points.after; console.log(` 💰 积分余额 ${r.points.after === null ? '查询失败' : r.points.after}`); return r; } if (require.main === module) { main().catch((e) => { console.error('❌ 脚本异常退出:' + (e && e.stack ? e.stack : e)); process.exitCode = 1; }); } module.exports = { parseAccounts, parseApi, b64, aesEcb, aesEcbDecrypt, decodePng, matchGap, pieceBox, loginByPassword, getRecord, getSignConfig, fetchCaptcha, checkCaptcha, solveCaptcha, doSign, getPoints, buildPush, resolveSession, claimAwards, friendlyMsg, cleanName, };