diff --git a/package.json b/package.json index f588a4e3..8c787af6 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.14.5", + "version": "1.14.6", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 84bb67ca..f2959a35 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.14.5", + "version": "1.14.6", "private": true, "type": "module", "description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).", diff --git a/packages/common/package.json b/packages/common/package.json index 2f4ea97f..20aaf258 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.14.5", + "version": "1.14.6", "private": true, "type": "module", "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", diff --git a/packages/core/package.json b/packages/core/package.json index b6e2c4de..d6eada66 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.14.5", + "version": "1.14.6", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", @@ -44,10 +44,11 @@ "@snowluma/bridge": "workspace:*", "@snowluma/common": "workspace:*", "@snowluma/onebot": "workspace:*", - "@snowluma/protocol": "workspace:*", "@snowluma/proto-defs": "workspace:*", + "@snowluma/protocol": "workspace:*", "@snowluma/proton": "workspace:*", - "@snowluma/websocket": "workspace:*" + "@snowluma/websocket": "workspace:*", + "otpauth": "^9.5.1" }, "devDependencies": { "@hono/node-server": "^1.19.14", diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index f8a80572..5d6ad235 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -34,6 +34,13 @@ import type { BridgeContext } from '../bridge-context'; const log = createLogger('Bridge.Contacts'); +// Official client stores group mute as an expire timestamp (internal 60027 / +// JS groupShutupExpireTime): 0 = off, 0xFFFFFFFF = permanent, otherwise unix +// seconds. `> 0` is wrong — a leftover past expire still looks "on". +function isGroupAllMuted(expireTs?: number, nowSec = Math.floor(Date.now() / 1000)): boolean { + return (expireTs ?? 0) > nowSec; +} + // ─── Helpers (previously in bridge-contacts.ts) ─────────────────── type FriendPropertySource = { @@ -310,7 +317,7 @@ export class ContactsApi { // is not in the list (0x88D_0 detail only), so it stays undefined here. createTime: raw.info?.createdTime ?? 0, memo: raw.info?.announcement || raw.info?.description || '', - allMuted: (raw.info?.shutUpAllTimestamp ?? 0) > 0, + allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp), }); } this.ctx.identity.rememberGroups(groups); @@ -341,7 +348,7 @@ export class ContactsApi { createTime: Number(r.createTime ?? 0n), level: Number(r.level ?? 0n), memo: r.noticePreview ?? '', - allMuted: (r.shutUpAllTimestamp ?? 0) > 0, + allMuted: isGroupAllMuted(r.shutUpAllTimestamp), }; } diff --git a/packages/core/src/bridge/apis/profile.ts b/packages/core/src/bridge/apis/profile.ts index d848afb8..1ac48ca1 100644 --- a/packages/core/src/bridge/apis/profile.ts +++ b/packages/core/src/bridge/apis/profile.ts @@ -19,9 +19,12 @@ import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-inp import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile'; import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { createLogger } from '@snowluma/common/logger'; import type { Bridge } from '../bridge'; import type { BridgeContext } from '../bridge-context'; +const log = createLogger('Bridge.Profile'); + function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } export interface CustomFaceDetail { @@ -133,8 +136,37 @@ export class ProfileApi { // ─────────────── queries on me / my contacts ─────────────── - getLike(userId?: number, start = 0, limit = 10): Promise { - return GetLike.invoke(this.ctx, { userId, start, limit }); + async getLike(userId?: number, start = 0, limit = 10): Promise { + const info = await GetLike.invoke(this.ctx, { userId, start, limit }); + const users = [...info.favoriteInfo.userInfos, ...info.voteInfo.userInfos]; + const unresolved = new Map(); + + for (const user of users) { + if (user.uin > 0) continue; + const sameUid = unresolved.get(user.uid) ?? []; + sameUid.push(user); + unresolved.set(user.uid, sameUid); + } + + await Promise.all([...unresolved].map(async ([uid, sameUid]) => { + try { + const profile = await this.ctx.apis.contacts.fetchUserProfileByUid(uid); + if (profile.uin <= 0) { + log.warn('profile-like user resolution returned no uin: uid=%s', uid); + return; + } + for (const user of sameUid) user.uin = profile.uin; + } catch (error) { + log.error( + 'profile-like user resolution failed: uid=%s err=%s', + uid, + error instanceof Error ? error.message : String(error), + ); + throw error; + } + })); + + return info; } getUnidirectionalFriendList(): Promise { diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index 3dcd2bba..ad1fa4fc 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -2,6 +2,12 @@ import { createLogger } from '@snowluma/common/logger'; import { randomBytes, scryptSync, timingSafeEqual } from 'crypto'; import fs from 'fs'; import path from 'path'; +import { + parseTotpStateLenient, + prepareTotpStateForRestore, + rewrapTotpSecret, + type TotpPersistedState, +} from './totp'; const log = createLogger('WebUI.Auth'); @@ -32,6 +38,7 @@ export interface WebuiAuthState { mustChangePassword: boolean; generatedAt: string; updatedAt: string; + totp?: TotpPersistedState; } export interface PasswordRule { @@ -91,24 +98,43 @@ export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) { throw new Error('updatedAt must be a valid timestamp'); } - const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt']); + const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt', 'totp']); const unknown = Object.keys(v).find((key) => !allowed.has(key)); if (unknown) throw new Error(`unknown field $.${unknown}`); - return { + const state: WebuiAuthState = { passwordHash: v.passwordHash, passwordSalt: v.passwordSalt, mustChangePassword: v.mustChangePassword, generatedAt: v.generatedAt, updatedAt: v.updatedAt, }; + if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) { + return state; + } + state.totp = prepareTotpStateForRestore(v.totp); + return state; } -function isValidState(value: unknown): value is WebuiAuthState { +function parseLiveAuthState(value: unknown): WebuiAuthState | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const v = value as Record; + const totpValue = v.totp; + const withoutTotp = { ...v }; + delete withoutTotp.totp; try { - prepareWebuiAuthStateForRestore(value); - return true; + const state = prepareWebuiAuthStateForRestore( + Object.prototype.hasOwnProperty.call(v, 'totp') + ? withoutTotp + : value, + ); + const totp = parseTotpStateLenient(totpValue); + if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) { + log.warn('webui.json totp field is invalid and will be ignored; password credentials are unchanged'); + } + if (totp) state.totp = totp; + return state; } catch { - return false; + return null; } } @@ -177,8 +203,9 @@ export class WebuiAuth { try { const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8'); const parsed = JSON.parse(raw) as unknown; - if (isValidState(parsed)) { - if (parsed.mustChangePassword) { + const live = parseLiveAuthState(parsed); + if (live) { + if (live.mustChangePassword) { // Previous start generated a bootstrap password but the operator // never completed the forced-change flow. The plaintext is gone // (only the hash is on disk, and the log line from last run may @@ -189,7 +216,7 @@ export class WebuiAuth { log.warn('previous bootstrap password was never rotated; regenerated a new one'); return new WebuiAuth(state, initialPassword, false); } - return new WebuiAuth(parsed, null, false); + return new WebuiAuth(live, null, false); } log.error('webui.json schema invalid; backing up and regenerating credentials'); backupCorruptConfig(); @@ -257,13 +284,20 @@ export class WebuiAuth { } } - setPassword(newPassword: string): void { + setPassword(newPassword: string, currentPassword?: string): void { if (this.devMode) { throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改'); } if (!isStrongPassword(newPassword)) { throw new Error('密码不符合强度要求'); } + let totp = this.state.totp; + if (totp) { + if (typeof currentPassword !== 'string' || currentPassword.length === 0) { + throw new Error('修改密码需要当前密码以重新保护 2FA 密钥'); + } + totp = rewrapTotpSecret(currentPassword, newPassword, totp); + } const salt = randomBytes(16); const hash = hashPassword(newPassword, salt); const next: WebuiAuthState = { @@ -272,8 +306,38 @@ export class WebuiAuth { mustChangePassword: false, generatedAt: this.state.generatedAt, updatedAt: new Date().toISOString(), + ...(totp ? { totp } : {}), }; atomicWrite(next); this.state = next; } + + totpEnabled(): boolean { + return this.state.totp !== undefined; + } + + totpStatus(): { enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } { + const totp = this.state.totp; + if (!totp) return { enabled: false }; + return { + enabled: true, + remainingRecoveryCodes: totp.recoveryCodeHashes.length, + label: totp.label, + }; + } + + totpState(): TotpPersistedState | undefined { + return this.state.totp; + } + + persistTotp(totp: TotpPersistedState | undefined): void { + if (this.devMode) { + throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA'); + } + const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() }; + if (totp) next.totp = totp; + else delete next.totp; + atomicWrite(next); + this.state = next; + } } diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 58611be3..56af0ec5 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -39,6 +39,13 @@ import os from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth'; +import { completeWebuiLogin, invalidateOtherSessions } from './webui-login'; +import { + beginTotpEnrollment, + confirmTotpEnrollment, + decideSecondFactorLogin, + regenerateRecoveryCodes, +} from './totp'; import { EULA_ACCEPT_ENV, getAgreementsPayload, @@ -103,10 +110,18 @@ interface SessionInfo { const sessionTokens = new Map(); const loginAttempts = new Map(); +const totpEnrollments = new Map(); const LOGIN_MAX_ATTEMPTS = 5; const LOGIN_LOCKOUT_MS = 15 * 60 * 1000; const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; +const TOTP_ENROLL_TTL_MS = 10 * 60 * 1000; +const DEFAULT_TOTP_ISSUER = 'SnowLuma'; const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000; const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60; @@ -229,6 +244,21 @@ function purgeExpiredTokens() { for (const [ip, attempt] of loginAttempts) { if (now > attempt.resetAt) loginAttempts.delete(ip); } + for (const [token, enrollment] of totpEnrollments) { + if (now > enrollment.expiresAt) totpEnrollments.delete(token); + } +} + +function sanitizeTotpLabelPart(value: unknown, fallback: string): string { + if (typeof value !== 'string') return fallback; + const trimmed = value.replace(/[\r\n\t]/g, '').trim(); + if (!trimmed) return fallback; + return trimmed.slice(0, 64); +} + +function defaultTotpAccountName(): string { + const host = os.hostname().trim(); + return host || 'admin'; } @@ -632,27 +662,42 @@ export async function initWebUI( return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429); } - let body: { password?: unknown }; + let body: unknown; try { body = await c.req.json(); } catch { return c.json({ success: false, message: '请求格式错误' }, 400); } - const password = typeof body.password === 'string' ? body.password : ''; - if (!auth.verify(password)) { + + const result = completeWebuiLogin(auth, body, now); + if (result.kind === 'bad-request') { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + if (result.kind === 'bad-password' || result.kind === 'bad-second-factor') { const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS }; current.count += 1; if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS; loginAttempts.set(ip, current); - return c.json({ success: false, message: '密码错误' }, 401); + const message = result.kind === 'bad-second-factor' ? '验证码不正确' : '密码错误'; + return c.json({ success: false, message }, 401); + } + if (result.kind === 'needs-totp') { + return c.json({ success: false, needsTotp: true }); } loginAttempts.delete(ip); + if (result.totpState) { + try { + auth.persistTotp(result.totpState); + } catch (err) { + log.warn('persist totp after login failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '登录失败' }, 500); + } + } const token = randomBytes(32).toString('hex'); - const mustChange = auth.mustChangePassword(); - sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange }); + sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: result.mustChangePassword }); setAvatarSessionCookie(c, token, listener.tlsEnabled === true); - return c.json({ success: true, token, mustChangePassword: mustChange }); + return c.json({ success: true, token, mustChangePassword: result.mustChangePassword }); }); app.post('/api/logout', (c) => { @@ -703,7 +748,7 @@ export async function initWebUI( return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400); } try { - auth.setPassword(newPassword); + auth.setPassword(newPassword, oldPassword); } catch (err) { log.warn('change password failed: %s', err instanceof Error ? err.message : String(err)); return c.json({ success: false, message: '密码修改失败' }, 400); @@ -717,6 +762,167 @@ export async function initWebUI( return c.json({ success: true, requireRelogin: true }); }); + const totpDisabledInDev = () => auth.isDevMode(); + + app.get('/api/auth/totp', (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + return c.json(auth.totpStatus()); + }); + + app.post('/api/auth/totp/begin', async (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + if (auth.totpEnabled()) { + return c.json({ success: false, message: '2FA 已开启' }, 409); + } + const token = c.get('sessionToken' as never) as string; + let body: Record = {}; + try { + const parsed = await c.req.json(); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + body = parsed as Record; + } + } catch { + body = {}; + } + const issuer = sanitizeTotpLabelPart(body.issuer, DEFAULT_TOTP_ISSUER); + const accountName = sanitizeTotpLabelPart(body.accountName, defaultTotpAccountName()); + const now = Date.now(); + const existing = totpEnrollments.get(token); + const secret = existing && existing.expiresAt > now ? existing.secret : undefined; + const enrollment = beginTotpEnrollment({ issuer, accountName, secret }); + totpEnrollments.set(token, { + secret: enrollment.secret, + issuer, + accountName, + expiresAt: now + TOTP_ENROLL_TTL_MS, + }); + return c.json({ + success: true, + secret: enrollment.secret, + otpauthUrl: enrollment.otpauthUrl, + issuer: enrollment.issuer, + accountName: enrollment.accountName, + }); + }); + + app.post('/api/auth/totp/confirm', async (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + if (auth.totpEnabled()) { + return c.json({ success: false, message: '2FA 已开启' }, 409); + } + const token = c.get('sessionToken' as never) as string; + let body: { password?: unknown; code?: unknown }; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const password = typeof body.password === 'string' ? body.password : ''; + const code = typeof body.code === 'string' ? body.code : ''; + if (!auth.verify(password)) { + return c.json({ success: false, message: '当前密码不正确' }, 401); + } + const pending = totpEnrollments.get(token); + if (!pending || pending.expiresAt <= Date.now()) { + totpEnrollments.delete(token); + return c.json({ success: false, message: '请先开始绑定' }, 400); + } + try { + const enabled = confirmTotpEnrollment({ + password, + secret: pending.secret, + code, + label: `${pending.issuer} (${pending.accountName})`, + atMs: Date.now(), + }); + auth.persistTotp(enabled.state); + totpEnrollments.delete(token); + invalidateOtherSessions(sessionTokens, token); + log.info('webui 2FA enabled; other sessions invalidated'); + return c.json({ success: true, recoveryCodes: enabled.recoveryCodes }); + } catch (err) { + log.warn('totp confirm failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '验证码不正确' }, 401); + } + }); + + app.post('/api/auth/totp/disable', async (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + if (!auth.totpEnabled()) { + return c.json({ success: false, message: '2FA 未开启' }, 400); + } + const token = c.get('sessionToken' as never) as string; + let body: { password?: unknown; totp?: unknown; recoveryCode?: unknown }; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const password = typeof body.password === 'string' ? body.password : ''; + if (!auth.verify(password)) { + return c.json({ success: false, message: '当前密码不正确' }, 401); + } + const decision = decideSecondFactorLogin({ + totpEnabled: true, + state: auth.totpState(), + password, + totp: typeof body.totp === 'string' ? body.totp : undefined, + recoveryCode: typeof body.recoveryCode === 'string' ? body.recoveryCode : undefined, + atMs: Date.now(), + }); + if (decision.kind !== 'ok') { + return c.json({ success: false, message: '验证码不正确' }, 401); + } + auth.persistTotp(undefined); + totpEnrollments.delete(token); + invalidateOtherSessions(sessionTokens, token); + log.info('webui 2FA disabled; other sessions invalidated'); + return c.json({ success: true }); + }); + + app.post('/api/auth/totp/recovery-codes', async (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + const state = auth.totpState(); + if (!state) { + return c.json({ success: false, message: '2FA 未开启' }, 400); + } + let body: { password?: unknown; totp?: unknown }; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const password = typeof body.password === 'string' ? body.password : ''; + const totp = typeof body.totp === 'string' ? body.totp : ''; + if (!auth.verify(password)) { + return c.json({ success: false, message: '当前密码不正确' }, 401); + } + try { + const next = regenerateRecoveryCodes({ + password, + state, + totp, + atMs: Date.now(), + }); + auth.persistTotp(next.state); + log.info('webui 2FA recovery codes regenerated'); + return c.json({ success: true, recoveryCodes: next.recoveryCodes }); + } catch (err) { + log.warn('totp recovery regenerate failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '验证码不正确' }, 401); + } + }); + // ─── EULA / PRIVACY consent ────────────────────────────────────────────── // Both are bearer-gated (consent is collected AFTER login) and live in the // consent + must-change allowlists so they're reachable during onboarding. diff --git a/packages/core/src/webui/totp.ts b/packages/core/src/webui/totp.ts new file mode 100644 index 00000000..82cce090 --- /dev/null +++ b/packages/core/src/webui/totp.ts @@ -0,0 +1,337 @@ +import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto'; +import * as OTPAuth from 'otpauth'; + +const TOTP_PERIOD_SECONDS = 30; +const TOTP_WINDOW = 1; +const TOTP_DIGITS = 6; +const RECOVERY_CODE_COUNT = 8; +const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; +const WRAP_SALT_BYTES = 16; +const WRAP_IV_BYTES = 12; +const WRAP_KEY_BYTES = 32; +const SCRYPT_N = 16384; +const SCRYPT_R = 8; +const SCRYPT_P = 1; + +export interface WrappedTotpSecret { + wrapSalt: string; + iv: string; + ciphertext: string; + authTag: string; +} + +export interface TotpPersistedState extends WrappedTotpSecret { + recoveryCodeHashes: string[]; + lastUsedStep: number; + label: string; +} + +export interface TotpEnrollment { + secret: string; + otpauthUrl: string; + issuer: string; + accountName: string; +} + +function totpFromSecret(secretBase32: string, issuer = '', accountName = 'admin'): OTPAuth.TOTP { + return new OTPAuth.TOTP({ + issuer, + label: accountName, + algorithm: 'SHA1', + digits: TOTP_DIGITS, + period: TOTP_PERIOD_SECONDS, + secret: OTPAuth.Secret.fromBase32(secretBase32), + }); +} + +export function verifyTotpCode( + secretBase32: string, + code: string, + atMs: number, + lastUsedStep?: number, +): { ok: true; step: number } | { ok: false } { + const token = code.replace(/\s/g, ''); + if (!/^\d{6}$/.test(token)) return { ok: false }; + + let totp: OTPAuth.TOTP; + try { + totp = totpFromSecret(secretBase32); + } catch { + return { ok: false }; + } + const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW }); + if (delta === null) return { ok: false }; + + const step = totp.counter({ timestamp: atMs }) + delta; + if (lastUsedStep !== undefined && step === lastUsedStep) return { ok: false }; + return { ok: true, step }; +} + +function deriveWrapKey(password: string, salt: Buffer): Buffer { + return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P }); +} + +export function wrapTotpSecret(password: string, secret: string): WrappedTotpSecret { + const wrapSalt = randomBytes(WRAP_SALT_BYTES); + const iv = randomBytes(WRAP_IV_BYTES); + const key = deriveWrapKey(password, wrapSalt); + const cipher = createCipheriv('aes-256-gcm', key, iv); + const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]); + return { + wrapSalt: wrapSalt.toString('hex'), + iv: iv.toString('hex'), + ciphertext: ciphertext.toString('hex'), + authTag: cipher.getAuthTag().toString('hex'), + }; +} + +export function unwrapTotpSecret(password: string, wrapped: WrappedTotpSecret): string | null { + try { + const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex'); + const iv = Buffer.from(wrapped.iv, 'hex'); + const ciphertext = Buffer.from(wrapped.ciphertext, 'hex'); + const authTag = Buffer.from(wrapped.authTag, 'hex'); + if (wrapSalt.length !== WRAP_SALT_BYTES || iv.length !== WRAP_IV_BYTES || authTag.length !== 16) { + return null; + } + const key = deriveWrapKey(password, wrapSalt); + const decipher = createDecipheriv('aes-256-gcm', key, iv); + decipher.setAuthTag(authTag); + return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8'); + } catch { + return null; + } +} + +function randomRecoveryChunk(): string { + const bytes = randomBytes(4); + let chunk = ''; + for (let i = 0; i < 4; i++) { + chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length]; + } + return chunk; +} + +export function generateRecoveryCodes(): string[] { + const codes = new Set(); + while (codes.size < RECOVERY_CODE_COUNT) { + codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`); + } + return [...codes]; +} + +export function normalizeRecoveryCode(code: string): string { + return code.replace(/[-\s]/g, '').toUpperCase(); +} + +export function hashRecoveryCode(code: string): string { + return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex'); +} + +function hashesEqual(left: string, right: string): boolean { + const a = Buffer.from(left, 'hex'); + const b = Buffer.from(right, 'hex'); + if (a.length !== b.length || a.length === 0) return false; + return timingSafeEqual(a, b); +} + +export function consumeRecoveryCode( + code: string, + hashes: readonly string[], +): { ok: true; remainingHashes: string[] } | { ok: false } { + const candidate = hashRecoveryCode(code); + const index = hashes.findIndex((hash) => hashesEqual(hash, candidate)); + if (index < 0) return { ok: false }; + return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) }; +} + +export function beginTotpEnrollment(options: { + issuer: string; + accountName: string; + secret?: string; +}): TotpEnrollment { + const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32; + const totp = totpFromSecret(secret, options.issuer, options.accountName); + return { + secret, + otpauthUrl: totp.toString(), + issuer: options.issuer, + accountName: options.accountName, + }; +} + +export function confirmTotpEnrollment(options: { + password: string; + secret: string; + code: string; + label: string; + atMs: number; +}): { state: TotpPersistedState; recoveryCodes: string[] } { + const verified = verifyTotpCode(options.secret, options.code, options.atMs); + if (!verified.ok) { + throw new Error('验证码不正确'); + } + const recoveryCodes = generateRecoveryCodes(); + return { + recoveryCodes, + state: { + ...wrapTotpSecret(options.password, options.secret), + recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode), + lastUsedStep: verified.step, + label: options.label, + }, + }; +} + +export function verifySecondFactor(options: { + password: string; + state: TotpPersistedState; + atMs: number; + totp?: string; + recoveryCode?: string; +}): { ok: true; state: TotpPersistedState } | { ok: false } { + if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) { + const consumed = consumeRecoveryCode(options.recoveryCode, options.state.recoveryCodeHashes); + if (!consumed.ok) return { ok: false }; + return { ok: true, state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes } }; + } + if (typeof options.totp !== 'string') return { ok: false }; + const secret = unwrapTotpSecret(options.password, options.state); + if (secret === null) return { ok: false }; + const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep); + if (!checked.ok) return { ok: false }; + return { ok: true, state: { ...options.state, lastUsedStep: checked.step } }; +} + +export type SecondFactorDecision = + | { kind: 'needs-totp' } + | { kind: 'bad-second-factor' } + | { kind: 'ok'; state?: TotpPersistedState }; + +export function decideSecondFactorLogin(options: { + totpEnabled: boolean; + state?: TotpPersistedState; + password: string; + totp?: string; + recoveryCode?: string; + atMs: number; +}): SecondFactorDecision { + if (!options.totpEnabled) return { kind: 'ok' }; + if (!options.state) return { kind: 'bad-second-factor' }; + const totp = typeof options.totp === 'string' && options.totp.trim().length > 0 + ? options.totp.trim() + : undefined; + const recoveryCode = typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0 + ? options.recoveryCode.trim() + : undefined; + if (!totp && !recoveryCode) return { kind: 'needs-totp' }; + const result = verifySecondFactor({ + password: options.password, + state: options.state, + atMs: options.atMs, + totp, + recoveryCode, + }); + if (!result.ok) return { kind: 'bad-second-factor' }; + return { kind: 'ok', state: result.state }; +} + +export function regenerateRecoveryCodes(options: { + password: string; + state: TotpPersistedState; + totp: string; + atMs: number; +}): { state: TotpPersistedState; recoveryCodes: string[] } { + const verified = verifySecondFactor({ + password: options.password, + state: options.state, + totp: options.totp, + atMs: options.atMs, + }); + if (!verified.ok) { + throw new Error('验证码不正确'); + } + const recoveryCodes = generateRecoveryCodes(); + return { + recoveryCodes, + state: { + ...verified.state, + recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode), + }, + }; +} + +export function rewrapTotpSecret( + oldPassword: string, + newPassword: string, + state: TotpPersistedState, +): TotpPersistedState { + const secret = unwrapTotpSecret(oldPassword, state); + if (secret === null) { + throw new Error('无法使用当前密码解开 2FA 密钥'); + } + return { + ...state, + ...wrapTotpSecret(newPassword, secret), + }; +} + +const HEX = /^[0-9a-f]+$/i; + +function isWrappedShape(value: Record): value is WrappedTotpSecret & Record { + return typeof value.wrapSalt === 'string' + && HEX.test(value.wrapSalt) + && value.wrapSalt.length === WRAP_SALT_BYTES * 2 + && typeof value.iv === 'string' + && HEX.test(value.iv) + && value.iv.length === WRAP_IV_BYTES * 2 + && typeof value.ciphertext === 'string' + && HEX.test(value.ciphertext) + && value.ciphertext.length > 0 + && value.ciphertext.length % 2 === 0 + && typeof value.authTag === 'string' + && HEX.test(value.authTag) + && value.authTag.length === 32; +} + +export function prepareTotpStateForRestore(value: unknown): TotpPersistedState { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error('totp state must be an object'); + } + const v = value as Record; + if (!isWrappedShape(v)) { + throw new Error('totp wrapped secret fields are invalid'); + } + if (!Array.isArray(v.recoveryCodeHashes) + || v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT + || v.recoveryCodeHashes.some((hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash))) { + throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings'); + } + if (typeof v.lastUsedStep !== 'number' || !Number.isInteger(v.lastUsedStep) || v.lastUsedStep < 0) { + throw new Error('totp lastUsedStep must be a non-negative integer'); + } + if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) { + throw new Error('totp label must be a non-empty string'); + } + const allowed = new Set(['wrapSalt', 'iv', 'ciphertext', 'authTag', 'recoveryCodeHashes', 'lastUsedStep', 'label']); + const unknown = Object.keys(v).find((key) => !allowed.has(key)); + if (unknown) throw new Error(`unknown totp field $.${unknown}`); + return { + wrapSalt: v.wrapSalt.toLowerCase(), + iv: v.iv.toLowerCase(), + ciphertext: v.ciphertext.toLowerCase(), + authTag: v.authTag.toLowerCase(), + recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()), + lastUsedStep: v.lastUsedStep, + label: v.label, + }; +} + +export function parseTotpStateLenient(value: unknown): TotpPersistedState | undefined { + if (value === undefined || value === null) return undefined; + try { + return prepareTotpStateForRestore(value); + } catch { + return undefined; + } +} diff --git a/packages/core/src/webui/webui-login.ts b/packages/core/src/webui/webui-login.ts new file mode 100644 index 00000000..81efb6e2 --- /dev/null +++ b/packages/core/src/webui/webui-login.ts @@ -0,0 +1,51 @@ +import { decideSecondFactorLogin, type TotpPersistedState } from './totp'; + +export interface WebuiLoginAuth { + verify(password: string): boolean; + totpEnabled(): boolean; + totpState(): TotpPersistedState | undefined; + mustChangePassword(): boolean; +} + +export type WebuiLoginResult = + | { kind: 'bad-request' } + | { kind: 'bad-password' } + | { kind: 'needs-totp' } + | { kind: 'bad-second-factor' } + | { kind: 'ok'; mustChangePassword: boolean; totpState?: TotpPersistedState }; + +function readString(value: unknown): string { + return typeof value === 'string' ? value : ''; +} + +export function completeWebuiLogin(auth: WebuiLoginAuth, body: unknown, atMs: number): WebuiLoginResult { + if (!body || typeof body !== 'object' || Array.isArray(body)) { + return { kind: 'bad-request' }; + } + const record = body as Record; + const password = readString(record.password); + if (!auth.verify(password)) { + return { kind: 'bad-password' }; + } + const decision = decideSecondFactorLogin({ + totpEnabled: auth.totpEnabled(), + state: auth.totpState(), + password, + totp: readString(record.totp) || undefined, + recoveryCode: readString(record.recoveryCode) || undefined, + atMs, + }); + if (decision.kind === 'needs-totp') return { kind: 'needs-totp' }; + if (decision.kind === 'bad-second-factor') return { kind: 'bad-second-factor' }; + return { + kind: 'ok', + mustChangePassword: auth.mustChangePassword(), + ...(decision.state ? { totpState: decision.state } : {}), + }; +} + +export function invalidateOtherSessions(sessions: Map, keepToken: string): void { + for (const token of sessions.keys()) { + if (token !== keepToken) sessions.delete(token); + } +} diff --git a/packages/core/tests/actions/contacts.test.ts b/packages/core/tests/actions/contacts.test.ts index c7b3e396..c0548506 100644 --- a/packages/core/tests/actions/contacts.test.ts +++ b/packages/core/tests/actions/contacts.test.ts @@ -269,6 +269,25 @@ describe('apis/contacts / group roster', () => { allMuted: true, })); }); + + it('treats a past group-mute expire as unmuted (#356)', async () => { + const sendRawPacket = vi.fn(async () => groupListPacket({ + groups: [{ + groupUin: 123456789, + info: { + groupName: 'Was Muted', + shutUpAllTimestamp: 1_700_000_000, + }, + }], + })); + const api = new ContactsApi({ + sendRawPacket, + identity: { rememberGroups: vi.fn() }, + } as any); + + const groups = await api.fetchGroupList(); + expect(groups[0]?.allMuted).toBe(false); + }); }); describe('apis/contacts / group requests', () => { diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index fa95515e..598cc737 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -173,22 +173,35 @@ describe('apis/profile', () => { it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => { const bridge = mockBridge(); + bridge.identity.findUinByUid.mockImplementation( + (uid: string) => uid === 'liker-uid' ? 20002 : 0, + ); bridge.sendRawPacket.mockResolvedValueOnce({ success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.from(protobuf_encode>({ body: { userLikeInfos: [{ uid: 'u', - time: 1700000000n, - favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 }, - voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n }, + time: 1700000000, + favoriteInfo: { totalCount: 5, lastTime: 1, todayCount: 1 }, + voteInfo: { + totalCount: 7, + newCount: 2, + newNearbyCount: 1, + lastVisitTime: 2, + userInfos: [{ uid: 'liker-uid', nick: '点赞者', count: 3 }], + }, }], } as any, })), }); const out = await new ProfileApi(bridge as any).getLike(); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x7ed_13'); expect(out.favoriteInfo.total_count).toBe(5); expect(out.voteInfo.total_count).toBe(7); + expect(out.voteInfo.userInfos).toEqual([ + expect.objectContaining({ uid: 'liker-uid', uin: 20002, nick: '点赞者', count: 3 }), + ]); }); it('getProfileLike throws on empty result', async () => { @@ -200,6 +213,56 @@ describe('apis/profile', () => { await expect(new ProfileApi(bridge as any).getLike()).rejects.toThrow(/empty/); }); + it('getProfileLike resolves uncached liker uins from their profiles', async () => { + const bridge = mockBridge(); + bridge.identity.findUinByUid.mockReturnValue(null); + const fetchUserProfileByUid = vi.fn(async (uid: string) => ({ + uid, + uin: 30003, + nickname: '陌生点赞者', + })); + (bridge.apis.contacts as any).fetchUserProfileByUid = fetchUserProfileByUid; + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ + body: { + userLikeInfos: [{ + uid: 'self-uid', + voteInfo: { userInfos: [{ uid: 'stranger-uid', nick: '陌生点赞者' }] }, + }], + }, + })), + }); + + const out = await new ProfileApi(bridge as any).getLike(); + + expect(fetchUserProfileByUid).toHaveBeenCalledOnce(); + expect(fetchUserProfileByUid).toHaveBeenCalledWith('stranger-uid'); + expect(out.voteInfo.userInfos[0]?.uin).toBe(30003); + }); + + it('getProfileLike surfaces failures while resolving uncached liker uins', async () => { + const bridge = mockBridge(); + bridge.identity.findUinByUid.mockReturnValue(null); + (bridge.apis.contacts as any).fetchUserProfileByUid = vi.fn(async () => { + throw new Error('profile lookup failed'); + }); + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ + body: { + userLikeInfos: [{ + uid: 'self-uid', + voteInfo: { userInfos: [{ uid: 'stranger-uid' }] }, + }], + }, + })), + }); + + await expect(new ProfileApi(bridge as any).getLike()) + .rejects.toThrow('profile lookup failed'); + }); + it('getUnidirectionalFriendList parses the embedded JSON body', async () => { const bridge = mockBridge(); bridge.sendRawPacket.mockResolvedValueOnce({ diff --git a/packages/core/tests/highway-utils.test.ts b/packages/core/tests/highway-utils.test.ts index bcbe5c2f..bd217ad9 100644 --- a/packages/core/tests/highway-utils.test.ts +++ b/packages/core/tests/highway-utils.test.ts @@ -3,7 +3,7 @@ import os from 'os'; import path from 'path'; import { pathToFileURL } from 'url'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { loadBinarySource, resolveLocalFilePath } from '@snowluma/protocol/highway/utils'; +import { guessFileNameFromUrl, loadBinarySource, resolveLocalFilePath } from '@snowluma/protocol/highway/utils'; describe('highway source paths', () => { it('normalizes file URLs with an extra leading slash on POSIX', () => { @@ -12,6 +12,16 @@ describe('highway source paths', () => { .toBe('/AstrBot/data/plugin/cache/BV-test.mp4'); }); + it('percent-decodes a URL basename used as the upload filename (#354)', () => { + expect(guessFileNameFromUrl( + 'file:///D:/test/%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.xlsx', + )).toBe('测试文件.xlsx'); + expect(guessFileNameFromUrl('https://cdn.example/a/%E4%B8%AD%E6%96%87.png?x=1')) + .toBe('中文.png'); + expect(guessFileNameFromUrl('https://cdn.example/plain.bin')).toBe('plain.bin'); + expect(guessFileNameFromUrl('https://cdn.example/%ZZ.xlsx')).toBe('%ZZ.xlsx'); + }); + it('loads encoded file URLs from the local filesystem', async () => { const filePath = path.join(os.tmpdir(), `snowluma video ${process.pid}-${Date.now()}.txt`); fs.writeFileSync(filePath, 'ok'); diff --git a/packages/core/tests/highway/highway-client.test.ts b/packages/core/tests/highway/highway-client.test.ts index fca8bc3d..d187658f 100644 --- a/packages/core/tests/highway/highway-client.test.ts +++ b/packages/core/tests/highway/highway-client.test.ts @@ -2,10 +2,12 @@ // // 方案 3(#211):单连接、按 offset 顺序、流水线上传,跨 chunk 复用同一个 // TCP 连接(HTTP keep-alive)。要点: -// - 顺序发送 → 天然保序,避开 QQ highway 对乱序块的 error_code=102902; +// - 顺序发送 → 减少 QQ highway 对重叠块的 NeedDelayRetry(error_code=102902); // - 复用连接 → TCP 拥塞窗口全程保持,省掉每块新建连接的 slow-start。 // 边缘节点可能在响应后 FIN(#118);此时自适应地丢弃 socket + 重连 + 重发 // 同一块(重发幂等),最坏退化成“每块一连接”,不比旧实现差,且仍然保序。 +// 102902 / 302902 不是致命拒绝(#352):官方 BDH 走 NeedDelayRetry,延迟后 +// 换连接重发同一 offset。 // // 本测试用两种 mock 服务端行为锁定这套自适应逻辑: // - keepalive:每个 POST 回一个响应,连接保持 → 整个文件 1 个连接; @@ -36,10 +38,21 @@ function buildEmptyHighwayResponseFrame(): Buffer { return frame; } -// errorCode 帧:RespDataHighwayHead.field3 (errorCode) = 921。tag(field3, -// varint)=0x18,varint(921)=0x99 0x07。定义即拒绝(不重试)。 -function buildErrorCodeFrame(): Buffer { - const head = Buffer.from([0x18, 0x99, 0x07]); +function encodeVarint(n: number): number[] { + const bytes: number[] = []; + let value = n >>> 0; + while (value > 0x7f) { + bytes.push((value & 0x7f) | 0x80); + value >>>= 7; + } + bytes.push(value); + return bytes; +} + +// errorCode 帧:RespDataHighwayHead.field3 (errorCode)。tag(field3, varint)=0x18。 +// 921 是定义即拒绝;102902 / 302902 是 QQ BDH 的 NeedDelayRetry(#352)。 +function buildErrorCodeFrame(errorCode = 921): Buffer { + const head = Buffer.from([0x18, ...encodeVarint(errorCode)]); const frame = Buffer.alloc(9 + head.length + 1); frame[0] = 0x28; frame.writeUInt32BE(head.length, 1); @@ -75,6 +88,7 @@ class FakeSocket extends EventEmitter { private readonly failOnPost = -1, private readonly truncateOnPost = -1, private readonly errorAfterPartialOnPost = -1, + private readonly frameOnPost: Readonly> = {}, ) { super(); } @@ -135,7 +149,7 @@ class FakeSocket extends EventEmitter { this.emit('close'); return; } - this.emit('data', httpWrap(this.responseFrame)); + this.emit('data', httpWrap(this.frameOnPost[thisPost] ?? this.responseFrame)); if (this.mode === 'closeafter') { this.readableEnded = true; this.writable = false; @@ -660,4 +674,69 @@ describe('uploadHighwayHttp single-connection pipelined upload (#211)', () => { // Definitive reject on block 0 → stop immediately, don't PUT later blocks. expect(source.reads.length).toBeLessThan(3); }); + + it('delay-retries 102902 on the same offset, then completes (#352)', async () => { + // QQ BDH NeedDelayRetry: 102902 is backpressure, not a fatal reject. + // Official client delays, switches sender, and re-PUTs the same piece. + installFactory((idx) => idx === 0 + ? new FakeSocket(buildErrorCodeFrame(102902), 'keepalive') + : new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + try { + const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); + await uploadHighwayHttp( + makeBridge(), makeSession(), 71, new BufferChunkSource(bytes), + new Uint8Array(16), new Uint8Array(0), + ); + expect(createConnectionMock).toHaveBeenCalledTimes(2); + const messages = highwayTrace(entries).map((entry) => entry.message); + expect(messages).toEqual(expect.arrayContaining([ + expect.stringContaining('branch=chunk_delay_retry offset=0'), + expect.stringContaining('errorCode=102902'), + expect.stringContaining('outcome=completed reason=upload_complete'), + ])); + } finally { + unsubscribe(); + } + }); + + it('delay-retries 302902 the same way as 102902', async () => { + installFactory((idx) => idx === 0 + ? new FakeSocket(buildErrorCodeFrame(302902), 'keepalive') + : new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); + await uploadHighwayHttp( + makeBridge(), makeSession(), 71, + new BufferChunkSource(new Uint8Array(512 * 1024)), + new Uint8Array(16), new Uint8Array(0), + ); + expect(createConnectionMock).toHaveBeenCalledTimes(2); + }); + + it('delay-retries 102902 on a later in-order block after keep-alive was already warm (#352 shape)', async () => { + // Mirrors the report: sequential upload is healthy, then a later offset + // returns 102902. Recovery must re-PUT that offset, not abort the file. + installFactory((idx) => idx === 0 + ? new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', -1, -1, -1, { + 3: buildErrorCodeFrame(102902), + }) + : new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); + const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks + await uploadHighwayHttp( + makeBridge(), makeSession(), 71, new BufferChunkSource(bytes), + new Uint8Array(16), new Uint8Array(0), + ); + expect(createConnectionMock).toHaveBeenCalledTimes(2); + }); + + it('exhausts delay-retries when 102902 keeps coming back', async () => { + installFactory(() => new FakeSocket(buildErrorCodeFrame(102902), 'keepalive')); + await expect(uploadHighwayHttp( + makeBridge(), makeSession(), 71, + new BufferChunkSource(new Uint8Array(16)), + new Uint8Array(16), new Uint8Array(0), + )).rejects.toThrow(/error_code=102902/); + expect(createConnectionMock.mock.calls.length).toBeGreaterThan(1); + }); }); diff --git a/packages/core/tests/webui-login.test.ts b/packages/core/tests/webui-login.test.ts new file mode 100644 index 00000000..87b3610a --- /dev/null +++ b/packages/core/tests/webui-login.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest'; +import { confirmTotpEnrollment } from '../src/webui/totp'; +import { completeWebuiLogin, invalidateOtherSessions, type WebuiLoginAuth } from '../src/webui/webui-login'; + +const RFC_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'; +const T59_MS = 59_000; +const T59_CODE = '287082'; +const PASSWORD = 'Correct-Horse-1!'; + +function authWithoutTotp(): WebuiLoginAuth { + return { + verify: (password) => password === PASSWORD, + totpEnabled: () => false, + totpState: () => undefined, + mustChangePassword: () => false, + }; +} + +describe('completeWebuiLogin', () => { + it('rejects a wrong password without mentioning TOTP', () => { + expect(completeWebuiLogin(authWithoutTotp(), { password: 'nope' }, T59_MS)).toEqual({ + kind: 'bad-password', + }); + }); + + it('logs in with only a password when 2FA is off', () => { + expect(completeWebuiLogin(authWithoutTotp(), { password: PASSWORD }, T59_MS)).toEqual({ + kind: 'ok', + mustChangePassword: false, + }); + }); + + it('asks for TOTP after a correct password when 2FA is on', () => { + const enabled = confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + const auth: WebuiLoginAuth = { + verify: (password) => password === PASSWORD, + totpEnabled: () => true, + totpState: () => enabled.state, + mustChangePassword: () => false, + }; + expect(completeWebuiLogin(auth, { password: PASSWORD }, T59_MS)).toEqual({ + kind: 'needs-totp', + }); + }); + + it('accepts password plus TOTP and returns the updated totp state', () => { + const enabled = confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + const auth: WebuiLoginAuth = { + verify: (password) => password === PASSWORD, + totpEnabled: () => true, + totpState: () => enabled.state, + mustChangePassword: () => true, + }; + const result = completeWebuiLogin( + auth, + { password: PASSWORD, totp: '081804' }, + 1_111_111_109_000, + ); + expect(result.kind).toBe('ok'); + if (result.kind !== 'ok') return; + expect(result.mustChangePassword).toBe(true); + expect(result.totpState?.lastUsedStep).toBeGreaterThan(enabled.state.lastUsedStep); + }); +}); + +describe('invalidateOtherSessions', () => { + it('keeps the current session and drops the rest', () => { + const sessions = new Map([ + ['keep', { n: 1 }], + ['drop-a', { n: 2 }], + ['drop-b', { n: 3 }], + ]); + invalidateOtherSessions(sessions, 'keep'); + expect([...sessions.keys()]).toEqual(['keep']); + }); +}); diff --git a/packages/core/tests/webui-totp.test.ts b/packages/core/tests/webui-totp.test.ts new file mode 100644 index 00000000..84c89d1c --- /dev/null +++ b/packages/core/tests/webui-totp.test.ts @@ -0,0 +1,272 @@ +import { describe, expect, it } from 'vitest'; +import { prepareWebuiAuthStateForRestore } from '../src/webui/auth'; +import { + beginTotpEnrollment, + confirmTotpEnrollment, + consumeRecoveryCode, + decideSecondFactorLogin, + generateRecoveryCodes, + hashRecoveryCode, + parseTotpStateLenient, + prepareTotpStateForRestore, + regenerateRecoveryCodes, + rewrapTotpSecret, + unwrapTotpSecret, + verifySecondFactor, + verifyTotpCode, + wrapTotpSecret, +} from '../src/webui/totp'; + +// RFC 6238 Appendix B, SHA-1, secret ASCII "12345678901234567890". +// 8-digit vector at T=59 is 94287082; 6-digit TOTP is that value mod 10^6. +const RFC_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'; +const T59_MS = 59_000; +const T59_CODE = '287082'; +const T1111111109_MS = 1_111_111_109_000; +const T1111111109_CODE = '081804'; +const PASSWORD = 'Correct-Horse-1!'; + +describe('verifyTotpCode', () => { + it('accepts the RFC 6238 SHA-1 6-digit code at T=59', () => { + expect(verifyTotpCode(RFC_SECRET, T59_CODE, T59_MS)).toEqual({ ok: true, step: 1 }); + }); + + it('rejects a wrong 6-digit code at the same instant', () => { + expect(verifyTotpCode(RFC_SECRET, '000000', T59_MS)).toEqual({ ok: false }); + }); + + it('rejects the same time-step being used twice', () => { + expect(verifyTotpCode(RFC_SECRET, T59_CODE, T59_MS, 1)).toEqual({ ok: false }); + }); +}); + +describe('wrapTotpSecret', () => { + it('round-trips a TOTP secret with the wrapping password', () => { + const wrapped = wrapTotpSecret(PASSWORD, RFC_SECRET); + expect(wrapped.ciphertext.toLowerCase()).not.toContain( + Buffer.from(RFC_SECRET, 'utf8').toString('hex'), + ); + expect(unwrapTotpSecret(PASSWORD, wrapped)).toBe(RFC_SECRET); + }); + + it('returns null when the wrapping password is wrong', () => { + const wrapped = wrapTotpSecret(PASSWORD, RFC_SECRET); + expect(unwrapTotpSecret('Wrong-Password-2!', wrapped)).toBeNull(); + }); +}); + +describe('recovery codes', () => { + it('generates 8 XXXX-XXXX codes that each verify once', () => { + const codes = generateRecoveryCodes(); + expect(codes).toHaveLength(8); + expect(new Set(codes).size).toBe(8); + for (const code of codes) { + expect(code).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}$/); + } + + const hashes = codes.map(hashRecoveryCode); + const first = consumeRecoveryCode(codes[0]!, hashes); + expect(first.ok).toBe(true); + if (!first.ok) return; + expect(first.remainingHashes).toHaveLength(7); + expect(consumeRecoveryCode(codes[0]!, first.remainingHashes)).toEqual({ ok: false }); + }); +}); + +describe('totp enrollment and second factor', () => { + it('enables 2FA only after a matching TOTP code and then accepts a later code', () => { + const enrollment = beginTotpEnrollment({ + issuer: 'SnowLuma', + accountName: 'testhost', + secret: RFC_SECRET, + }); + expect(enrollment.otpauthUrl).toContain('otpauth://totp/'); + expect(enrollment.otpauthUrl).toContain('secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'); + expect(enrollment.otpauthUrl).toContain('issuer=SnowLuma'); + + expect(() => confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: '000000', + label: 'SnowLuma (testhost)', + atMs: T59_MS, + })).toThrow(/验证码/); + + const enabled = confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + expect(enabled.recoveryCodes).toHaveLength(8); + expect(enabled.state.lastUsedStep).toBe(1); + expect(enabled.state.label).toBe('SnowLuma (testhost)'); + expect(enabled.state.recoveryCodeHashes).toHaveLength(8); + + expect(verifySecondFactor({ + password: PASSWORD, + totp: T59_CODE, + state: enabled.state, + atMs: T59_MS, + })).toEqual({ ok: false }); + + const later = verifySecondFactor({ + password: PASSWORD, + totp: T1111111109_CODE, + state: enabled.state, + atMs: T1111111109_MS, + }); + expect(later.ok).toBe(true); + if (!later.ok) return; + expect(later.state.lastUsedStep).toBeGreaterThan(enabled.state.lastUsedStep); + }); + + it('accepts a recovery code at login and consumes only that hash', () => { + const enabled = confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + const used = enabled.recoveryCodes[3]!; + const result = verifySecondFactor({ + password: PASSWORD, + recoveryCode: used, + state: enabled.state, + atMs: T59_MS, + }); + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.state.recoveryCodeHashes).toHaveLength(7); + expect(verifySecondFactor({ + password: PASSWORD, + recoveryCode: used, + state: result.state, + atMs: T59_MS, + })).toEqual({ ok: false }); + }); + + it('re-wraps the TOTP secret when the password changes', () => { + const enabled = confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + const nextPassword = 'Correct-Horse-2!'; + const rewrapped = rewrapTotpSecret(PASSWORD, nextPassword, enabled.state); + expect(unwrapTotpSecret(nextPassword, rewrapped)).toBe(RFC_SECRET); + expect(unwrapTotpSecret(PASSWORD, rewrapped)).toBeNull(); + expect(verifySecondFactor({ + password: nextPassword, + totp: T1111111109_CODE, + state: rewrapped, + atMs: T1111111109_MS, + }).ok).toBe(true); + }); +}); + +describe('totp persistence', () => { + it('round-trips a valid persisted totp object for backup restore', () => { + const enabled = confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + const restored = prepareTotpStateForRestore(JSON.parse(JSON.stringify(enabled.state))); + expect(restored).toEqual(enabled.state); + }); + + it('rejects a malformed totp object on restore', () => { + expect(() => prepareTotpStateForRestore({ wrapSalt: 'zz' })).toThrow(/totp/i); + }); + + it('treats a malformed totp object as absent when loading live config', () => { + expect(parseTotpStateLenient({ wrapSalt: 'zz' })).toBeUndefined(); + expect(parseTotpStateLenient(undefined)).toBeUndefined(); + }); + + it('keeps totp on credential restore and rejects a malformed totp object', () => { + const enabled = confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + const base = { + passwordHash: 'ab'.repeat(64), + passwordSalt: 'cd'.repeat(16), + mustChangePassword: false, + generatedAt: '2026-06-18T00:00:00.000Z', + updatedAt: '2026-06-18T00:00:00.000Z', + }; + expect(prepareWebuiAuthStateForRestore({ ...base, totp: enabled.state }).totp).toEqual(enabled.state); + expect(() => prepareWebuiAuthStateForRestore({ ...base, totp: { wrapSalt: 'zz' } })).toThrow(/totp/i); + }); +}); + +describe('decideSecondFactorLogin', () => { + it('asks for TOTP when 2FA is on and the request has no second factor', () => { + const enabled = confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + expect(decideSecondFactorLogin({ + totpEnabled: true, + state: enabled.state, + password: PASSWORD, + atMs: T59_MS, + })).toEqual({ kind: 'needs-totp' }); + }); + + it('skips the second factor when 2FA is off', () => { + expect(decideSecondFactorLogin({ + totpEnabled: false, + password: PASSWORD, + totp: '000000', + atMs: T59_MS, + })).toEqual({ kind: 'ok' }); + }); +}); + +describe('regenerateRecoveryCodes', () => { + it('replaces every recovery hash after a valid TOTP', () => { + const enabled = confirmTotpEnrollment({ + password: PASSWORD, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + const oldCode = enabled.recoveryCodes[0]!; + const next = regenerateRecoveryCodes({ + password: PASSWORD, + state: enabled.state, + totp: T1111111109_CODE, + atMs: T1111111109_MS, + }); + expect(next.recoveryCodes).toHaveLength(8); + expect(next.recoveryCodes).not.toContain(oldCode); + expect(verifySecondFactor({ + password: PASSWORD, + recoveryCode: oldCode, + state: next.state, + atMs: T1111111109_MS, + })).toEqual({ ok: false }); + expect(verifySecondFactor({ + password: PASSWORD, + recoveryCode: next.recoveryCodes[0]!, + state: next.state, + atMs: T1111111109_MS, + }).ok).toBe(true); + }); +}); diff --git a/packages/mcp/package.json b/packages/mcp/package.json index d790c85d..94a36135 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.14.5", + "version": "1.14.6", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index ac14206c..be46612f 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -6172,7 +6172,7 @@ "name": "get_profile_like", "aliases": [], "summary": "获取资料点赞", - "returns": "点赞资料:uid、最近点赞时间、收藏(favoriteInfo)与点赞(voteInfo)统计。", + "returns": "点赞资料:uid、最近点赞时间、收藏与点赞统计及用户明细。", "returnsSchema": { "type": "object", "properties": { @@ -6202,7 +6202,94 @@ }, "userInfos": { "type": "array", - "description": "用户列表(恒空)" + "description": "收藏用户列表", + "items": { + "type": "object", + "properties": { + "uid": { + "type": "string", + "description": "用户 uid" + }, + "uin": { + "type": "integer", + "description": "用户 QQ 号;资料中没有有效号码时为 0" + }, + "src": { + "type": "integer", + "description": "来源类型" + }, + "latestTime": { + "type": "integer", + "description": "最近互动时间戳" + }, + "count": { + "type": "integer", + "description": "互动次数" + }, + "giftCount": { + "type": "integer", + "description": "礼物数量" + }, + "customId": { + "type": "integer", + "description": "自定义标识" + }, + "lastCharged": { + "type": "integer", + "description": "最近充能时间" + }, + "bAvailableCnt": { + "type": "integer", + "description": "可用次数" + }, + "bTodayVotedCnt": { + "type": "integer", + "description": "今日已点赞次数" + }, + "nick": { + "type": "string", + "description": "昵称" + }, + "gender": { + "type": "integer", + "description": "性别" + }, + "age": { + "type": "integer", + "description": "年龄" + }, + "isFriend": { + "type": "boolean", + "description": "是否为好友" + }, + "isvip": { + "type": "boolean", + "description": "是否为会员" + }, + "isSvip": { + "type": "boolean", + "description": "是否为超级会员" + } + }, + "required": [ + "uid", + "uin", + "src", + "latestTime", + "count", + "giftCount", + "customId", + "lastCharged", + "bAvailableCnt", + "bTodayVotedCnt", + "nick", + "gender", + "age", + "isFriend", + "isvip", + "isSvip" + ] + } } } }, @@ -6228,7 +6315,94 @@ }, "userInfos": { "type": "array", - "description": "用户列表(恒空)" + "description": "点赞用户列表", + "items": { + "type": "object", + "properties": { + "uid": { + "type": "string", + "description": "用户 uid" + }, + "uin": { + "type": "integer", + "description": "用户 QQ 号;资料中没有有效号码时为 0" + }, + "src": { + "type": "integer", + "description": "来源类型" + }, + "latestTime": { + "type": "integer", + "description": "最近互动时间戳" + }, + "count": { + "type": "integer", + "description": "互动次数" + }, + "giftCount": { + "type": "integer", + "description": "礼物数量" + }, + "customId": { + "type": "integer", + "description": "自定义标识" + }, + "lastCharged": { + "type": "integer", + "description": "最近充能时间" + }, + "bAvailableCnt": { + "type": "integer", + "description": "可用次数" + }, + "bTodayVotedCnt": { + "type": "integer", + "description": "今日已点赞次数" + }, + "nick": { + "type": "string", + "description": "昵称" + }, + "gender": { + "type": "integer", + "description": "性别" + }, + "age": { + "type": "integer", + "description": "年龄" + }, + "isFriend": { + "type": "boolean", + "description": "是否为好友" + }, + "isvip": { + "type": "boolean", + "description": "是否为会员" + }, + "isSvip": { + "type": "boolean", + "description": "是否为超级会员" + } + }, + "required": [ + "uid", + "uin", + "src", + "latestTime", + "count", + "giftCount", + "customId", + "lastCharged", + "bAvailableCnt", + "bTodayVotedCnt", + "nick", + "gender", + "age", + "isFriend", + "isvip", + "isSvip" + ] + } } } } diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index c1bd818a..62e9ca0b 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -6175,7 +6175,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_profile_like", "aliases": [], "summary": "获取资料点赞", - "returns": "点赞资料:uid、最近点赞时间、收藏(favoriteInfo)与点赞(voteInfo)统计。", + "returns": "点赞资料:uid、最近点赞时间、收藏与点赞统计及用户明细。", "returnsSchema": { "type": "object", "properties": { @@ -6205,7 +6205,94 @@ export const ACTIONS: CatalogAction[] = [ }, "userInfos": { "type": "array", - "description": "用户列表(恒空)" + "description": "收藏用户列表", + "items": { + "type": "object", + "properties": { + "uid": { + "type": "string", + "description": "用户 uid" + }, + "uin": { + "type": "integer", + "description": "用户 QQ 号;资料中没有有效号码时为 0" + }, + "src": { + "type": "integer", + "description": "来源类型" + }, + "latestTime": { + "type": "integer", + "description": "最近互动时间戳" + }, + "count": { + "type": "integer", + "description": "互动次数" + }, + "giftCount": { + "type": "integer", + "description": "礼物数量" + }, + "customId": { + "type": "integer", + "description": "自定义标识" + }, + "lastCharged": { + "type": "integer", + "description": "最近充能时间" + }, + "bAvailableCnt": { + "type": "integer", + "description": "可用次数" + }, + "bTodayVotedCnt": { + "type": "integer", + "description": "今日已点赞次数" + }, + "nick": { + "type": "string", + "description": "昵称" + }, + "gender": { + "type": "integer", + "description": "性别" + }, + "age": { + "type": "integer", + "description": "年龄" + }, + "isFriend": { + "type": "boolean", + "description": "是否为好友" + }, + "isvip": { + "type": "boolean", + "description": "是否为会员" + }, + "isSvip": { + "type": "boolean", + "description": "是否为超级会员" + } + }, + "required": [ + "uid", + "uin", + "src", + "latestTime", + "count", + "giftCount", + "customId", + "lastCharged", + "bAvailableCnt", + "bTodayVotedCnt", + "nick", + "gender", + "age", + "isFriend", + "isvip", + "isSvip" + ] + } } } }, @@ -6231,7 +6318,94 @@ export const ACTIONS: CatalogAction[] = [ }, "userInfos": { "type": "array", - "description": "用户列表(恒空)" + "description": "点赞用户列表", + "items": { + "type": "object", + "properties": { + "uid": { + "type": "string", + "description": "用户 uid" + }, + "uin": { + "type": "integer", + "description": "用户 QQ 号;资料中没有有效号码时为 0" + }, + "src": { + "type": "integer", + "description": "来源类型" + }, + "latestTime": { + "type": "integer", + "description": "最近互动时间戳" + }, + "count": { + "type": "integer", + "description": "互动次数" + }, + "giftCount": { + "type": "integer", + "description": "礼物数量" + }, + "customId": { + "type": "integer", + "description": "自定义标识" + }, + "lastCharged": { + "type": "integer", + "description": "最近充能时间" + }, + "bAvailableCnt": { + "type": "integer", + "description": "可用次数" + }, + "bTodayVotedCnt": { + "type": "integer", + "description": "今日已点赞次数" + }, + "nick": { + "type": "string", + "description": "昵称" + }, + "gender": { + "type": "integer", + "description": "性别" + }, + "age": { + "type": "integer", + "description": "年龄" + }, + "isFriend": { + "type": "boolean", + "description": "是否为好友" + }, + "isvip": { + "type": "boolean", + "description": "是否为会员" + }, + "isSvip": { + "type": "boolean", + "description": "是否为超级会员" + } + }, + "required": [ + "uid", + "uin", + "src", + "latestTime", + "count", + "giftCount", + "customId", + "lastCharged", + "bAvailableCnt", + "bTodayVotedCnt", + "nick", + "gender", + "age", + "isFriend", + "isvip", + "isSvip" + ] + } } } } diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 7f302441..f19037a3 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.14.5", + "version": "1.14.6", "private": true, "type": "module", "description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis..method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 823dda68..048a568e 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -23,6 +23,33 @@ import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id'; const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB const DOWNLOAD_FILE_TIMEOUT_MS = 60_000; +const profileLikeUserSchema = { + type: 'object', + properties: { + uid: { type: 'string', description: '用户 uid' }, + uin: { type: 'integer', description: '用户 QQ 号;资料中没有有效号码时为 0' }, + src: { type: 'integer', description: '来源类型' }, + latestTime: { type: 'integer', description: '最近互动时间戳' }, + count: { type: 'integer', description: '互动次数' }, + giftCount: { type: 'integer', description: '礼物数量' }, + customId: { type: 'integer', description: '自定义标识' }, + lastCharged: { type: 'integer', description: '最近充能时间' }, + bAvailableCnt: { type: 'integer', description: '可用次数' }, + bTodayVotedCnt: { type: 'integer', description: '今日已点赞次数' }, + nick: { type: 'string', description: '昵称' }, + gender: { type: 'integer', description: '性别' }, + age: { type: 'integer', description: '年龄' }, + isFriend: { type: 'boolean', description: '是否为好友' }, + isvip: { type: 'boolean', description: '是否为会员' }, + isSvip: { type: 'boolean', description: '是否为超级会员' }, + }, + required: [ + 'uid', 'uin', 'src', 'latestTime', 'count', 'giftCount', 'customId', + 'lastCharged', 'bAvailableCnt', 'bTodayVotedCnt', 'nick', 'gender', + 'age', 'isFriend', 'isvip', 'isSvip', + ], +}; + function essenceNumber(value: unknown, field: string): number { if (typeof value !== 'number' && (typeof value !== 'string' || !/^-?\d+$/.test(value))) { @@ -1150,7 +1177,7 @@ export const actions = [ name: 'get_profile_like', summary: '获取资料点赞', readOnly: true, - returns: '点赞资料:uid、最近点赞时间、收藏(favoriteInfo)与点赞(voteInfo)统计。', + returns: '点赞资料:uid、最近点赞时间、收藏与点赞统计及用户明细。', returnsSchema: { type: 'object', properties: { @@ -1163,7 +1190,11 @@ export const actions = [ total_count: { type: 'integer', description: '收藏总数' }, last_time: { type: 'integer', description: '最近收藏时间戳' }, today_count: { type: 'integer', description: '今日收藏数' }, - userInfos: { type: 'array', description: '用户列表(恒空)' }, + userInfos: { + type: 'array', + description: '收藏用户列表', + items: profileLikeUserSchema, + }, }, }, voteInfo: { @@ -1174,7 +1205,11 @@ export const actions = [ new_count: { type: 'integer', description: '新增点赞数' }, new_nearby_count: { type: 'integer', description: '附近的人新增点赞数' }, last_visit_time: { type: 'integer', description: '最近访问时间戳' }, - userInfos: { type: 'array', description: '用户列表(恒空)' }, + userInfos: { + type: 'array', + description: '点赞用户列表', + items: profileLikeUserSchema, + }, }, }, }, diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index fbd5db1d..f1674602 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -2,6 +2,7 @@ import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, MessageElementOf, QQEventVariant } from '@snowluma/protocol/events'; import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/video-upload'; +import { guessFileNameFromUrl } from '@snowluma/protocol/highway/utils'; import type { MessageSendResult } from '../api-handler'; import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter'; import { segmentsToRawMessage } from '../helper/cq'; @@ -978,7 +979,7 @@ export async function sendPrivateMessage( const userUid = await ensureFileTargetUid(); for (const fileEl of allFileElements) { if (fileEl.url && !fileEl.fileId) { - const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file'; + const name = fileEl.fileName || guessFileNameFromUrl(fileEl.url) || 'file'; // Upload and publish are separate here so the Action keeps the real // PbSendMsg receipt. Letting uploadPrivate publish internally discards // that receipt, which makes a reliable message_sent event impossible @@ -1109,7 +1110,7 @@ export async function sendGroupMessage( let fileId: string; if (fileEl.url && !fileEl.fileId) { // upload() already calls publish() internally — do NOT call publish() again. - const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file'; + const name = fileEl.fileName || guessFileNameFromUrl(fileEl.url) || 'file'; const result = await ref.bridge.apis.groupFile.upload(groupId, fileEl.url, name, '/', true); fileId = result.fileId ?? ''; if (!fileId) throw new Error('group file auto-upload returned no file_id'); diff --git a/packages/onebot/tests/send-group-file.test.ts b/packages/onebot/tests/send-group-file.test.ts index 4e06d459..7af24910 100644 --- a/packages/onebot/tests/send-group-file.test.ts +++ b/packages/onebot/tests/send-group-file.test.ts @@ -295,4 +295,26 @@ describe('send_group_msg with {type:"file"} segment', () => { // publish must NOT be called — upload() already handles it internally expect(publish).not.toHaveBeenCalled(); }); + + it('percent-decodes a file:// URL basename when name is omitted (#354)', async () => { + const upload = vi.fn(async () => ({ fileId: 'auto-fid', fileHash: null })); + const bridge = fakeBridge({ + apis: { + message: { sendGroup: vi.fn() }, + groupFile: { upload, publish: vi.fn() }, + } as any, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge); + + await sendGroupMessage(ctx, 12345, [{ + type: 'file', + data: { file: 'file:///D:/test/%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.xlsx' }, + }] as any, false); + + expect(upload).toHaveBeenCalledOnce(); + const [, src, name] = upload.mock.calls[0]!; + expect(src).toBe('file:///D:/test/%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.xlsx'); + expect(name).toBe('测试文件.xlsx'); + }); }); diff --git a/packages/onebot/tests/send-private-c2c-file.test.ts b/packages/onebot/tests/send-private-c2c-file.test.ts index e3b2d6f8..63f217ef 100644 --- a/packages/onebot/tests/send-private-c2c-file.test.ts +++ b/packages/onebot/tests/send-private-c2c-file.test.ts @@ -336,4 +336,41 @@ describe('send_private_msg with {type:"file"} segment', () => { ); expect(sendC2cFile).toHaveBeenCalledOnce(); }); + + it('percent-decodes a file:// URL basename when name is omitted (#354)', async () => { + const uploadPrivate = vi.fn(async () => ({ fileId: 'auto-fid', fileHash: 'auto-hash' })); + const sendC2cFileMessage = vi.fn(async () => goodReceipt); + const bridge = fakeBridge({ + apis: { + message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage }, + groupFile: { uploadPrivate }, + } as any, + resolveUserUid: vi.fn(async () => 'u_peer'), + recallUploadedFile: vi.fn(() => ({ + fileId: 'auto-fid', + scope: 'private', + userId: 67890, + fileName: '测试文件.xlsx', + fileSize: 3, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + fileHash: 'auto-hash', + rememberedAt: Date.now(), + })), + } as any); + const ctx = makeCtx(bridge); + + await sendPrivateMessage(ctx, 67890, [{ + type: 'file', + data: { file: 'file:///D:/test/%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.xlsx' }, + }] as any, false); + + expect(uploadPrivate).toHaveBeenCalledWith( + 67890, + 'file:///D:/test/%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.xlsx', + '测试文件.xlsx', + true, + false, + ); + }); }); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index ad406d7f..37e47fed 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.14.5", + "version": "1.14.6", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).", diff --git a/packages/proto-defs/src/oidb-actions/base.ts b/packages/proto-defs/src/oidb-actions/base.ts index a0163c4f..cf9c029b 100644 --- a/packages/proto-defs/src/oidb-actions/base.ts +++ b/packages/proto-defs/src/oidb-actions/base.ts @@ -352,7 +352,9 @@ export interface OidbGroupDetailFlags { question?: pb<24, bool>; answer?: pb<25, string>; maxAdminCount?: pb<29, string>; - shutUpAllTimestamp?: pb<59, bool>; + // Official request mask for group shutup expire (proto tag 45 → 60027). + // Lagrange's tag 59 requests 60259, which is a different field. + shutUpAllTimestamp?: pb<45, bool>; /** Current complete app privilege bitfield; needed for masked mutations. */ privilegeFlag?: pb<99, bool>; /** Current complete groupFlagExt4 bitfield; needed for masked mutations. */ @@ -539,28 +541,55 @@ export interface OidbSetProfile { stringProfiles?: pb_repeated<2, OidbProfileStringItem>; intProfiles?: pb_repeated<3, OidbProfileIntItem>; } -export interface Oidb0x7edInteraction { +export interface Oidb0x7edUserInfo { + uid?: pb<1, string>; + src?: pb<2, uint_32>; + latestTime?: pb<3, uint_32>; + count?: pb<4, uint_32>; + giftCount?: pb<5, uint_32>; + customId?: pb<6, uint_32>; + lastCharged?: pb<8, uint_32>; + availableCount?: pb<21, uint_32>; + todayVotedCount?: pb<22, uint_32>; + nick?: pb<101, string>; + gender?: pb<102, uint_32>; + age?: pb<103, uint_32>; + isFriend?: pb<104, bool>; + isVip?: pb<105, bool>; + isSvip?: pb<106, bool>; +} +export interface Oidb0x7edFavoriteInfo { totalCount?: pb<1, uint_32>; - newCount?: pb<2, uint_32>; + lastTime?: pb<2, uint_32>; todayCount?: pb<3, uint_32>; - lastTime?: pb<4, uint_64>; + userInfos?: pb_repeated<4, Oidb0x7edUserInfo>; +} +export interface Oidb0x7edVoteInfo { + totalCount?: pb<1, uint_32>; + newCount?: pb<2, uint_32>; + newNearbyCount?: pb<3, uint_32>; + lastVisitTime?: pb<4, uint_32>; + userInfos?: pb_repeated<5, Oidb0x7edUserInfo>; } export interface Oidb0x7edUserLikeInfo { uid?: pb<1, string>; - time?: pb<2, uint_64>; - favoriteInfo?: pb<3, Oidb0x7edInteraction>; - voteInfo?: pb<4, Oidb0x7edInteraction>; + time?: pb<2, uint_32>; + favoriteInfo?: pb<3, Oidb0x7edFavoriteInfo>; + voteInfo?: pb<4, Oidb0x7edVoteInfo>; } export interface Oidb0x7edReq { - targetUid?: pb<1, string>; - basic?: pb<2, uint_32>; - vote?: pb<3, uint_32>; - favorite?: pb<4, uint_32>; - start?: pb<12, uint_32>; - limit?: pb<103, uint_32>; + targetUids?: pb_repeated<1, string>; + basic?: pb<2, uint_32>; + vote?: pb<3, uint_32>; + favorite?: pb<4, uint_32>; + userProfile?: pb<101, uint_32>; + start?: pb<102, uint_32>; + limit?: pb<103, uint_32>; } export interface Oidb0x7edResp { userLikeInfos?: pb_repeated<1, Oidb0x7edUserLikeInfo>; + friendMaxVotes?: pb<2, uint_32>; + start?: pb<101, int_32>; } export interface Oidb0x8a7Req { basic1?: pb<1, uint_32>; diff --git a/packages/proto-defs/src/oidb.ts b/packages/proto-defs/src/oidb.ts index f2065315..856564a2 100644 --- a/packages/proto-defs/src/oidb.ts +++ b/packages/proto-defs/src/oidb.ts @@ -82,7 +82,10 @@ export interface OidbSvcTrpcTcp0xFE5_2GroupInfo { description?: pb<18, string>; question?: pb<19, string>; announcement?: pb<30, string>; - shutUpAllTimestamp?: pb<31, uint_32>; + // wrapper.node 3.2.32 group_codec.cc DecodeGroupInfo: tag 10 → internal + // 60027 (JS groupShutupExpireTime). Tag 31 is 60259, not the mute expire. + // 0 = off, 0xFFFFFFFF = permanent, otherwise unix-seconds expire. + shutUpAllTimestamp?: pb<10, uint_32>; } export interface OidbSvcTrpcTcp0xFE5_2CustomInfo { @@ -116,7 +119,10 @@ export interface OidbSvcTrpcTcp0x88D_0Results { question?: pb<24, string>; answer?: pb<25, string>; maxAdminCount?: pb<29, uint_64>; - shutUpAllTimestamp?: pb<59, uint_32>; + // wrapper.node 3.2.32 group_info_fetch_codec.cc + // DecodeSingleGroupDetailInfoByBaseFilter: tag 45 → internal 60027. + // Tag 59 is 60259, not the mute expire. Request mask tag is also 45. + shutUpAllTimestamp?: pb<45, uint_32>; /** Complete app privilege bitfield (requested with detail flag tag 99). */ privilegeFlag?: pb<99, uint_32>; /** Complete groupFlagExt4 bitfield (requested with detail flag tag 101). */ diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 8fede30c..b7be0f42 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.14.5", + "version": "1.14.6", "private": true, "type": "module", "description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/protocol/'`.", diff --git a/packages/protocol/src/highway/highway-client.ts b/packages/protocol/src/highway/highway-client.ts index 0650d444..9cca0d72 100644 --- a/packages/protocol/src/highway/highway-client.ts +++ b/packages/protocol/src/highway/highway-client.ts @@ -28,10 +28,20 @@ const HIGHWAY_BLOCK_SIZE = 1024 * 1024; // one-shot TCP connections; QQ's highway edge nodes (and proxies/NAT on the // path) sporadically FIN a fresh connection before responding, so a single // transient close among a 48 MB file's ~48 chunks must not abort the whole -// upload (issue #118). Only transport failures retry — a decoded highway -// error_code is a definitive server reject and is never retried. +// upload (issue #118). Transport failures retry. Most decoded highway +// error_codes are definitive rejects and are never retried — except +// 102902 / 302902, which QQ's own BDH client treats as NeedDelayRetry +// (issue #352; wrapper.node multi_uploader.cc). const HIGHWAY_MAX_CHUNK_ATTEMPTS = 3; const HIGHWAY_RETRY_BASE_MS = 300; +const HIGHWAY_DELAY_RETRY_CODES = new Set([102902, 302902]); +// Official DelayTryNext clamps server uDelayTime to [250, 1200] ms and +// gives up after 33 consecutive delay-retries. We don't currently parse +// uDelayTime out of the highway response, so use the 250 ms floor; 8 +// consecutive delay-retries is enough to ride out the backpressure that +// #352 hits on multi-GiB PUTs without stalling a chunk for ~8 s. +const HIGHWAY_DELAY_RETRY_MS = 250; +const HIGHWAY_MAX_DELAY_RETRIES = 8; // Idle read timeout for a highway response. tcpConnect() clears the socket's // own timeout once connected, so a peer that accepts the connection but then @@ -165,10 +175,11 @@ export function fetchHighwaySession(bridge: BridgeContext): Promise({ msgBaseHead: { - version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0, + version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes, appId: HIGHWAY_APP_ID, dataFlag: 16, commandId, }, msgSegHead: { @@ -482,10 +493,11 @@ async function uploadHighwayHttpOperation( // // Blocks are PUT in STRICT offset order over ONE persistent connection, // reused across chunks via HTTP keep-alive. Two properties matter: - // - In order: QQ's highway server reassembles by offset but REJECTS a - // block that arrives after a later one (error_code=102902) — parallel or - // out-of-order PUTs do not work (proven on a real endpoint). Sequential - // send guarantees in-order arrival. + // - In order: QQ's highway server wants blocks in offset order. Parallel + // PUTs were observed to return error_code=102902 (~20% on a live + // account). That code is NeedDelayRetry in the official BDH client, + // not a fatal "out of order" reject — but sequential send still keeps + // the server from having to delay-retry overlapping pieces. // - One warm connection: reusing the socket keeps the TCP congestion // window open across the whole file instead of paying slow-start on a // fresh connection for every 1 MiB block. That per-block cold start was @@ -497,10 +509,13 @@ async function uploadHighwayHttpOperation( // half-closed after a response, we drop it, reconnect, and re-send the SAME // block (re-PUTting an offset is idempotent). Worst case — a server that // closes after every response — degrades to one connection per block: no - // worse than the #118 behavior, and still strictly in order (so never - // error_code=102902). `connectCount` is logged so a real run reveals which - // regime we hit (1 connection = keep-alive honored; ~chunkCount = closed - // every time). + // worse than the #118 behavior, and still strictly in order. + // + // 102902 / 302902 are a separate recovery path (issue #352): drop the + // socket (official client switches sender IP), wait DelayTryNext's 250 ms + // floor, and re-PUT the same offset. `connectCount` is logged so a real + // run reveals which regime we hit (1 connection = keep-alive honored; + // ~chunkCount = closed every time). // // `source` may buffer the whole file (BufferChunkSource) or stream it from // disk (FileChunkSource); either way one chunk is read/held at a time. We @@ -526,25 +541,41 @@ async function uploadHighwayHttpOperation( } log.trace('highway_put_branch branch=chunk_read offset=%d bytes=%d', offset, chunkSize); const chunkMd5 = computeMd5(chunk); - const head = makeHighwayHead( - bridge.identity.uin, commandId, totalSize, offset, chunkSize, - chunkMd5, fileMd5, session.sigSession, extend, - ); - log.trace(() => [ - 'highway_put_branch branch=chunk_control_request offset=%d bytes=%d headBytes=%d headHex=%s', - offset, - chunkSize, - head.byteLength, - renderTraceBytes(head), - ]); - const frame = packHighwayFrame(head, chunk); + const rejectServer = (errorCode: number, segRetCode: number): never => { + const fileMd5Hex = Buffer.from(fileMd5).toString('hex'); + trace.failureReason = 'server_rejected'; + trace.error = new Error( + `highway upload error_code=${errorCode}` + + ` (cmdId=${commandId} chunk=${chunkSize}/${totalSize}` + + ` offset=${offset} segRetCode=${segRetCode}` + + ` fileMd5=${fileMd5Hex.slice(0, 16)}…)`, + ); + throw trace.error; + }; // Send this block, reusing the live connection when there is one. On any // transport failure (peer FIN between chunks, ECONNRESET, connect // refused/timeout) drop the socket, reconnect, and retry THIS block — // re-sending the same offset range is idempotent on the server. + // 102902 / 302902 take a separate delay-retry path (issue #352). let responseBody: Uint8Array | undefined; - for (let attempt = 1; ; attempt++) { + let transportAttempts = 0; + let delayRetries = 0; + for (;;) { + const retryTimes = transportAttempts + delayRetries; + const attempt = retryTimes + 1; + const head = makeHighwayHead( + bridge.identity.uin, commandId, totalSize, offset, chunkSize, + chunkMd5, fileMd5, session.sigSession, extend, retryTimes, + ); + log.trace(() => [ + 'highway_put_branch branch=chunk_control_request offset=%d bytes=%d headBytes=%d headHex=%s', + offset, + chunkSize, + head.byteLength, + renderTraceBytes(head), + ]); + const frame = packHighwayFrame(head, chunk); try { if (!socket) { socket = await tcpConnect(session.host, session.port); @@ -566,7 +597,6 @@ async function uploadHighwayHttpOperation( connectCount, ); responseBody = await httpPostFrame(socket, session.host, pathStr, frame); - break; } catch (err) { if (err instanceof HighwayResponseReadError && err.responseBody) { log.trace(() => [ @@ -578,10 +608,11 @@ async function uploadHighwayHttpOperation( ]); } dropSocket(); - if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { + transportAttempts += 1; + if (transportAttempts >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { trace.failureReason = 'transport_exhausted'; const exhausted = new Error( - `highway upload transport failed after ${attempt} attempts ` + + `highway upload transport failed after ${transportAttempts} attempts ` + `(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}): ${String(err)}`, ); trace.error = exhausted; @@ -591,59 +622,72 @@ async function uploadHighwayHttpOperation( 'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d error=%j', offset, chunkSize, - attempt, + transportAttempts, highwayErrorText(err), ); - await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt); + await sleepMs(HIGHWAY_RETRY_BASE_MS * transportAttempts); + continue; } - } - // Unreachable: the retry loop only exits via break (responseBody set) or - // throw — the guard just narrows the type for the compiler. - if (!responseBody) { - trace.failureReason = 'transport_exhausted'; - trace.error = new Error('highway upload: missing response'); - throw trace.error; - } - log.trace(() => [ - 'highway_put_branch branch=chunk_control_response offset=%d bytes=%d responseBytes=%d responseHex=%s', - offset, - chunkSize, - responseBody.byteLength, - renderTraceBytes(responseBody), - ]); - let resp: RespDataHighwayHead; - try { - const { head: respHead } = unpackHighwayFrame(responseBody); - resp = protobuf_decode(respHead); - log.trace( - 'highway_put_branch branch=chunk_control_decoded offset=%d errorCode=%d segRetCode=%d', + // Unreachable: httpPostFrame either returns a body or throws. + if (!responseBody) { + trace.failureReason = 'transport_exhausted'; + trace.error = new Error('highway upload: missing response'); + throw trace.error; + } + const body = responseBody; + log.trace(() => [ + 'highway_put_branch branch=chunk_control_response offset=%d bytes=%d responseBytes=%d responseHex=%s', offset, - resp?.errorCode ?? 0, - resp?.msgSegHead?.retCode ?? 0, - ); - } catch (error) { - trace.failureReason = 'control_decode_failed'; - trace.error = error; - throw error; - } - if (resp?.errorCode && resp.errorCode !== 0) { - // Surface every diagnostic the highway response carries so - // user reports of `error_code=921` and friends include the - // server-side context (segHead.retCode, chunk size, file md5) - // — without these we can't tell apart a malformed-payload - // reject, a session-ticket mismatch, or a per-account rate- - // limit. - const segRetCode = resp.msgSegHead?.retCode ?? 0; - const fileMd5Hex = Buffer.from(fileMd5).toString('hex'); - trace.failureReason = 'server_rejected'; - trace.error = new Error( - `highway upload error_code=${resp.errorCode}` + - ` (cmdId=${commandId} chunk=${chunkSize}/${totalSize}` + - ` offset=${offset} segRetCode=${segRetCode}` + - ` fileMd5=${fileMd5Hex.slice(0, 16)}…)`, - ); - throw trace.error; + chunkSize, + body.byteLength, + renderTraceBytes(body), + ]); + let resp: RespDataHighwayHead; + try { + const { head: respHead } = unpackHighwayFrame(body); + resp = protobuf_decode(respHead); + log.trace( + 'highway_put_branch branch=chunk_control_decoded offset=%d errorCode=%d segRetCode=%d', + offset, + resp?.errorCode ?? 0, + resp?.msgSegHead?.retCode ?? 0, + ); + } catch (error) { + trace.failureReason = 'control_decode_failed'; + trace.error = error; + throw error; + } + + const errorCode = resp?.errorCode ?? 0; + const segRetCode = resp?.msgSegHead?.retCode ?? 0; + if (errorCode !== 0 && HIGHWAY_DELAY_RETRY_CODES.has(errorCode)) { + dropSocket(); + delayRetries += 1; + if (delayRetries >= HIGHWAY_MAX_DELAY_RETRIES) { + rejectServer(errorCode, segRetCode); + } + log.trace( + 'highway_put_branch branch=chunk_delay_retry offset=%d bytes=%d attempt=%d errorCode=%d delayMs=%d', + offset, + chunkSize, + delayRetries, + errorCode, + HIGHWAY_DELAY_RETRY_MS, + ); + await sleepMs(HIGHWAY_DELAY_RETRY_MS); + continue; + } + if (errorCode !== 0) { + // Surface every diagnostic the highway response carries so + // user reports of `error_code=921` and friends include the + // server-side context (segHead.retCode, chunk size, file md5) + // — without these we can't tell apart a malformed-payload + // reject, a session-ticket mismatch, or a per-account rate- + // limit. + rejectServer(errorCode, segRetCode); + } + break; } // If the peer half-closed after sending its response, the socket can no diff --git a/packages/protocol/src/highway/utils.ts b/packages/protocol/src/highway/utils.ts index 9e785085..bb4a91b2 100644 --- a/packages/protocol/src/highway/utils.ts +++ b/packages/protocol/src/highway/utils.ts @@ -252,11 +252,17 @@ export async function loadBinarySource( return { bytes, fileName }; } -function guessFileNameFromUrl(url: string): string { +export function guessFileNameFromUrl(url: string): string { const queryPos = url.search(/[?#]/); const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url; const lastSlash = pathPart.lastIndexOf('/'); - return lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : ''; + const raw = lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : ''; + if (!raw) return ''; + try { + return decodeURIComponent(raw); + } catch { + return raw; + } } // --- Hashing --- diff --git a/packages/protocol/src/oidb-service.ts b/packages/protocol/src/oidb-service.ts index 98667ce1..5a3f1de7 100644 --- a/packages/protocol/src/oidb-service.ts +++ b/packages/protocol/src/oidb-service.ts @@ -53,12 +53,13 @@ export interface OidbSender { * `Pick` slices the cmd actually needs. * * One of `subCommand` (static) or `resolveSubCommand` (dynamic from - * params) must be present. `resolveSubCommand` wins if both are given. + * params and context) must be present. `resolveSubCommand` wins if both + * are given. */ export interface OidbCallSpec { command: number; subCommand?: number; - resolveSubCommand?(params: TParams): number; + resolveSubCommand?(params: TParams, ctx: TCtx): number; /** Set OIDB envelope `reserved = 1` (UIN-form variant, see makeOidbEnvelope's isUid). */ uinForm?: boolean; /** Override the default `OidbSvcTrpcTcp.0xNNNN_N` wire name. A few @@ -107,7 +108,7 @@ export async function invokeOidb { const subCommand = spec.resolveSubCommand - ? spec.resolveSubCommand(params) + ? spec.resolveSubCommand(params, ctx) : spec.subCommand!; const reqBody = await spec.serialize(ctx, params); const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false); @@ -163,7 +164,7 @@ export async function buildOidbRequest { const subCommand = spec.resolveSubCommand - ? spec.resolveSubCommand(params) + ? spec.resolveSubCommand(params, ctx) : spec.subCommand!; const reqBody = await spec.serialize(ctx, params); const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false); diff --git a/packages/protocol/src/oidb-services/contacts/fetch-group-detail.ts b/packages/protocol/src/oidb-services/contacts/fetch-group-detail.ts index 5675e4df..bfd18c57 100644 --- a/packages/protocol/src/oidb-services/contacts/fetch-group-detail.ts +++ b/packages/protocol/src/oidb-services/contacts/fetch-group-detail.ts @@ -4,9 +4,8 @@ // including ones the bot hasn't joined — used to put a name on a group invite // (where the invite push itself carries no group name). The `flags` block is a // request mask: a present bool(true)/string("") asks the server to include that -// field in the response. Cross-checked against -// dev/Lagrange.Core/.../GetGroupInfoService.cs — note it builds the envelope -// with isUid=false, i.e. reserved=0 (NO uinForm), unlike the 0xFE5_2 list query. +// field in the response. Envelope is reserved=0 (NO uinForm), unlike 0xFE5_2. +// Mute expire request/response tag is 45 (official 60027), not Lagrange's 59. import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase, OidbSvcTrpcTcp0x88D_0Response } from '@snowluma/proto-defs/oidb'; @@ -33,6 +32,7 @@ export namespace FetchGroupDetail { ownerUid: on, createTime: on, maxMemberCount: on, memberCount: on, level: on, name: '', noticePreview: '', uin: on, lastSequence: on, lastMessageTime: on, question: on, answer: '', maxAdminCount: '', + // Tag 45 (not Lagrange's 59): official request mask for 60027. shutUpAllTimestamp: on, privilegeFlag: on, groupFlagExt4: on, }, }, diff --git a/packages/protocol/src/oidb-services/profile/get-like.ts b/packages/protocol/src/oidb-services/profile/get-like.ts index 9f273753..84ef4163 100644 --- a/packages/protocol/src/oidb-services/profile/get-like.ts +++ b/packages/protocol/src/oidb-services/profile/get-like.ts @@ -1,15 +1,40 @@ -// 0x7ED_12 — fetch QQ "thumbs up" (赞) summary for self or another user. +// 0x7ED_12 / 0x7ED_13 — fetch QQ "thumbs up" (赞) details for another +// user / self respectively. // // Self lookup needs the bot's own UID, hence the `identity` dependency. // For other users we use `resolveUserUid` to translate the uin first. import type { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { Oidb0x7edReq, Oidb0x7edResp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { + Oidb0x7edReq, + Oidb0x7edResp, + Oidb0x7edUserInfo, +} from '@snowluma/proto-defs/oidb-actions/base'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../../bridge-context'; import { invokeOidb, type OidbSender } from '../../oidb-service'; import { resolveSelfUid } from '../../self-uid'; +export interface ProfileLikeUserInfo { + [key: string]: import('@snowluma/common/json').JsonValue; + uid: string; + uin: number; + src: number; + latestTime: number; + count: number; + giftCount: number; + customId: number; + lastCharged: number; + bAvailableCnt: number; + bTodayVotedCnt: number; + nick: string; + gender: number; + age: number; + isFriend: boolean; + isvip: boolean; + isSvip: boolean; +} + export interface LikeInfo { [key: string]: import('@snowluma/common/json').JsonValue; uid: string; @@ -19,7 +44,7 @@ export interface LikeInfo { total_count: number; last_time: number; today_count: number; - userInfos: never[]; + userInfos: ProfileLikeUserInfo[]; }; voteInfo: { [key: string]: import('@snowluma/common/json').JsonValue; @@ -27,13 +52,38 @@ export interface LikeInfo { new_count: number; new_nearby_count: number; last_visit_time: number; - userInfos: never[]; + userInfos: ProfileLikeUserInfo[]; + }; +} + +function deserializeUserInfo( + ctx: GetLike.Deps, + data: Oidb0x7edUserInfo, +): ProfileLikeUserInfo { + const uid = data.uid; + if (!uid) throw new Error('get profile like user uid missing'); + return { + uid, + uin: ctx.identity.findUinByUid(uid) ?? 0, + src: data.src ?? 0, + latestTime: data.latestTime ?? 0, + count: data.count ?? 0, + giftCount: data.giftCount ?? 0, + customId: data.customId ?? 0, + lastCharged: data.lastCharged ?? 0, + bAvailableCnt: data.availableCount ?? 0, + bTodayVotedCnt: data.todayVotedCount ?? 0, + nick: data.nick ?? '', + gender: data.gender ?? 0, + age: data.age ?? 0, + isFriend: data.isFriend ?? false, + isvip: data.isVip ?? false, + isSvip: data.isSvip ?? false, }; } export namespace GetLike { export const command = 0x7ED; - export const subCommand = 12; export interface Params { /** Omit / 0 → query self. */ @@ -44,39 +94,48 @@ export namespace GetLike { export type Deps = OidbSender & Pick; + const isSelfQuery = (ctx: Deps, p: Params): boolean => + !p.userId || p.userId === Number(ctx.identity.uin); + + export const resolveSubCommand = (p: Params, ctx: Deps): number => + isSelfQuery(ctx, p) ? 13 : 12; + export const serialize = async (ctx: Deps, p: Params): Promise => { - const targetUid = p.userId - ? await ctx.resolveUserUid(p.userId) - : await resolveSelfUid(ctx); + const targetUid = isSelfQuery(ctx, p) + ? await resolveSelfUid(ctx) + : await ctx.resolveUserUid(p.userId!); if (!targetUid) throw new Error('target uid not found'); return { - targetUid, + targetUids: [targetUid], basic: 1, vote: 1, - favorite: 1, + favorite: 0, + userProfile: 1, start: p.start ?? 0, limit: p.limit ?? 10, }; }; - export const deserialize = (_ctx: Deps, body: Oidb0x7edResp): LikeInfo => { + export const deserialize = (ctx: Deps, body: Oidb0x7edResp): LikeInfo => { const data = body.userLikeInfos?.[0]; if (!data) throw new Error('get profile like info empty'); return { uid: data.uid ?? '', time: Number(data.time ?? 0), favoriteInfo: { - total_count: data.favoriteInfo?.totalCount || 0, - last_time: Number(data.favoriteInfo?.lastTime || 0), - today_count: data.favoriteInfo?.newCount || 0, - userInfos: [], + total_count: data.favoriteInfo?.totalCount ?? 0, + last_time: data.favoriteInfo?.lastTime ?? 0, + today_count: data.favoriteInfo?.todayCount ?? 0, + userInfos: (data.favoriteInfo?.userInfos ?? []) + .map(user => deserializeUserInfo(ctx, user)), }, voteInfo: { - total_count: data.voteInfo?.totalCount || 0, - new_count: data.voteInfo?.newCount || 0, - new_nearby_count: 0, - last_visit_time: Number(data.voteInfo?.lastTime || 0), - userInfos: [], + total_count: data.voteInfo?.totalCount ?? 0, + new_count: data.voteInfo?.newCount ?? 0, + new_nearby_count: data.voteInfo?.newNearbyCount ?? 0, + last_visit_time: data.voteInfo?.lastVisitTime ?? 0, + userInfos: (data.voteInfo?.userInfos ?? []) + .map(user => deserializeUserInfo(ctx, user)), }, }; }; diff --git a/packages/protocol/src/qq-info.ts b/packages/protocol/src/qq-info.ts index 3e944d0e..e7ff78b9 100644 --- a/packages/protocol/src/qq-info.ts +++ b/packages/protocol/src/qq-info.ts @@ -57,7 +57,7 @@ export interface QQGroupInfo { level?: number; /** Group memo / announcement preview. '' when unknown (#197). */ memo?: string; - /** Whether the group currently has group-wide mute enabled. */ + /** Whether group-wide mute is currently in effect (expire still in the future). */ allMuted?: boolean; } diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-group-detail.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-group-detail.test.ts index 637df9b9..0065c2b8 100644 --- a/packages/protocol/tests/oidb-services/contacts/fetch-group-detail.test.ts +++ b/packages/protocol/tests/oidb-services/contacts/fetch-group-detail.test.ts @@ -18,7 +18,8 @@ import { FetchGroupDetail } from '../../../src/oidb-services/contacts/fetch-grou interface GroupDetailResultsFixture { name?: pb<15, string>; - shutUpAllTimestamp?: pb<59, uint_32>; + shutUpAllTimestamp?: pb<45, uint_32>; + leftover59?: pb<59, uint_32>; privilegeFlag?: pb<99, uint_32>; groupFlagExt4?: pb<101, uint_32>; } @@ -116,6 +117,28 @@ describe('FetchGroupDetail namespace', () => { expect(out.groupInfo?.results?.shutUpAllTimestamp).toBe(4_294_967_295); }); + it('does not treat 0x88D results tag 59 as the mute expire (#356)', async () => { + const responseData = Buffer.from(protobuf_encode>({ + body: { + groupInfo: { + uin: 601692726n, + results: { name: 'Unmuted Group', leftover59: 4_294_967_295 }, + }, + }, + })); + const sender = makeSender(); + sender.sendRawPacket.mockResolvedValue({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData, + }); + + const out = await FetchGroupDetail.invoke(sender, { groupUin: 601692726 }); + expect(out.groupInfo?.results?.shutUpAllTimestamp ?? undefined).toBeUndefined(); + }); + it('decodes the complete privilege flag used by masked group mutations', async () => { const responseData = Buffer.from(protobuf_encode>({ body: { diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts index 492cff83..e9c2ea02 100644 --- a/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts +++ b/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts @@ -14,7 +14,8 @@ import { FetchGroupList } from '../../../src/oidb-services/contacts/fetch-group- interface GroupInfoFixture { groupName?: pb<5, string>; - shutUpAllTimestamp?: pb<31, uint_32>; + shutUpAllTimestamp?: pb<10, uint_32>; + leftover31?: pb<31, uint_32>; } interface GroupFixture { @@ -55,7 +56,7 @@ describe('FetchGroupList namespace', () => { const env = protobuf_decode>(bytes); expect(env.body?.config?.config1?.groupName).toBe(true); expect(env.body?.config?.config1?.memberCount).toBe(true); - expect(env.body?.config?.config1?.field31).toBe(true); + expect(env.body?.config?.config1?.field10).toBe(true); expect(env.body?.config?.config2?.remark).toBe(true); for (const field of ['field1', 'field2', 'field4', 'field5', 'field6', 'field7', 'field8'] as const) { expect(env.body?.config?.config2?.[field] ?? false, field).toBe(false); @@ -87,5 +88,28 @@ describe('FetchGroupList namespace', () => { expect(out.groups?.[0]?.info?.shutUpAllTimestamp).toBe(4_294_967_295); }); + + it('does not treat 0xFE5 info tag 31 as the mute expire (#356)', async () => { + const responseData = Buffer.from(protobuf_encode>({ + body: { + groups: [{ + groupUin: 123456789, + info: { groupName: 'Unmuted Group', leftover31: 4_294_967_295 }, + }], + }, + })); + const sender = makeSender(); + sender.sendRawPacket.mockResolvedValue({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData, + }); + + const out = await FetchGroupList.invoke(sender); + + expect(out.groups?.[0]?.info?.shutUpAllTimestamp ?? undefined).toBeUndefined(); + }); }); }); diff --git a/packages/protocol/tests/oidb-services/profile/get-like.test.ts b/packages/protocol/tests/oidb-services/profile/get-like.test.ts index 6d14c7f5..d394d8f0 100644 --- a/packages/protocol/tests/oidb-services/profile/get-like.test.ts +++ b/packages/protocol/tests/oidb-services/profile/get-like.test.ts @@ -9,6 +9,7 @@ import { GetLike } from '../../../src/oidb-services/profile/get-like'; function makeDeps(opts: { cachedSelfUid?: string | null; resolveUserUid?: (uin: number) => Promise; + findUinByUid?: (uid: string) => number | null; responseBody?: Oidb0x7edResp; } = {}) { const responseData = opts.responseBody !== undefined @@ -17,35 +18,44 @@ function makeDeps(opts: { const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; return { sendRawPacket: vi.fn(async () => r), - identity: { uin: '10001', selfUid: opts.cachedSelfUid ?? null } as any, + identity: { + uin: '10001', + selfUid: opts.cachedSelfUid ?? null, + findUinByUid: vi.fn(opts.findUinByUid ?? (() => null)), + } as any, resolveUserUid: vi.fn(opts.resolveUserUid ?? (async (uin: number) => `uid-of-${uin}`)), }; } describe('GetLike namespace', () => { - it('declares 0x7ED_12', () => { + it('uses the self and other-user subcommands selected by the native client', () => { + const deps = makeDeps({ cachedSelfUid: 'self-uid' }); expect(GetLike.command).toBe(0x7ED); - expect(GetLike.subCommand).toBe(12); + expect(GetLike.resolveSubCommand({}, deps)).toBe(13); + expect(GetLike.resolveSubCommand({ userId: 0 }, deps)).toBe(13); + expect(GetLike.resolveSubCommand({ userId: 10001 }, deps)).toBe(13); + expect(GetLike.resolveSubCommand({ userId: 20002 }, deps)).toBe(12); }); describe('invoke (target uid resolution)', () => { it('uses cached self uid when userId is omitted', async () => { const deps = makeDeps({ cachedSelfUid: 'cached-self', - responseBody: { userLikeInfos: [{ uid: 'cached-self', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + responseBody: { userLikeInfos: [{ uid: 'cached-self', time: 0, favoriteInfo: {}, voteInfo: {} }] }, }); await GetLike.invoke(deps, {}); expect(deps.resolveUserUid).not.toHaveBeenCalled(); - const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const [serviceCmd, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(serviceCmd).toBe('OidbSvcTrpcTcp.0x7ed_13'); const env = protobuf_decode>(bytes); - expect(env.body?.targetUid).toBe('cached-self'); + expect(env.body?.targetUids).toEqual(['cached-self']); }); it('falls back to resolveUserUid for self when cache is empty', async () => { const deps = makeDeps({ cachedSelfUid: null, resolveUserUid: vi.fn(async () => 'fresh-self') as any, - responseBody: { userLikeInfos: [{ uid: 'fresh-self', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + responseBody: { userLikeInfos: [{ uid: 'fresh-self', time: 0, favoriteInfo: {}, voteInfo: {} }] }, }); await GetLike.invoke(deps, {}); expect(deps.resolveUserUid).toHaveBeenCalledWith(10001); @@ -53,10 +63,21 @@ describe('GetLike namespace', () => { it('resolves other users via resolveUserUid', async () => { const deps = makeDeps({ - responseBody: { userLikeInfos: [{ uid: 'uid-of-99999', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + responseBody: { userLikeInfos: [{ uid: 'uid-of-99999', time: 0, favoriteInfo: {}, voteInfo: {} }] }, }); await GetLike.invoke(deps, { userId: 99999 }); expect(deps.resolveUserUid).toHaveBeenCalledWith(99999); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x7ed_12'); + }); + + it('treats an explicit self uin as a self query', async () => { + const deps = makeDeps({ + cachedSelfUid: 'cached-self', + responseBody: { userLikeInfos: [{ uid: 'cached-self', time: 0 }] }, + }); + await GetLike.invoke(deps, { userId: 10001 }); + expect(deps.resolveUserUid).not.toHaveBeenCalled(); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x7ed_13'); }); it('throws when self uin is invalid and cache is empty', async () => { @@ -67,21 +88,22 @@ describe('GetLike namespace', () => { }); describe('serialize', () => { - it('always sets basic=1, vote=1, favorite=1 (full breakdown query)', async () => { + it('requests the profile-backed vote list', async () => { const deps = makeDeps({ - responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + responseBody: { userLikeInfos: [{ uid: 'u', time: 0, favoriteInfo: {}, voteInfo: {} }] }, }); await GetLike.invoke(deps, { userId: 1 }); const [, bytes] = deps.sendRawPacket.mock.calls[0]!; const env = protobuf_decode>(bytes); expect(env.body?.basic).toBe(1); expect(env.body?.vote).toBe(1); - expect(env.body?.favorite).toBe(1); + expect(env.body?.favorite ?? 0).toBe(0); + expect(env.body?.userProfile).toBe(1); }); it('threads start / limit through to the request', async () => { const deps = makeDeps({ - responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + responseBody: { userLikeInfos: [{ uid: 'u', time: 0, favoriteInfo: {}, voteInfo: {} }] }, }); await GetLike.invoke(deps, { userId: 1, start: 5, limit: 50 }); const [, bytes] = deps.sendRawPacket.mock.calls[0]!; @@ -92,7 +114,7 @@ describe('GetLike namespace', () => { it('defaults start=0 / limit=10', async () => { const deps = makeDeps({ - responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + responseBody: { userLikeInfos: [{ uid: 'u', time: 0, favoriteInfo: {}, voteInfo: {} }] }, }); await GetLike.invoke(deps, { userId: 1 }); const [, bytes] = deps.sendRawPacket.mock.calls[0]!; @@ -104,20 +126,74 @@ describe('GetLike namespace', () => { describe('deserialize', () => { it('shapes favorite + vote info with the expected key names', () => { - const out = GetLike.deserialize({} as any, { + const deps = makeDeps({ + findUinByUid: uid => uid === 'vote-user' ? 12345 : null, + }); + const out = GetLike.deserialize(deps, { userLikeInfos: [{ - uid: 'u', time: 1700000000n, - favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 }, - voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n }, + uid: 'u', time: 1700000000, + favoriteInfo: { + totalCount: 5, + lastTime: 1, + todayCount: 1, + userInfos: [{ uid: 'favorite-user', nick: '收藏者', count: 3 }], + }, + voteInfo: { + totalCount: 7, + newCount: 2, + newNearbyCount: 1, + lastVisitTime: 2, + userInfos: [{ + uid: 'vote-user', + src: 4, + latestTime: 3, + count: 2, + giftCount: 1, + customId: 5, + lastCharged: 6, + availableCount: 7, + todayVotedCount: 8, + nick: '点赞者', + gender: 1, + age: 20, + isFriend: true, + isVip: true, + isSvip: false, + }], + }, }], }); expect(out.uid).toBe('u'); expect(out.time).toBe(1700000000); expect(out.favoriteInfo).toEqual({ - total_count: 5, last_time: 1, today_count: 1, userInfos: [], + total_count: 5, + last_time: 1, + today_count: 1, + userInfos: [expect.objectContaining({ uid: 'favorite-user', nick: '收藏者', count: 3 })], }); expect(out.voteInfo).toEqual({ - total_count: 7, new_count: 2, new_nearby_count: 0, last_visit_time: 2, userInfos: [], + total_count: 7, + new_count: 2, + new_nearby_count: 1, + last_visit_time: 2, + userInfos: [expect.objectContaining({ + uid: 'vote-user', + uin: 12345, + src: 4, + latestTime: 3, + count: 2, + giftCount: 1, + customId: 5, + lastCharged: 6, + bAvailableCnt: 7, + bTodayVotedCnt: 8, + nick: '点赞者', + gender: 1, + age: 20, + isFriend: true, + isvip: true, + isSvip: false, + })], }); }); @@ -126,8 +202,14 @@ describe('GetLike namespace', () => { expect(() => GetLike.deserialize({} as any, { userLikeInfos: [] })).toThrow('get profile like info empty'); }); + it('throws when a returned user item has no uid', () => { + expect(() => GetLike.deserialize(makeDeps(), { + userLikeInfos: [{ uid: 'u', voteInfo: { userInfos: [{ nick: 'broken' }] } }], + })).toThrow('get profile like user uid missing'); + }); + it('defaults all count fields to 0 when omitted', () => { - const out = GetLike.deserialize({} as any, { userLikeInfos: [{ uid: 'u', time: 0n }] }); + const out = GetLike.deserialize(makeDeps(), { userLikeInfos: [{ uid: 'u', time: 0 }] }); expect(out.favoriteInfo.total_count).toBe(0); expect(out.voteInfo.total_count).toBe(0); }); diff --git a/packages/proton/package.json b/packages/proton/package.json index ebaf455f..4c89419d 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.14.5", + "version": "1.14.6", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/runtime/native/snowluma-linux-arm64.node b/packages/runtime/native/snowluma-linux-arm64.node index 7ca4befc..940c74ee 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.node and b/packages/runtime/native/snowluma-linux-arm64.node differ diff --git a/packages/runtime/native/snowluma-linux-arm64.so b/packages/runtime/native/snowluma-linux-arm64.so index c98b676e..c7ea74f3 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.so and b/packages/runtime/native/snowluma-linux-arm64.so differ diff --git a/packages/runtime/native/snowluma-linux-x64.node b/packages/runtime/native/snowluma-linux-x64.node index 79ef6489..62305b8c 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.node and b/packages/runtime/native/snowluma-linux-x64.node differ diff --git a/packages/runtime/native/snowluma-linux-x64.so b/packages/runtime/native/snowluma-linux-x64.so index 50f30678..d45866b2 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.so and b/packages/runtime/native/snowluma-linux-x64.so differ diff --git a/packages/runtime/native/snowluma-win32-x64.node b/packages/runtime/native/snowluma-win32-x64.node index f5fd351d..bc2f5de6 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.node and b/packages/runtime/native/snowluma-win32-x64.node differ diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 4ada513a..319ac723 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.14.5", + "version": "1.14.6", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 291f3031..20dedd20 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.14.5", + "version": "1.14.6", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index 3b35250b..5c9302df 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.14.5", + "version": "1.14.6", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index ccfd5454..dde97ee1 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.14.5", + "version": "1.14.6", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 1db336a9..e4ef5e1e 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.14.5", + "version": "1.14.6", "type": "module", "scripts": { "dev": "vite", @@ -31,7 +31,8 @@ "react": "^19.2.5", "react-dom": "^19.2.5", "tailwind-merge": "^3.5.0", - "tw-animate-css": "^1.2.5" + "tw-animate-css": "^1.2.5", + "uqr": "^0.1.3" }, "devDependencies": { "@eslint/js": "^10.0.1", diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index d5d4f207..ecbd4cea 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -92,6 +92,8 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi // (which browsers autofill, misleading users on upgrade). Stays undefined // for a returning session that's already authed but still must change. const [loginPassword, setLoginPassword] = useState(undefined); + const [urlLoginPassword, setUrlLoginPassword] = useState(undefined); + const [urlNeedsTotp, setUrlNeedsTotp] = useState(false); const authLoading = !authChecked || (authed && agreements === null && agreementsError === null); const { showSkeleton: showAuthSkeleton } = useSkeletonSwap({ ready: !authLoading }); @@ -134,6 +136,10 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi if (pw) { const result = await client.login(pw); if (result.ok) { ok = true; urlPassword = pw; } + else if ('needsTotp' in result && result.needsTotp) { + setUrlLoginPassword(pw); + setUrlNeedsTotp(true); + } } } if (ok) { @@ -166,6 +172,8 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi setReplayingOnboarding(false); onboardingReturnPath.current = null; setLoginPassword(undefined); + setUrlLoginPassword(undefined); + setUrlNeedsTotp(false); }, []); const handleDecline = useCallback(async () => { @@ -220,11 +228,15 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi } else if (!authed) { view = ( { setAuthed(true); setStatus('已连接'); setMustChange(needsChange); setLoginPassword(password); + setUrlLoginPassword(undefined); + setUrlNeedsTotp(false); setOnboardingFinished(false); void refreshAgreements(); }} @@ -351,29 +363,45 @@ function Splash({ children }: { children: React.ReactNode }) { ); } -function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) { +function LoginGate({ + onAuthed, + initialPassword, + initialNeedsTotp, +}: { + onAuthed: (mustChange: boolean, password: string) => void; + initialPassword?: string; + initialNeedsTotp?: boolean; +}) { const api = useApi(); - const { runAction } = useActionFeedback(); + const { startAction, dismiss } = useActionFeedback(); const handleLogin = useCallback( - async (password: string) => { - const result = await runAction( - { - title: '正在登录', - detail: '正在验证 WebUI 访问密码', - successTitle: '登录成功', - successDetail: '正在进入控制台', - errorTitle: '登录失败', - resultError: (login) => login.ok ? null : login.message, - }, - () => api.login(password), - ); - if (!result.ok) return { success: false, error: result.message }; - onAuthed(result.mustChangePassword, password); - return { success: true }; + async (password: string, secondFactor?: { totp?: string; recoveryCode?: string }) => { + const handle = startAction({ + title: '正在登录', + detail: secondFactor ? '正在验证一次性密码' : '正在验证 WebUI 访问密码', + }); + const result = await api.login(password, secondFactor); + if (result.ok) { + handle.succeed({ title: '登录成功', detail: '正在进入控制台' }); + onAuthed(result.mustChangePassword, password); + return { success: true }; + } + if ('message' in result) { + handle.fail(result.message, { title: '登录失败' }); + return { success: false, error: result.message }; + } + dismiss(); + return { success: false, needsTotp: true }; }, - [api, onAuthed, runAction], + [api, dismiss, onAuthed, startAction], + ); + return ( + ); - return ; } function OnboardingGate({ diff --git a/packages/webui/src/components/interior/otp-input.tsx b/packages/webui/src/components/interior/otp-input.tsx new file mode 100644 index 00000000..abffcc13 --- /dev/null +++ b/packages/webui/src/components/interior/otp-input.tsx @@ -0,0 +1,503 @@ +"use client"; + +import { + useCallback, + useEffect, + useId, + useImperativeHandle, + useRef, + useState, + type ChangeEvent, + type ClipboardEvent, + type FocusEvent, + type KeyboardEvent, + type Ref, +} from "react"; +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; + +const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const; +const EASE = [0.23, 1, 0.32, 1] as const; + + +export type OtpMode = "numeric" | "alphanumeric"; + +const ALLOW: Record = { + numeric: /^[0-9]$/, + alphanumeric: /^[0-9a-zA-Z]$/, +}; + +export type UseOtpInputOptions = { + length?: number; + mode?: OtpMode; + defaultValue?: string; + disabled?: boolean; + onChange?: (value: string) => void; + onComplete?: (value: string) => void; +}; + +export type OtpCellProps = { + ref: (el: HTMLInputElement | null) => void; + value: string; + disabled: boolean; + type: "text"; + inputMode: "numeric" | "text"; + autoComplete: string; + autoCorrect: "off"; + autoCapitalize: "off"; + spellCheck: false; + onChange: (e: ChangeEvent) => void; + onKeyDown: (e: KeyboardEvent) => void; + onPaste: (e: ClipboardEvent) => void; + onFocus: (e: FocusEvent) => void; + onBlur: (e: FocusEvent) => void; +}; + +export type UseOtpInputReturn = { + chars: string[]; + value: string; + length: number; + complete: boolean; + focusedIndex: number; + getCellProps: (index: number) => OtpCellProps; + focusAt: (index: number) => void; + clear: () => void; +}; + +export function useOtpInput({ + length = 6, + mode = "numeric", + defaultValue = "", + disabled = false, + onChange, + onComplete, +}: UseOtpInputOptions = {}): UseOtpInputReturn { + const allow = ALLOW[mode]; + + const keep = useCallback( + (text: string) => + text + .split("") + .filter((c) => allow.test(c)) + .join(""), + [allow], + ); + + const [chars, setChars] = useState(() => { + const seed = defaultValue + .split("") + .filter((c) => ALLOW[mode].test(c)) + .slice(0, length); + return Array.from({ length }, (_, i) => seed[i] ?? ""); + }); + const [focusedIndex, setFocusedIndex] = useState(-1); + + const charsRef = useRef(chars); + const refs = useRef<(HTMLInputElement | null)[]>([]); + const changed = useRef(onChange); + const completed = useRef(onComplete); + + useEffect(() => { + charsRef.current = chars; + }, [chars]); + + useEffect(() => { + changed.current = onChange; + }, [onChange]); + + useEffect(() => { + completed.current = onComplete; + }, [onComplete]); + + useEffect(() => { + setChars((prev) => + prev.length === length + ? prev + : Array.from({ length }, (_, i) => prev[i] ?? ""), + ); + refs.current.length = length; + }, [length]); + + const commit = useCallback((next: string[]) => { + charsRef.current = next; + setChars(next); + const value = next.join(""); + changed.current?.(value); + if (next.length > 0 && next.every((c) => c !== "")) completed.current?.(value); + }, []); + + const focusAt = useCallback( + (index: number) => { + const el = refs.current[Math.max(0, Math.min(length - 1, index))]; + if (!el) return; + el.focus(); + el.select(); + }, + [length], + ); + + const fillFrom = useCallback( + (index: number, text: string) => { + const incoming = keep(text); + if (incoming.length === 0) return; + const next = [...charsRef.current]; + let cursor = index; + for (const c of incoming) { + if (cursor >= length) break; + next[cursor] = c; + cursor += 1; + } + commit(next); + focusAt(cursor); + }, + [commit, focusAt, keep, length], + ); + + const clear = useCallback(() => { + commit(Array.from({ length }, () => "")); + focusAt(0); + }, [commit, focusAt, length]); + + const getCellProps = useCallback( + (index: number): OtpCellProps => ({ + ref: (el) => { + refs.current[index] = el; + }, + value: chars[index] ?? "", + disabled, + type: "text", + inputMode: mode === "numeric" ? "numeric" : "text", + autoComplete: index === 0 ? "one-time-code" : "off", + autoCorrect: "off", + autoCapitalize: "off", + spellCheck: false, + onChange: (e) => { + const previous = charsRef.current[index] ?? ""; + const raw = e.currentTarget.value; + const trimmed = + raw.length > 1 && previous && raw.startsWith(previous) + ? raw.slice(previous.length) + : raw; + const incoming = keep(trimmed); + + if (incoming.length === 0) { + if (raw.length === 0 && previous) { + const next = [...charsRef.current]; + next[index] = ""; + commit(next); + } + e.currentTarget.value = charsRef.current[index] ?? ""; + return; + } + + if (incoming.length === 1) { + const next = [...charsRef.current]; + next[index] = incoming; + e.currentTarget.value = incoming; + commit(next); + if (index < length - 1) focusAt(index + 1); + return; + } + + fillFrom(index, incoming); + }, + onKeyDown: (e) => { + if (e.key === "Backspace") { + e.preventDefault(); + const current = charsRef.current; + const next = [...current]; + if (current[index]) { + next[index] = ""; + commit(next); + return; + } + if (index > 0) { + next[index - 1] = ""; + commit(next); + focusAt(index - 1); + } + return; + } + if (e.key === "Delete") { + e.preventDefault(); + const next = [...charsRef.current]; + next[index] = ""; + commit(next); + return; + } + if (e.key === "ArrowLeft") { + e.preventDefault(); + focusAt(index - 1); + return; + } + if (e.key === "ArrowRight") { + e.preventDefault(); + focusAt(index + 1); + return; + } + if (e.key === "Home") { + e.preventDefault(); + focusAt(0); + return; + } + if (e.key === "End") { + e.preventDefault(); + focusAt(length - 1); + } + }, + onPaste: (e) => { + e.preventDefault(); + const text = keep(e.clipboardData.getData("text")); + fillFrom(text.length >= length ? 0 : index, text); + }, + onFocus: (e) => { + e.currentTarget.select(); + const firstEmpty = charsRef.current.findIndex((c) => c === ""); + if (firstEmpty !== -1 && firstEmpty < index) { + focusAt(firstEmpty); + return; + } + setFocusedIndex(index); + }, + onBlur: (e) => { + const to = e.relatedTarget as HTMLInputElement | null; + if (to && refs.current.includes(to)) return; + setFocusedIndex(-1); + }, + }), + [chars, commit, disabled, fillFrom, focusAt, keep, length, mode], + ); + + const value = chars.join(""); + + return { + chars, + value, + length, + complete: chars.length > 0 && chars.every((c) => c !== ""), + focusedIndex, + getCellProps, + focusAt, + clear, + }; +} + +export type OtpStatus = "idle" | "error" | "success"; + +export type OtpInputHandle = { + clear: () => void; + focus: () => void; +}; + +export type OtpInputProps = { + length?: number; + mode?: OtpMode; + defaultValue?: string; + onChange?: (value: string) => void; + onComplete?: (value: string) => void; + /** Official usage example: red cells + shake on the false → true edge. */ + error?: boolean; + status?: OtpStatus; + errorMessage?: string; + successMessage?: string; + hint?: string; + label?: string; + groupEvery?: number; + /** Draw a rule between groups (recovery XXXX-XXXX). Spacing-only when false. */ + groupSeparator?: boolean; + disabled?: boolean; + autoFocus?: boolean; + focusOnError?: boolean; + className?: string; + ref?: Ref; +}; + +export function OtpInput({ + length = 6, + mode = "numeric", + defaultValue = "", + onChange, + onComplete, + error: errorProp = false, + status = "idle", + errorMessage = "", + successMessage = "", + hint = "", + label = "Verification code", + groupEvery = 3, + groupSeparator = false, + disabled = false, + autoFocus = false, + focusOnError = true, + className = "", + ref, +}: OtpInputProps) { + const reduced = useReducedMotion(); + const statusId = useId(); + + const { chars, focusedIndex, getCellProps, focusAt, clear } = useOtpInput({ + length, + mode, + defaultValue, + disabled, + onChange, + onComplete, + }); + + const wasError = useRef(false); + const error = errorProp || status === "error"; + const success = status === "success"; + const tone = error ? "error" : success ? "success" : "idle"; + + useImperativeHandle( + ref, + () => ({ + clear: () => { + clear(); + focusAt(0); + }, + focus: () => focusAt(0), + }), + [clear, focusAt], + ); + + useEffect(() => { + if (error && !wasError.current && focusOnError && !disabled) focusAt(0); + wasError.current = error; + }, [error, focusOnError, disabled, focusAt]); + + useEffect(() => { + if (autoFocus && !disabled) focusAt(0); + }, [autoFocus, disabled, focusAt]); + + const enter = reduced ? { duration: 0 } : { duration: 0.22, ease: EASE }; + const swap = reduced ? { duration: 0 } : CROSSFADE; + const hasStatus = + hint.length > 0 || errorMessage.length > 0 || successMessage.length > 0; + + const message = error ? errorMessage : success ? successMessage : hint; + const messageTone = error + ? "text-destructive" + : success + ? "text-success" + : "text-muted-foreground"; + + return ( +
+ + {Array.from({ length }, (_, i) => { + const char = chars[i] ?? ""; + const active = focusedIndex === i; + const gap = groupEvery > 0 && i > 0 && i % groupEvery === 0; + + return ( +
+ {gap && groupSeparator ? ( + + + + ) : null} +
+ + + + + {char ? ( + + {char} + + ) : null} + + + {active && !char && !disabled ? ( + + ) : null} + +
+
+ ); + })} +
+ + {hasStatus && ( + <> +
+ + + {message} + + +
+ + {message} + + + )} +
+ ); +} diff --git a/packages/webui/src/components/pages/login-page.tsx b/packages/webui/src/components/pages/login-page.tsx index c1007148..444264d3 100644 --- a/packages/webui/src/components/pages/login-page.tsx +++ b/packages/webui/src/components/pages/login-page.tsx @@ -1,7 +1,8 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'; import { motion } from 'motion/react'; import { ArrowRight, KeyRound, Sparkles } from 'lucide-react'; import { Modal } from '@/components/interior/modal'; +import { OtpInput, type OtpInputHandle } from '@/components/interior/otp-input'; import { Button } from '@/components/ui/button'; import { Card, CardContent } from '@/components/ui/card'; import { Input } from '@/components/ui/input'; @@ -12,9 +13,16 @@ import { LoginWaves } from '@/components/login-waves'; import { useTheme } from '@/contexts/ThemeContext'; import { cn } from '@/lib/utils'; import { APP_NAME, APP_VERSION } from '@/types'; +import { parseSecondFactor } from '@/lib/totp-second-factor'; interface LoginPageProps { - onLogin: (password: string) => Promise<{ success: boolean; error?: string }>; + onLogin: ( + password: string, + secondFactor?: { totp?: string; recoveryCode?: string }, + ) => Promise<{ success: boolean; error?: string; needsTotp?: boolean }>; + initialPassword?: string; + initialNeedsTotp?: boolean; + initialUseRecovery?: boolean; } // Device-local preference for the (heavy) animated login background. Kept out @@ -33,7 +41,12 @@ function readLoginFx(): boolean { try { return !window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch { return true; } } -export function LoginPage({ onLogin }: LoginPageProps) { +export function LoginPage({ + onLogin, + initialPassword = '', + initialNeedsTotp = false, + initialUseRecovery = false, +}: LoginPageProps) { const { appearance } = useTheme(); const customBg = appearance.background.type !== 'none'; const reduce = appearance.reduceMotion || appearance.disableMotion; @@ -43,7 +56,11 @@ export function LoginPage({ onLogin }: LoginPageProps) { // clear any lingering custom-CSS