fix: 公众号保活续期与可观测 (v2.2.1)

- 保活追加带 token 的 /cgi-bin/home 续期请求(we-mp-rss/hive-mp 同源做法)
- 服务端未续期时本地延长临期会话 Cookie 到 7 天(仅在线验证通过后)
- 新增保活运行记录 + 在线页显示会话有效期/上次保活时间/运行记录
- 桥接新增 mpState / mpKeepAlive 方法
- 修复保活锁与 syncing 状态崩溃残留导致保活永久卡死
This commit is contained in:
3970260761 committed 2026-11-10 22:37:50 +08:00
1 parent 35284395b3
commit 8c2ce3dcb9
6 files changed
+267 -13

No files matched your search

+19
View File
@@ -129,6 +129,25 @@ export function parseMpAuth(html: string): MpAuthInfo | null {
}
}
/** 公众号会话关键 Cookie(按重要性排序,与社区保活工具 hive-mp 同源的取法) */
export const MP_SESSION_COOKIE_NAMES = ['slave_sid', 'slave_user', 'bizuin', 'uin', 'pass_ticket'] as const
/**
* 取公众号会话的过期时间(秒级时间戳,与 chrome.cookies.expirationDate 同单位)。
* 会话是否即将到期只看这些关键 Cookie,统计类 Cookie 不参与。
*/
export function mpSessionExpiry(
cookies: Array<{ name: string; expirationDate?: number }>,
): number | null {
for (const name of MP_SESSION_COOKIE_NAMES) {
const c = cookies.find((x) => x.name === name)
if (c && typeof c.expirationDate === 'number' && c.expirationDate > 0) {
return c.expirationDate
}
}
return null
}
/**
* 按 Cookie 规范拼装 Cookie 请求头
* 只包含对目标 URL 生效(domain/path 匹配)的 Cookie
+1 -1
View File
@@ -2,7 +2,7 @@
"manifest_version": 3,
"name": "文章同步助手",
"description": "一键同步文章到知乎、头条、掘金等 20+ 平台,支持公众号多账号保持在线",
"version": "2.2.0",
"version": "2.2.1",
"icons": {
"16": "assets/icon-16.png",
"48": "assets/icon-48.png",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@wechatsync/extension",
"version": "2.2.0",
"version": "2.2.1",
"private": true,
"description": "微信公众号同步助手 Chrome 扩展",
"type": "module",
+183 -8
View File
@@ -15,6 +15,8 @@ import {
MP_TARGET_KEY,
MP_DEFAULT_INTERVAL,
MP_HOME_URL,
mpSessionExpiry,
MP_SESSION_COOKIE_NAMES,
parseMpAuth,
readMpCookies,
withMpAccountCookies,
@@ -43,6 +45,41 @@ const MIN_RUN_INTERVAL = 30 * 1000
const REQUEST_GAP = 400
/** 连续失败多少次判定为离线 */
const OFFLINE_AFTER_FAILS = 3
/** 保活运行记录(storage.local,供界面与远程诊断查看) */
const MP_RUN_HISTORY_KEY = 'mpKeepAliveHistory'
const MAX_RUN_HISTORY = 40
/** 会话 Cookie 剩余有效期不足该秒数时触发本地延长(48 小时) */
const EXTEND_THRESHOLD_SEC = 48 * 3600
/** 本地延长后的目标有效期(7 天) */
const EXTEND_TO_SEC = 7 * 24 * 3600
/** 同步状态超过该毫秒数仍为 syncing 视为崩溃残留,不再阻止保活 */
const SYNC_STALE_MS = 10 * 60 * 1000
/** 保活锁超过该毫秒数视为残留锁(崩溃恢复) */
const LOCK_STALE_MS = 5 * 60 * 1000
/** 单次保活运行记录 */
export interface MpRunRecord {
at: number
id: string
status: 'online' | 'expired' | 'offline' | 'error' | 'skipped'
note?: string
/** 保活前的会话过期时间(秒级时间戳) */
expiryBefore?: number | null
/** 保活后的会话过期时间(秒级时间戳) */
expiryAfter?: number | null
}
async function recordRun(rec: Omit<MpRunRecord, 'at'> & { at?: number }): Promise<void> {
try {
const { at, ...rest } = rec
const stored = await chrome.storage.local.get(MP_RUN_HISTORY_KEY)
const list = (stored[MP_RUN_HISTORY_KEY] as MpRunRecord[] | undefined) || []
list.unshift({ ...rest, at: at ?? Date.now() })
await chrome.storage.local.set({ [MP_RUN_HISTORY_KEY]: list.slice(0, MAX_RUN_HISTORY) })
} catch (error) {
logger.warn('写入保活记录失败:', error)
}
}
/** 返回给 popup 的账号摘要(不带 Cookie,体积小) */
export interface MpAccountSummary {
@@ -58,6 +95,8 @@ export interface MpAccountSummary {
lastOnlineAt?: number
failCount: number
note?: string
/** 会话过期时间(秒级时间戳) */
sessionExpiry?: number | null
cookieCount: number
createdAt: number
}
@@ -75,7 +114,8 @@ function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function summarize(account: MpAccount): MpAccountSummary {
function summarize(account: MpAccount, jar?: MpCookie[]): MpAccountSummary {
const live = account.isCurrent && jar ? jar : account.cookies
return {
id: account.id,
userName: account.userName,
@@ -89,6 +129,7 @@ function summarize(account: MpAccount): MpAccountSummary {
lastOnlineAt: account.lastOnlineAt,
failCount: account.failCount,
note: account.note,
sessionExpiry: mpSessionExpiry(live),
cookieCount: account.cookies?.length || 0,
createdAt: account.createdAt,
}
@@ -111,14 +152,21 @@ export async function getMpState(): Promise<{
accounts: MpAccountSummary[]
targetId: string
alarmPeriodMinutes: number | null
lastRunAt: number | null
history: MpRunRecord[]
}> {
const list = await loadAccounts()
const stored = await chrome.storage.local.get(MP_TARGET_KEY)
const stored = await chrome.storage.local.get([MP_TARGET_KEY, MP_RUN_HISTORY_KEY])
const session = await chrome.storage.session.get([MP_LAST_RUN_KEY])
const alarms = await chrome.alarms.get(MP_KEEPALIVE_ALARM)
const jar = await readMpCookies(runtime)
const history = (stored[MP_RUN_HISTORY_KEY] as MpRunRecord[] | undefined) || []
return {
accounts: list.map(summarize),
accounts: list.map((a) => summarize(a, jar)),
targetId: (stored[MP_TARGET_KEY] as string) || 'current',
alarmPeriodMinutes: alarms?.periodInMinutes ?? null,
lastRunAt: (session[MP_LAST_RUN_KEY] as number | undefined) ?? null,
history: history.slice(0, 12),
}
}
@@ -317,6 +365,7 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
const now = Date.now()
const isCurrent = jar.length > 0 && isAccountCurrentSession(account, jar)
if (account.isCurrent !== isCurrent) account.isCurrent = isCurrent
const expiryBefore = mpSessionExpiry(isCurrent ? jar : account.cookies)
try {
let html: string
@@ -349,6 +398,7 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
account.failCount += 1
account.note = '登录态已过期,需要重新扫码登录'
logger.warn(`[${account.nickName || account.userName}] 登录态已过期`)
await recordRun({ id: account.id, status: 'expired', note: account.note, expiryBefore })
return
}
if (account.userName && auth.userName && auth.userName !== account.userName) {
@@ -356,9 +406,49 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
account.failCount += 1
account.note = `返回了其他账号(${auth.nickName || auth.userName}),登录态异常`
logger.warn(`[${account.nickName}] ${account.note}`)
await recordRun({ id: account.id, status: 'expired', note: account.note, expiryBefore })
return
}
// ★ 续期请求:带 token 访问后台首页(社区验证的会话活跃端点,we-mp-rss / hive-mp 同源做法)。
// 根路径只做在线判定,这个请求让服务端会话持续活跃。
let renewNote: string | undefined
try {
const renewUrl = `https://mp.weixin.qq.com/cgi-bin/home?token=${encodeURIComponent(auth.token)}&lang=zh_CN`
const fetchRenewAuth = async (): Promise<ReturnType<typeof parseMpAuth>> => {
const res = await runtime.fetch(renewUrl, { method: 'GET' })
return parseMpAuth(await res.text())
}
const renewAuth = isCurrent
? await fetchRenewAuth()
: await withMpAccountCookies(runtime, account.cookies, fetchRenewAuth, {
onCookiesRefreshed: (cookies) => {
account.cookies = cookies
},
})
if (
renewAuth &&
account.userName &&
renewAuth.userName &&
renewAuth.userName !== account.userName
) {
account.status = 'expired'
account.failCount += 1
account.note = `续期请求返回了其他账号(${renewAuth.nickName || renewAuth.userName}),登录态异常`
logger.warn(`[${account.nickName}] ${account.note}`)
await recordRun({ id: account.id, status: 'expired', note: account.note, expiryBefore })
return
}
if (renewAuth) {
account.token = renewAuth.token
account.ticket = renewAuth.ticket || account.ticket
account.svrTime = renewAuth.svrTime
}
} catch (renewError) {
renewNote = `续期请求失败: ${(renewError as Error).message}`
logger.warn(renewNote)
}
account.status = 'online'
account.failCount = 0
account.note = undefined
@@ -369,7 +459,30 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
account.svrTime = auth.svrTime
account.nickName = auth.nickName || account.nickName
account.avatar = auth.avatar || account.avatar
logger.info(`[${account.nickName || account.userName}] 保活成功`)
// ★ 读取续期后的会话过期时间;服务端没续就本地延长临期 Cookie(仅当前登录账号的实时 Cookie 可改)
const afterJar = isCurrent ? await readMpCookies(runtime) : account.cookies
let expiryAfter = mpSessionExpiry(afterJar)
const extended = await extendCurrentMpSessionCookies(account, isCurrent, expiryAfter)
if (extended) {
expiryAfter = extended
renewNote = renewNote
? `${renewNote};已本地延长会话有效期`
: '服务端未延长,已本地延长会话有效期'
}
logger.info(
`[${account.nickName || account.userName}] 保活成功` +
(renewNote ? `(${renewNote})` : '') +
(expiryAfter ? `,会话有效期至 ${new Date(expiryAfter * 1000).toLocaleString()}` : ''),
)
await recordRun({
id: account.id,
status: 'online',
note: renewNote,
expiryBefore,
expiryAfter,
})
} catch (error) {
account.failCount += 1
account.lastCheckAt = now
@@ -378,9 +491,66 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
account.status = 'offline'
}
logger.warn(`[${account.nickName || account.userName}] 保活失败:`, error)
await recordRun({
id: account.id,
status: account.failCount >= OFFLINE_AFTER_FAILS ? 'offline' : 'error',
note: account.note,
expiryBefore,
})
}
}
/**
* 本地兜底续期:服务端没有通过 Set-Cookie 延长有效期时,把 48 小时内到期的
* 会话 Cookie(slave_sid 等)直接改写为 7 天后。只在本次在线验证通过后调用,
* 且只处理浏览器当前登录账号的实时 Cookie(其他账号走快照注入,客户端有效期不参与请求)。
*
* @returns 成功延长后的最新过期时间(秒),未延长返回 null
*/
async function extendCurrentMpSessionCookies(
account: MpAccount,
isCurrent: boolean,
expirySec: number | null,
): Promise<number | null> {
if (!isCurrent) return null
if (!expirySec) return null
if (!account.status || account.status !== 'online') return null
const remaining = expirySec - Date.now() / 1000
if (remaining > EXTEND_THRESHOLD_SEC) return null
try {
const list = await chrome.cookies.getAll({ domain: 'mp.weixin.qq.com' })
const target = Math.floor(Date.now() / 1000) + EXTEND_TO_SEC
let touched = false
for (const c of list) {
if (!(MP_SESSION_COOKIE_NAMES as readonly string[]).includes(c.name)) continue
if (!c.expirationDate || c.expirationDate - Date.now() / 1000 > EXTEND_THRESHOLD_SEC) continue
const set = await chrome.cookies.set({
url: `https://mp.weixin.qq.com${c.path || '/'}`,
name: c.name,
value: c.value,
path: c.path || '/',
secure: c.secure,
httpOnly: c.httpOnly,
sameSite: c.sameSite,
expirationDate: target,
storeId: c.storeId,
...(c.hostOnly ? {} : { domain: c.domain }),
})
if (set) touched = true
}
if (!touched) return null
const fresh = await chrome.cookies.getAll({ domain: 'mp.weixin.qq.com' })
const actual = mpSessionExpiry(fresh)
if (actual && actual > expirySec) {
logger.info(`会话 Cookie 有效期已本地延长至 ${new Date(actual * 1000).toLocaleString()}`)
return actual
}
} catch (error) {
logger.warn('本地延长会话有效期失败:', error)
}
return null
}
/**
* 对所有启用的账号执行一次保活
* @param force 忽略节流与"同步进行中"保护
@@ -389,20 +559,25 @@ export async function keepAliveMpAccounts(force = false): Promise<MpKeepAliveRes
const lock = await chrome.storage.session.get([MP_LOCK_KEY, MP_LAST_RUN_KEY])
const now = Date.now()
if (!force) {
if (lock[MP_LOCK_KEY]) {
const lockedAt = typeof lock[MP_LOCK_KEY] === 'number' ? (lock[MP_LOCK_KEY] as number) : null
if (lockedAt && now - lockedAt < LOCK_STALE_MS) {
return { total: 0, online: 0, expired: 0, offline: 0, skipped: true, message: '保活任务进行中' }
}
if (lock[MP_LAST_RUN_KEY] && now - (lock[MP_LAST_RUN_KEY] as number) < MIN_RUN_INTERVAL) {
return { total: 0, online: 0, expired: 0, offline: 0, skipped: true, message: '刚保活过,跳过' }
}
// 同步进行中跳过(避免与发布请求的 Cookie 注入规则互相干扰)
// 同步进行中跳过(避免与发布请求的 Cookie 注入规则互相干扰);
// 超过 SYNC_STALE_MS 仍为 syncing 视为崩溃残留,不再阻止保活
const sync = await chrome.storage.local.get('activeSyncState')
if (sync.activeSyncState?.status === 'syncing') {
const syncState = sync.activeSyncState as { status?: string; startTime?: number } | undefined
if (syncState?.status === 'syncing' && now - (syncState.startTime || 0) < SYNC_STALE_MS) {
await recordRun({ id: '*', status: 'skipped', note: '正在同步,稍后重试' })
return { total: 0, online: 0, expired: 0, offline: 0, skipped: true, message: '正在同步,稍后重试' }
}
}
await chrome.storage.session.set({ [MP_LOCK_KEY]: true })
// 锁值带时间戳:崩溃残留的旧锁超过 LOCK_STALE_MS 会被忽略,不会永久卡死保活
await chrome.storage.session.set({ [MP_LOCK_KEY]: now })
try {
const list = await refreshMpCurrentFlags()
const targets = list.filter((a) => a.enabled)
+11
View File
@@ -9,6 +9,7 @@ import {
import { markdownToHtml } from '@wechatsync/core'
import { createLogger } from '../lib/logger'
import { performSync } from '../background/sync-service'
import { getMpState, keepAliveMpAccounts } from '../lib/mp-keepalive'
const logger = createLogger('MCPClient')
@@ -505,6 +506,16 @@ class McpClient {
return await this.performImageUpload(imageData, upload.mimeType, upload.platform)
}
case 'mpState': {
// 公众号保活状态 + 运行记录(供 MCP / 远程诊断读取)
return await getMpState()
}
case 'mpKeepAlive': {
// 立即执行一轮公众号保活
return await keepAliveMpAccounts(true)
}
default:
throw new Error(`Unknown method: ${method}`)
}
@@ -18,24 +18,38 @@ const logger = createLogger('MpOnline')
interface MpAccountSummary {
id: string
userName: string
nickName: string
avatar: string
nickName?: string
avatar?: string
enabled: boolean
isCurrent: boolean
status: MpAccountStatus
intervalMinutes: number
intervalMinutes?: number
lastCheckAt?: number
lastOnlineAt?: number
failCount: number
note?: string
/** 会话过期时间(秒级时间戳) */
sessionExpiry?: number | null
cookieCount: number
createdAt: number
}
/** 保活运行记录 */
interface MpRunRecord {
at: number
id: string
status: 'online' | 'expired' | 'offline' | 'error' | 'skipped'
note?: string
expiryBefore?: number | null
expiryAfter?: number | null
}
interface MpState {
accounts: MpAccountSummary[]
targetId: string
alarmPeriodMinutes: number | null
lastRunAt?: number | null
history?: MpRunRecord[]
}
const STATUS_META: Record<MpAccountStatus, { label: string; className: string }> = {
@@ -45,6 +59,14 @@ const STATUS_META: Record<MpAccountStatus, { label: string; className: string }>
unknown: { label: '未检测', className: 'bg-muted text-muted-foreground' },
}
const RUN_STATUS_META: Record<MpRunRecord['status'], string> = {
online: '在线',
expired: '已过期',
offline: '离线',
error: '异常',
skipped: '跳过',
}
function formatTime(ts?: number): string {
if (!ts) return '—'
const d = new Date(ts)
@@ -168,6 +190,7 @@ export function MpOnlinePage() {
})
const accounts = state?.accounts || []
const history = state?.history || []
const onlineCount = accounts.filter((a) => a.status === 'online').length
return (
@@ -197,6 +220,7 @@ export function MpOnlinePage() {
同时保存多个公众号的登录态,后台定时"保活"防止掉线;
保活只用各账号自己的 Cookie,<b>不会影响浏览器当前登录的公众号</b>。
{state?.alarmPeriodMinutes ? ` 当前每 ${state.alarmPeriodMinutes} 分钟自动保活一次。` : ' 有账号开启保活后会自动定时执行。'}
{state?.lastRunAt ? ` 上次自动保活 ${formatTime(state.lastRunAt)}。` : ''}
</div>
{/* 添加 */}
@@ -268,6 +292,7 @@ export function MpOnlinePage() {
</div>
<div className="text-[11px] text-muted-foreground truncate">
{account.userName} · 上次在线 {formatTime(account.lastOnlineAt)}
{account.sessionExpiry ? ` · 会话至 ${formatTime(account.sessionExpiry * 1000)}` : ''}
</div>
</div>
<label className="flex items-center gap-1 text-[11px] text-muted-foreground cursor-pointer">
@@ -337,6 +362,30 @@ export function MpOnlinePage() {
)
})}
{/* 保活运行记录 */}
{history.length > 0 && (
<div className="rounded-lg border p-2.5 space-y-1">
<div className="text-xs text-muted-foreground">保活运行记录(最近 {history.length} 条)</div>
{history.map((h) => (
<div key={`${h.at}-${h.id}`} className="flex items-baseline justify-between gap-2 text-[11px]">
<span className="text-muted-foreground shrink-0">
{formatTime(h.at)} · {RUN_STATUS_META[h.status] || h.status}
</span>
<span className="truncate text-right">
{h.expiryAfter
? `会话至 ${formatTime(h.expiryAfter * 1000)}${
h.expiryBefore && h.expiryAfter > h.expiryBefore ? '(已续期)' : ''
}`
: h.expiryBefore
? `会话至 ${formatTime(h.expiryBefore * 1000)}`
: ''}
{h.note ? ` · ${h.note}` : ''}
</span>
</div>
))}
</div>
)}
{/* 汇总 */}
{accounts.length > 0 && (
<div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">