Merge pull request #357 from SnowLuma/dev
chore: promote dev → main (d26aef8)
This commit is contained in:
64 files changed
+3818
-343
No files matched your search
+1
-1
@@ -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",
|
||||
|
||||
@@ -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).",
|
||||
|
||||
@@ -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).",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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<LikeInfo> {
|
||||
return GetLike.invoke(this.ctx, { userId, start, limit });
|
||||
async getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
|
||||
const info = await GetLike.invoke(this.ctx, { userId, start, limit });
|
||||
const users = [...info.favoriteInfo.userInfos, ...info.voteInfo.userInfos];
|
||||
const unresolved = new Map<string, typeof users>();
|
||||
|
||||
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<UnidirectionalFriendEntry[]> {
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<string, SessionInfo>();
|
||||
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
|
||||
const totpEnrollments = new Map<string, {
|
||||
secret: string;
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
expiresAt: number;
|
||||
}>();
|
||||
|
||||
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<string, unknown> = {};
|
||||
try {
|
||||
const parsed = await c.req.json();
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
body = parsed as Record<string, unknown>;
|
||||
}
|
||||
} 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.
|
||||
|
||||
@@ -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<string>();
|
||||
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<string, unknown>): value is WrappedTotpSecret & Record<string, unknown> {
|
||||
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<string, unknown>;
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<string, unknown>;
|
||||
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<T>(sessions: Map<string, T>, keepToken: string): void {
|
||||
for (const token of sessions.keys()) {
|
||||
if (token !== keepToken) sessions.delete(token);
|
||||
}
|
||||
}
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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<OidbBase<Oidb0x7edResp>>({
|
||||
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<OidbBase<Oidb0x7edResp>>({
|
||||
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<OidbBase<Oidb0x7edResp>>({
|
||||
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({
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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<Record<number, Buffer>> = {},
|
||||
) {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.<area>.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/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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<N, T>` 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).",
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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). */
|
||||
|
||||
@@ -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/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
|
||||
|
||||
@@ -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<HighwaySessi
|
||||
function makeHighwayHead(
|
||||
uin: string, commandId: number, fileSize: number, offset: number, length: number,
|
||||
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
|
||||
retryTimes = 0,
|
||||
): Uint8Array {
|
||||
return protobuf_encode<ReqDataHighwayHead>({
|
||||
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<RespDataHighwayHead>(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<RespDataHighwayHead>(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
|
||||
|
||||
@@ -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 ---
|
||||
|
||||
@@ -53,12 +53,13 @@ export interface OidbSender {
|
||||
* `Pick<BridgeContext, ...>` 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<TCtx extends OidbSender, TReq, TResp, TParams, TResult> {
|
||||
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<TCtx extends OidbSender, TReq, TResp, TParams,
|
||||
timeoutMs?: number,
|
||||
): Promise<TResult> {
|
||||
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<TCtx extends OidbSender, TReq, TResp, TPa
|
||||
params: TParams,
|
||||
): Promise<{ wireName: string; bytes: Uint8Array }> {
|
||||
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);
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -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<BridgeContext, 'identity' | 'resolveUserUid'>;
|
||||
|
||||
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<Oidb0x7edReq> => {
|
||||
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)),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<OidbBase<GroupDetailResponseFixture>>({
|
||||
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<OidbBase<GroupDetailResponseFixture>>({
|
||||
body: {
|
||||
|
||||
@@ -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<OidbBase<OidbGroupListRequest>>(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<OidbBase<GroupListFixture>>({
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import { GetLike } from '../../../src/oidb-services/profile/get-like';
|
||||
function makeDeps(opts: {
|
||||
cachedSelfUid?: string | null;
|
||||
resolveUserUid?: (uin: number) => Promise<string>;
|
||||
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<OidbBase<Oidb0x7edReq>>(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<OidbBase<Oidb0x7edReq>>(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);
|
||||
});
|
||||
|
||||
@@ -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.",
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
+47
-19
@@ -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<string | undefined>(undefined);
|
||||
const [urlLoginPassword, setUrlLoginPassword] = useState<string | undefined>(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 = (
|
||||
<LoginGate
|
||||
initialPassword={urlLoginPassword}
|
||||
initialNeedsTotp={urlNeedsTotp}
|
||||
onAuthed={(needsChange, password) => {
|
||||
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 (
|
||||
<LoginPage
|
||||
onLogin={handleLogin}
|
||||
initialPassword={initialPassword}
|
||||
initialNeedsTotp={initialNeedsTotp}
|
||||
/>
|
||||
);
|
||||
return <LoginPage onLogin={handleLogin} />;
|
||||
}
|
||||
|
||||
function OnboardingGate({
|
||||
|
||||
@@ -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<OtpMode, RegExp> = {
|
||||
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<HTMLInputElement>) => void;
|
||||
onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => void;
|
||||
onPaste: (e: ClipboardEvent<HTMLInputElement>) => void;
|
||||
onFocus: (e: FocusEvent<HTMLInputElement>) => void;
|
||||
onBlur: (e: FocusEvent<HTMLInputElement>) => 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<string[]>(() => {
|
||||
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<OtpInputHandle>;
|
||||
};
|
||||
|
||||
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 (
|
||||
<div className={`flex w-full flex-col ${className}`}>
|
||||
<motion.div
|
||||
role="group"
|
||||
aria-label={label}
|
||||
className="relative flex w-full gap-2.5"
|
||||
initial={false}
|
||||
variants={{ idle: { x: 0 }, wrong: { x: [0, -5, 4, -3, 0] } }}
|
||||
animate={error && !reduced ? "wrong" : "idle"}
|
||||
transition={{ duration: 0.32, ease: EASE }}
|
||||
>
|
||||
{Array.from({ length }, (_, i) => {
|
||||
const char = chars[i] ?? "";
|
||||
const active = focusedIndex === i;
|
||||
const gap = groupEvery > 0 && i > 0 && i % groupEvery === 0;
|
||||
|
||||
return (
|
||||
<div key={i} className="contents">
|
||||
{gap && groupSeparator ? (
|
||||
<span
|
||||
aria-hidden
|
||||
className="flex h-16 w-3.5 shrink-0 items-center justify-center"
|
||||
>
|
||||
<span className="h-[2px] w-3 rounded-full bg-muted-foreground/55" />
|
||||
</span>
|
||||
) : null}
|
||||
<div className={`relative h-16 min-w-0 flex-1 ${gap && !groupSeparator ? "ms-3" : ""}`}>
|
||||
<input
|
||||
{...getCellProps(i)}
|
||||
aria-label={`${label}, character ${i + 1} of ${length}`}
|
||||
aria-invalid={error || undefined}
|
||||
aria-describedby={hasStatus ? statusId : undefined}
|
||||
className={`size-full rounded-xl border-2 text-center text-xl text-transparent caret-transparent outline-none transition-[background-color,border-color,box-shadow] duration-150 selection:bg-transparent focus-visible:outline-none disabled:opacity-50 ${
|
||||
error
|
||||
? "border-destructive bg-background"
|
||||
: success
|
||||
? "border-success bg-background"
|
||||
: active
|
||||
? "border-primary bg-background"
|
||||
: char
|
||||
? "border-border bg-background"
|
||||
: "border-border/80 bg-muted/60 shadow-[inset_0_1px_2px_color-mix(in_oklab,var(--foreground)_8%,transparent)]"
|
||||
}`}
|
||||
/>
|
||||
|
||||
<span
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-0 grid place-items-center"
|
||||
>
|
||||
<AnimatePresence initial={false} mode="popLayout">
|
||||
{char ? (
|
||||
<motion.span
|
||||
key={char}
|
||||
initial={
|
||||
reduced
|
||||
? false
|
||||
: { opacity: 0, scale: 0.97, y: 10, filter: "blur(6px)" }
|
||||
}
|
||||
animate={{ opacity: 1, scale: 1, y: 0, filter: "blur(0px)" }}
|
||||
exit={
|
||||
reduced
|
||||
? { opacity: 0 }
|
||||
: { opacity: 0, scale: 0.98, y: -6, filter: "blur(3px)" }
|
||||
}
|
||||
transition={enter}
|
||||
className="col-start-1 row-start-1 font-mono text-[22px] tabular-nums text-foreground"
|
||||
>
|
||||
{char}
|
||||
</motion.span>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
|
||||
{active && !char && !disabled ? (
|
||||
<motion.span
|
||||
className="col-start-1 row-start-1 block h-6 w-[1.5px] rounded-[1px] bg-foreground"
|
||||
initial={{ opacity: 1 }}
|
||||
animate={reduced ? { opacity: 1 } : { opacity: [1, 1, 0, 0] }}
|
||||
transition={
|
||||
reduced
|
||||
? { duration: 0 }
|
||||
: {
|
||||
duration: 1.06,
|
||||
times: [0, 0.5, 0.5, 1],
|
||||
repeat: Infinity,
|
||||
ease: "linear",
|
||||
}
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</motion.div>
|
||||
|
||||
{hasStatus && (
|
||||
<>
|
||||
<div aria-hidden className="mt-2 grid h-4 text-[11.5px] leading-[16px]">
|
||||
<AnimatePresence initial={false} mode="wait">
|
||||
<motion.span
|
||||
key={tone}
|
||||
initial={reduced ? { opacity: 0 } : { opacity: 0, y: 3 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={reduced ? { opacity: 0 } : { opacity: 0, y: -3 }}
|
||||
transition={swap}
|
||||
className={`col-start-1 row-start-1 ${messageTone}`}
|
||||
>
|
||||
{message}
|
||||
</motion.span>
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
<span id={statusId} role="status" className="sr-only">
|
||||
{message}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 <style> whenever the login page shows.
|
||||
useEffect(() => { document.getElementById('snowluma-custom-css')?.remove(); }, []);
|
||||
|
||||
const [password, setPassword] = useState('');
|
||||
const [password, setPassword] = useState(initialPassword);
|
||||
const [useRecovery, setUseRecovery] = useState(initialUseRecovery);
|
||||
const [needsTotp, setNeedsTotp] = useState(initialNeedsTotp);
|
||||
const [otpStatus, setOtpStatus] = useState<'idle' | 'checking' | 'rejected'>('idle');
|
||||
const otpRef = useRef<OtpInputHandle>(null);
|
||||
const [showPwd, setShowPwd] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -56,24 +73,213 @@ export function LoginPage({ onLogin }: LoginPageProps) {
|
||||
try { localStorage.setItem(LOGIN_FX_KEY, v ? '1' : '0'); } catch { /* ignore */ }
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
useEffect(() => {
|
||||
if (otpStatus !== 'rejected') return;
|
||||
const id = window.setTimeout(() => {
|
||||
otpRef.current?.clear();
|
||||
setOtpStatus('idle');
|
||||
setError('');
|
||||
}, 1600);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [otpStatus]);
|
||||
|
||||
const goBackToPassword = () => {
|
||||
setNeedsTotp(false);
|
||||
setUseRecovery(false);
|
||||
setOtpStatus('idle');
|
||||
setError('');
|
||||
};
|
||||
|
||||
const handlePasswordSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
const result = await onLogin(password);
|
||||
setLoading(false);
|
||||
if (result.needsTotp) {
|
||||
setNeedsTotp(true);
|
||||
setUseRecovery(false);
|
||||
setOtpStatus('idle');
|
||||
setError('');
|
||||
return;
|
||||
}
|
||||
if (!result.success) {
|
||||
setError(result.error || '登录失败');
|
||||
setShake((k) => k + 1);
|
||||
}
|
||||
};
|
||||
|
||||
const submitTotp = async (code: string) => {
|
||||
setOtpStatus('checking');
|
||||
const result = await onLogin(password, parseSecondFactor(code));
|
||||
if (result.success) return;
|
||||
if (result.needsTotp) {
|
||||
setOtpStatus('idle');
|
||||
return;
|
||||
}
|
||||
setError(result.error || (useRecovery
|
||||
? '恢复码不正确,改错的那一位即可。'
|
||||
: '验证码不正确,改错的那一位即可。'));
|
||||
setOtpStatus('rejected');
|
||||
};
|
||||
|
||||
const handleTotpSubmit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
};
|
||||
|
||||
return (
|
||||
<LoginShell
|
||||
customBg={customBg}
|
||||
reduce={reduce}
|
||||
fxOn={fxOn}
|
||||
helpOpen={helpOpen}
|
||||
onHelpOpen={setHelpOpen}
|
||||
onToggleFx={toggleFx}
|
||||
wide={useRecovery}
|
||||
>
|
||||
{needsTotp ? (
|
||||
<>
|
||||
<LoginBrand subtitle={useRecovery ? '输入保存的一次性恢复码' : '输入 Authenticator 中的 6 位验证码'} />
|
||||
<form onSubmit={handleTotpSubmit} className="mt-8 flex flex-col gap-3.5">
|
||||
<OtpInput
|
||||
key={useRecovery ? 'recovery' : 'totp'}
|
||||
ref={otpRef}
|
||||
autoFocus
|
||||
className="w-full"
|
||||
length={useRecovery ? 8 : 6}
|
||||
mode={useRecovery ? 'alphanumeric' : 'numeric'}
|
||||
groupEvery={useRecovery ? 4 : 3}
|
||||
groupSeparator={useRecovery}
|
||||
label={useRecovery ? '恢复码' : '验证码'}
|
||||
disabled={otpStatus === 'checking'}
|
||||
error={otpStatus === 'rejected'}
|
||||
errorMessage={error || (useRecovery
|
||||
? '恢复码不正确,改错的那一位即可。'
|
||||
: '验证码不正确,改错的那一位即可。')}
|
||||
hint={useRecovery
|
||||
? '可以把完整恢复码粘贴到任意一格,连字符会自动忽略。'
|
||||
: '可以把完整验证码粘贴到任意一格。'}
|
||||
onChange={() => setOtpStatus((s) => (s === 'rejected' ? 'idle' : s))}
|
||||
onComplete={(code) => { void submitTotp(code); }}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between text-[12px]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={goBackToPassword}
|
||||
className="text-muted-foreground transition-colors hover:text-foreground cursor-pointer"
|
||||
>
|
||||
返回
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setUseRecovery((v) => !v);
|
||||
setOtpStatus('idle');
|
||||
setError('');
|
||||
}}
|
||||
className="text-muted-foreground transition-colors hover:text-foreground cursor-pointer"
|
||||
>
|
||||
{useRecovery ? '改用验证码' : '使用恢复码'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<LoginBrand subtitle="OneBot v11 协议网关 · 安全登录" />
|
||||
<form onSubmit={handlePasswordSubmit} className="mt-8 flex flex-col gap-3.5">
|
||||
<motion.div
|
||||
key={shake}
|
||||
animate={shake > 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}}
|
||||
transition={{ duration: 0.4 }}
|
||||
className="relative"
|
||||
>
|
||||
<KeyRound className="pointer-events-none absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type={showPwd ? 'text' : 'password'}
|
||||
placeholder="输入访问令牌"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoFocus
|
||||
autoComplete="current-password"
|
||||
className="h-12 rounded-xl bg-background/40 pl-10 pr-11 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPwd((v) => !v)}
|
||||
className="absolute right-2 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground cursor-pointer"
|
||||
tabIndex={-1}
|
||||
aria-label={showPwd ? '隐藏密码' : '显示密码'}
|
||||
>
|
||||
<PasswordVisibilityIcon visible={showPwd} reduceMotion={reduce} />
|
||||
</button>
|
||||
</motion.div>
|
||||
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={reduce ? false : { opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="rounded-lg bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
|
||||
<Button type="submit" disabled={loading || !password} className="h-12 rounded-xl text-[15px]">
|
||||
{loading ? '验证中…' : (
|
||||
<>
|
||||
进入控制台 <ArrowRight className="optical-forward size-4" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</LoginShell>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginBrand({ subtitle }: { subtitle: string }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-3 text-center">
|
||||
<div className="flex size-14 items-center justify-center rounded-2xl bg-primary/10 shadow-sm ring-1 ring-primary/20">
|
||||
<img src="/logo.png" alt="SnowLuma" className="size-10 object-contain" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<span className="text-2xl font-semibold tracking-tight">{APP_NAME}</span>
|
||||
<span className="rounded-full bg-primary/10 px-1.5 py-0.5 font-mono text-micro text-primary tabular-nums">v{APP_VERSION}</span>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{subtitle}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginShell({
|
||||
customBg,
|
||||
reduce,
|
||||
fxOn,
|
||||
helpOpen,
|
||||
onHelpOpen,
|
||||
onToggleFx,
|
||||
wide = false,
|
||||
children,
|
||||
}: {
|
||||
customBg: boolean;
|
||||
reduce: boolean;
|
||||
fxOn: boolean;
|
||||
helpOpen: boolean;
|
||||
onHelpOpen: (open: boolean) => void;
|
||||
onToggleFx: (value: boolean) => void;
|
||||
wide?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-8', customBg ? 'bg-transparent' : 'bg-background')}>
|
||||
{/* Animated wavy-line background (device-local toggle) */}
|
||||
{fxOn && <LoginWaves />}
|
||||
|
||||
{/* Soft glow backdrop — also helps the frosted card read against the waves */}
|
||||
<div
|
||||
className="pointer-events-none absolute inset-0"
|
||||
style={{
|
||||
@@ -90,81 +296,20 @@ export function LoginPage({ onLogin }: LoginPageProps) {
|
||||
initial={reduce ? false : { opacity: 0, y: 16, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={reduce ? { duration: 0 } : { duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
|
||||
className="relative z-10 flex w-full max-w-md flex-col items-center"
|
||||
className={cn('relative z-10 flex w-full flex-col items-center', wide ? 'max-w-2xl' : 'max-w-md')}
|
||||
>
|
||||
{/* Frosted "vibrancy" card */}
|
||||
<Card className="w-full overflow-hidden border-border/50 bg-card/75 shadow-2xl shadow-primary/5 backdrop-blur-2xl supports-[backdrop-filter]:bg-card/65">
|
||||
<CardContent className="px-7 py-9 sm:px-10">
|
||||
{/* Centered brand focal point */}
|
||||
<div className="flex flex-col items-center gap-3 text-center">
|
||||
<div className="flex size-14 items-center justify-center rounded-2xl bg-primary/10 shadow-sm ring-1 ring-primary/20">
|
||||
<img src="/logo.png" alt="SnowLuma" className="size-10 object-contain" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<span className="text-2xl font-semibold tracking-tight">{APP_NAME}</span>
|
||||
<span className="rounded-full bg-primary/10 px-1.5 py-0.5 font-mono text-micro text-primary tabular-nums">v{APP_VERSION}</span>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">OneBot v11 协议网关 · 安全登录</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-8 flex flex-col gap-3.5">
|
||||
<motion.div
|
||||
key={shake}
|
||||
animate={shake > 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}}
|
||||
transition={{ duration: 0.4 }}
|
||||
className="relative"
|
||||
>
|
||||
<KeyRound className="pointer-events-none absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type={showPwd ? 'text' : 'password'}
|
||||
placeholder="输入访问令牌"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoFocus
|
||||
className="h-12 rounded-xl bg-background/40 pl-10 pr-11 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPwd((v) => !v)}
|
||||
className="absolute right-2 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground cursor-pointer"
|
||||
tabIndex={-1}
|
||||
aria-label={showPwd ? '隐藏密码' : '显示密码'}
|
||||
>
|
||||
<PasswordVisibilityIcon visible={showPwd} reduceMotion={reduce} />
|
||||
</button>
|
||||
</motion.div>
|
||||
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={reduce ? false : { opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="rounded-lg bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
|
||||
<Button type="submit" disabled={loading || !password} className="h-12 rounded-xl text-[15px]">
|
||||
{loading ? '验证中…' : (
|
||||
<>
|
||||
进入控制台 <ArrowRight className="optical-forward size-4" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{children}
|
||||
<p className="mt-7 text-center text-meta text-muted-foreground">
|
||||
© {new Date().getFullYear()} SnowLuma. All rights reserved.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 灵动岛-style frosted capsule: perf escape hatch for the background */}
|
||||
<motion.button
|
||||
type="button"
|
||||
onClick={() => setHelpOpen(true)}
|
||||
onClick={() => onHelpOpen(true)}
|
||||
whileHover={reduce ? undefined : { scale: 1.04 }}
|
||||
whileTap={reduce ? undefined : { scale: 0.96 }}
|
||||
transition={{ type: 'spring', stiffness: 420, damping: 26 }}
|
||||
@@ -177,7 +322,7 @@ export function LoginPage({ onLogin }: LoginPageProps) {
|
||||
|
||||
<Modal
|
||||
open={helpOpen}
|
||||
onClose={() => setHelpOpen(false)}
|
||||
onClose={() => onHelpOpen(false)}
|
||||
title="界面有点卡顿?"
|
||||
description="登录页背景是一个跟随鼠标的动态线条效果,在部分设备上可能比较吃性能。可以在这里关掉它——该开关仅作用于本设备的登录页,与系统的动效设置相互独立。"
|
||||
closeLabel="关闭性能设置弹窗"
|
||||
@@ -189,7 +334,7 @@ export function LoginPage({ onLogin }: LoginPageProps) {
|
||||
<p className="text-sm font-medium">登录页动态背景</p>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">{fxOn ? '已开启 · 关闭后背景为静态' : '已关闭 · 背景为静态'}</p>
|
||||
</div>
|
||||
<ToggleSwitch value={fxOn} onChange={toggleFx} ariaLabel="登录页动态背景" />
|
||||
<ToggleSwitch value={fxOn} onChange={onToggleFx} ariaLabel="登录页动态背景" />
|
||||
</div>
|
||||
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
|
||||
@@ -37,6 +37,7 @@ import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
|
||||
import { useSession } from '@/contexts/SessionContext';
|
||||
import { NAV_ITEMS } from '@/components/layout/sidebar';
|
||||
import { TOPBAR_CATALOGUE } from '@/components/layout/top-bar';
|
||||
import { TotpPanel } from '@/components/settings/totp-panel';
|
||||
import { ChangePasswordDialog } from '@/components/change-password-dialog';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { SkeletonSwap } from '@/components/interior/skeleton-swap';
|
||||
@@ -1220,44 +1221,47 @@ function AccountPanel() {
|
||||
const [confirmLogout, setConfirmLogout] = useState(false);
|
||||
|
||||
return (
|
||||
<Group title="账号安全" icon={ShieldCheck} description="WebUI 仅有 admin 一个账号,密码以 scrypt 哈希持久化到 config/webui.json。">
|
||||
<SettingRow
|
||||
label="访问密码"
|
||||
hint={pwdSavedAt
|
||||
? <span className="text-success">已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。</span>
|
||||
: '修改后其他设备的会话将立即失效。'}
|
||||
>
|
||||
<Button variant="outline" size="sm" onClick={() => setShowChangePwd(true)}>
|
||||
<KeyRound className="size-4" /> 修改密码
|
||||
</Button>
|
||||
</SettingRow>
|
||||
<SettingRow label="退出登录" hint="立即清除当前浏览器的会话令牌。">
|
||||
<Button variant="ghost" size="sm" onClick={() => setConfirmLogout(true)} className="text-destructive hover:text-destructive">
|
||||
<div className="flex flex-col gap-5">
|
||||
<Group title="账号安全" icon={ShieldCheck} description="WebUI 仅有 admin 一个账号,密码以 scrypt 哈希持久化到 config/webui.json。">
|
||||
<SettingRow
|
||||
label="访问密码"
|
||||
hint={pwdSavedAt
|
||||
? <span className="text-success">已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。</span>
|
||||
: '修改后其他设备的会话将立即失效。'}
|
||||
>
|
||||
<Button variant="outline" size="sm" onClick={() => setShowChangePwd(true)}>
|
||||
<KeyRound className="size-4" /> 修改密码
|
||||
</Button>
|
||||
</SettingRow>
|
||||
<SettingRow label="退出登录" hint="立即清除当前浏览器的会话令牌。">
|
||||
<Button variant="ghost" size="sm" onClick={() => setConfirmLogout(true)} className="text-destructive hover:text-destructive">
|
||||
退出登录
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</Button>
|
||||
</SettingRow>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmLogout}
|
||||
onOpenChange={setConfirmLogout}
|
||||
title="确认退出登录?"
|
||||
description="退出后将清除当前会话令牌,需要重新输入访问密码才能进入控制台。"
|
||||
confirmText="退出登录"
|
||||
destructive
|
||||
activity={{
|
||||
title: '正在退出登录',
|
||||
successTitle: '已退出登录',
|
||||
errorTitle: '退出登录失败',
|
||||
}}
|
||||
onConfirm={onLogout}
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={confirmLogout}
|
||||
onOpenChange={setConfirmLogout}
|
||||
title="确认退出登录?"
|
||||
description="退出后将清除当前会话令牌,需要重新输入访问密码才能进入控制台。"
|
||||
confirmText="退出登录"
|
||||
destructive
|
||||
activity={{
|
||||
title: '正在退出登录',
|
||||
successTitle: '已退出登录',
|
||||
errorTitle: '退出登录失败',
|
||||
}}
|
||||
onConfirm={onLogout}
|
||||
/>
|
||||
|
||||
<ChangePasswordDialog
|
||||
open={showChangePwd}
|
||||
onOpenChange={setShowChangePwd}
|
||||
onSuccess={() => setPwdSavedAt(Date.now())}
|
||||
/>
|
||||
</Group>
|
||||
<ChangePasswordDialog
|
||||
open={showChangePwd}
|
||||
onOpenChange={setShowChangePwd}
|
||||
onSuccess={() => setPwdSavedAt(Date.now())}
|
||||
/>
|
||||
</Group>
|
||||
<TotpPanel />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { KeyRound, ShieldCheck } from 'lucide-react';
|
||||
import { Card, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Modal } from '@/components/interior/modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useApi } from '@/lib/api';
|
||||
import type { TotpEnrollment, TotpStatus } from '@/lib/api/types';
|
||||
import { parseSecondFactor } from '@/lib/totp-second-factor';
|
||||
import { TotpQr } from '@/components/settings/totp-qr';
|
||||
import { TotpRecoveryCodes } from '@/components/settings/totp-recovery-codes';
|
||||
|
||||
function SettingRow({
|
||||
label,
|
||||
hint,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3 px-5 py-4 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium">{label}</p>
|
||||
{hint && <p className="mt-0.5 text-[12px] leading-snug text-muted-foreground">{hint}</p>}
|
||||
</div>
|
||||
<div className="sm:shrink-0">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TotpPanel() {
|
||||
const api = useApi();
|
||||
const [status, setStatus] = useState<TotpStatus | 'hidden' | 'loading'>('loading');
|
||||
const [setupOpen, setSetupOpen] = useState(false);
|
||||
const [disableOpen, setDisableOpen] = useState(false);
|
||||
const [regenOpen, setRegenOpen] = useState(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
setStatus(await api.totp.status());
|
||||
} catch {
|
||||
setStatus('hidden');
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => { void refresh(); }, [refresh]);
|
||||
|
||||
if (status === 'hidden') return null;
|
||||
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<CardHeader className="gap-1 pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-[15px]">
|
||||
<ShieldCheck className="size-4 text-primary" />
|
||||
双重验证
|
||||
</CardTitle>
|
||||
<CardDescription className="text-[12px] leading-relaxed">
|
||||
登录时在访问密码之外再验证 Authenticator 一次性密码。默认关闭。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<div className="divide-y divide-border/60 border-t border-border/60">
|
||||
{status === 'loading' ? (
|
||||
<SettingRow label="2FA" hint="正在读取…">
|
||||
<span className="text-sm text-muted-foreground">…</span>
|
||||
</SettingRow>
|
||||
) : status.enabled ? (
|
||||
<>
|
||||
<SettingRow label="状态" hint={`已绑定 ${status.label} · 剩余 ${status.remainingRecoveryCodes} 个恢复码`}>
|
||||
<span className="text-sm text-success">已开启</span>
|
||||
</SettingRow>
|
||||
<SettingRow label="恢复码" hint="重新生成后旧码立即作废。">
|
||||
<Button variant="outline" size="sm" onClick={() => setRegenOpen(true)}>
|
||||
重新生成
|
||||
</Button>
|
||||
</SettingRow>
|
||||
<SettingRow label="关闭 2FA" hint="需要当前密码,以及验证码或恢复码。其他设备的会话将失效。">
|
||||
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" onClick={() => setDisableOpen(true)}>
|
||||
关闭
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</>
|
||||
) : (
|
||||
<SettingRow label="Authenticator" hint="扫描二维码或手动输入密钥,再用 6 位验证码确认。">
|
||||
<Button variant="outline" size="sm" onClick={() => setSetupOpen(true)}>
|
||||
<KeyRound className="size-4" /> 开启 2FA
|
||||
</Button>
|
||||
</SettingRow>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TotpSetupDialog
|
||||
open={setupOpen}
|
||||
onOpenChange={setSetupOpen}
|
||||
onEnabled={async () => { await refresh(); }}
|
||||
/>
|
||||
<TotpChallengeDialog
|
||||
open={disableOpen}
|
||||
onOpenChange={setDisableOpen}
|
||||
title="关闭双重验证"
|
||||
description="关闭后,只需访问密码即可登录。其他已登录会话会立即失效。"
|
||||
confirmText="关闭 2FA"
|
||||
destructive
|
||||
onSubmit={async (password, second) => api.totp.disable(password, second)}
|
||||
onDone={refresh}
|
||||
/>
|
||||
<TotpRegenDialog
|
||||
open={regenOpen}
|
||||
onOpenChange={setRegenOpen}
|
||||
onDone={refresh}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function TotpSetupDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onEnabled,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onEnabled: () => void | Promise<void>;
|
||||
}) {
|
||||
const api = useApi();
|
||||
const [enrollment, setEnrollment] = useState<TotpEnrollment | null>(null);
|
||||
const [issuer, setIssuer] = useState('');
|
||||
const [accountName, setAccountName] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);
|
||||
|
||||
const loadEnrollment = useCallback(async (nextIssuer?: string, nextAccount?: string) => {
|
||||
const result = await api.totp.begin({
|
||||
...(nextIssuer ? { issuer: nextIssuer } : {}),
|
||||
...(nextAccount ? { accountName: nextAccount } : {}),
|
||||
});
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
setEnrollment(result);
|
||||
setIssuer(result.issuer);
|
||||
setAccountName(result.accountName);
|
||||
setError('');
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setEnrollment(null);
|
||||
setPassword('');
|
||||
setCode('');
|
||||
setError('');
|
||||
setRecoveryCodes(null);
|
||||
return;
|
||||
}
|
||||
void loadEnrollment();
|
||||
}, [open, loadEnrollment]);
|
||||
|
||||
const refreshLabels = async () => {
|
||||
if (!enrollment) return;
|
||||
await loadEnrollment(issuer, accountName);
|
||||
};
|
||||
|
||||
const confirm = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
await loadEnrollment(issuer, accountName);
|
||||
const result = await api.totp.confirm(password, code);
|
||||
setBusy(false);
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
setRecoveryCodes(result.recoveryCodes);
|
||||
await onEnabled();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => { if (!recoveryCodes) onOpenChange(false); }}
|
||||
title={recoveryCodes ? '保存恢复码' : '开启双重验证'}
|
||||
description={recoveryCodes
|
||||
? '这些恢复码只显示一次。丢失 Authenticator 时用它们登录。'
|
||||
: '用 Authenticator 扫描二维码,或手动输入密钥,然后输入当前访问密码和 6 位验证码。'}
|
||||
closeLabel="关闭 2FA 绑定"
|
||||
maxWidth={440}
|
||||
>
|
||||
{recoveryCodes ? (
|
||||
<TotpRecoveryCodes codes={recoveryCodes} onConfirm={() => onOpenChange(false)} />
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{enrollment && (
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<TotpQr value={enrollment.otpauthUrl} label="2FA 绑定二维码" />
|
||||
<p className="break-all text-center font-mono text-xs text-muted-foreground">{enrollment.secret}</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||
服务名
|
||||
<Input value={issuer} onChange={(e) => setIssuer(e.target.value)} onBlur={() => { void refreshLabels(); }} />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||
账号名
|
||||
<Input value={accountName} onChange={(e) => setAccountName(e.target.value)} onBlur={() => { void refreshLabels(); }} />
|
||||
</label>
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="当前访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Input
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder="6 位验证码"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
/>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
<Button type="button" disabled={busy || !password || !code} onClick={() => { void confirm(); }}>
|
||||
{busy ? '正在开启…' : '确认开启'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function TotpChallengeDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
confirmText,
|
||||
destructive,
|
||||
onSubmit,
|
||||
onDone,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
description: string;
|
||||
confirmText: string;
|
||||
destructive?: boolean;
|
||||
onSubmit: (password: string, second: { totp?: string; recoveryCode?: string }) => Promise<{ success: boolean; message?: string }>;
|
||||
onDone: () => void | Promise<void>;
|
||||
}) {
|
||||
const [password, setPassword] = useState('');
|
||||
const [second, setSecond] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setPassword('');
|
||||
setSecond('');
|
||||
setError('');
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const result = await onSubmit(password, parseSecondFactor(second));
|
||||
setBusy(false);
|
||||
if (!result.success) {
|
||||
setError(result.message ?? '操作失败');
|
||||
return;
|
||||
}
|
||||
await onDone();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => onOpenChange(false)}
|
||||
title={title}
|
||||
description={description}
|
||||
closeLabel={`关闭${title}`}
|
||||
maxWidth={400}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="当前访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Input
|
||||
placeholder="6 位验证码或恢复码"
|
||||
value={second}
|
||||
onChange={(e) => setSecond(e.target.value)}
|
||||
autoComplete="one-time-code"
|
||||
/>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
<Button
|
||||
type="button"
|
||||
variant={destructive ? 'destructive' : 'default'}
|
||||
disabled={busy || !password || !second.trim()}
|
||||
onClick={() => { void submit(); }}
|
||||
>
|
||||
{busy ? '处理中…' : confirmText}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function TotpRegenDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onDone,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onDone: () => void | Promise<void>;
|
||||
}) {
|
||||
const api = useApi();
|
||||
const [password, setPassword] = useState('');
|
||||
const [totp, setTotp] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [codes, setCodes] = useState<string[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setPassword('');
|
||||
setTotp('');
|
||||
setError('');
|
||||
setCodes(null);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const result = await api.totp.regenerateRecoveryCodes(password, totp.trim());
|
||||
setBusy(false);
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
setCodes(result.recoveryCodes);
|
||||
await onDone();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => { if (!codes) onOpenChange(false); }}
|
||||
title={codes ? '新的恢复码' : '重新生成恢复码'}
|
||||
description={codes ? '旧恢复码已作废。请保存下面的新码。' : '需要当前密码和 Authenticator 验证码。旧恢复码会立即作废。'}
|
||||
closeLabel="关闭恢复码"
|
||||
maxWidth={440}
|
||||
>
|
||||
{codes ? (
|
||||
<TotpRecoveryCodes codes={codes} onConfirm={() => onOpenChange(false)} />
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="当前访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Input
|
||||
inputMode="numeric"
|
||||
placeholder="6 位验证码"
|
||||
value={totp}
|
||||
onChange={(e) => setTotp(e.target.value)}
|
||||
autoComplete="one-time-code"
|
||||
/>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
<Button type="button" disabled={busy || !password || !totp.trim()} onClick={() => { void submit(); }}>
|
||||
{busy ? '正在生成…' : '生成新恢复码'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useMemo } from 'react';
|
||||
import { encode } from 'uqr';
|
||||
|
||||
export function TotpQr({ value, label }: { value: string; label: string }) {
|
||||
const qr = useMemo(() => encode(value, { ecc: 'M', border: 2 }), [value]);
|
||||
const modules = qr.data.flatMap((row, y) => (
|
||||
row.flatMap((on, x) => (
|
||||
on ? <rect key={`${x}-${y}`} x={x} y={y} width="1" height="1" /> : []
|
||||
))
|
||||
));
|
||||
|
||||
return (
|
||||
<svg
|
||||
role="img"
|
||||
aria-label={label}
|
||||
viewBox={`0 0 ${qr.size} ${qr.size}`}
|
||||
className="size-44 rounded-lg bg-white text-black"
|
||||
shapeRendering="crispEdges"
|
||||
>
|
||||
<rect width={qr.size} height={qr.size} fill="white" />
|
||||
<g fill="black">{modules}</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useState } from 'react';
|
||||
import { Check, Copy } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
async function copyText(value: string): Promise<boolean> {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
return true;
|
||||
} catch {
|
||||
try {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = value;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
const ok = document.execCommand('copy');
|
||||
document.body.removeChild(ta);
|
||||
return ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function TotpRecoveryCodes({
|
||||
codes,
|
||||
onConfirm,
|
||||
}: {
|
||||
codes: string[];
|
||||
onConfirm: () => void;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
每个恢复码只能用一次。请立刻抄写或保存到离线位置,关闭后将无法再查看。
|
||||
</p>
|
||||
<ol className="grid grid-cols-2 gap-2 font-mono text-sm">
|
||||
{codes.map((code) => (
|
||||
<li key={code} className="rounded-md border bg-muted/40 px-3 py-2 text-center tracking-wide">
|
||||
{code}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="self-start"
|
||||
onClick={async () => {
|
||||
if (await copyText(codes.join('\n'))) setCopied(true);
|
||||
}}
|
||||
>
|
||||
{copied ? <Check className="size-4" /> : <Copy className="size-4" />}
|
||||
{copied ? '已复制' : '复制全部'}
|
||||
</Button>
|
||||
<label className="flex items-start gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saved}
|
||||
onChange={(e) => setSaved(e.target.checked)}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
我已把恢复码保存到安全的地方
|
||||
</label>
|
||||
<Button type="button" disabled={!saved} onClick={onConfirm}>
|
||||
完成
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
type StateStreamOptions,
|
||||
type StreamStatus,
|
||||
type TokenStore,
|
||||
type TotpStatus,
|
||||
} from './types';
|
||||
import { localStorageTokenStore } from './token-store';
|
||||
|
||||
@@ -62,6 +63,7 @@ class HttpApiClient implements ApiClient {
|
||||
readonly storage: ApiClient['storage'];
|
||||
readonly debug: ApiClient['debug'];
|
||||
readonly agreements: ApiClient['agreements'];
|
||||
readonly totp: ApiClient['totp'];
|
||||
|
||||
constructor(opts: CreateApiClientOptions = {}) {
|
||||
this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
|
||||
@@ -312,6 +314,97 @@ class HttpApiClient implements ApiClient {
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
this.totp = {
|
||||
status: async () => {
|
||||
const data = await this.getJson<TotpStatus>('/api/auth/totp');
|
||||
if (data.enabled === true) {
|
||||
return {
|
||||
enabled: true,
|
||||
remainingRecoveryCodes: data.remainingRecoveryCodes,
|
||||
label: data.label,
|
||||
};
|
||||
}
|
||||
return { enabled: false };
|
||||
},
|
||||
begin: async (options) => {
|
||||
try {
|
||||
const res = await this.request('/api/auth/totp/begin', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(options ?? {}),
|
||||
});
|
||||
const data = await readJson<{
|
||||
success?: boolean;
|
||||
message?: string;
|
||||
secret?: string;
|
||||
otpauthUrl?: string;
|
||||
issuer?: string;
|
||||
accountName?: string;
|
||||
}>(res);
|
||||
if (
|
||||
res.ok
|
||||
&& data.success === true
|
||||
&& typeof data.secret === 'string'
|
||||
&& typeof data.otpauthUrl === 'string'
|
||||
&& typeof data.issuer === 'string'
|
||||
&& typeof data.accountName === 'string'
|
||||
) {
|
||||
return {
|
||||
success: true,
|
||||
secret: data.secret,
|
||||
otpauthUrl: data.otpauthUrl,
|
||||
issuer: data.issuer,
|
||||
accountName: data.accountName,
|
||||
};
|
||||
}
|
||||
return { success: false, message: data.message ?? '无法开始 2FA 绑定' };
|
||||
} catch (e) {
|
||||
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
|
||||
}
|
||||
},
|
||||
confirm: async (password, code) => {
|
||||
try {
|
||||
const res = await this.request('/api/auth/totp/confirm', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password, code }),
|
||||
});
|
||||
const data = await readJson<{ success?: boolean; message?: string; recoveryCodes?: string[] }>(res);
|
||||
if (res.ok && data.success === true && Array.isArray(data.recoveryCodes)) {
|
||||
return { success: true, recoveryCodes: data.recoveryCodes };
|
||||
}
|
||||
return { success: false, message: data.message ?? '2FA 绑定失败' };
|
||||
} catch (e) {
|
||||
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
|
||||
}
|
||||
},
|
||||
disable: async (password, secondFactor) => {
|
||||
try {
|
||||
const res = await this.request('/api/auth/totp/disable', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password, ...secondFactor }),
|
||||
});
|
||||
const data = await readJson<{ success?: boolean; message?: string }>(res);
|
||||
return { success: res.ok && !!data.success, message: data.message };
|
||||
} catch (e) {
|
||||
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
|
||||
}
|
||||
},
|
||||
regenerateRecoveryCodes: async (password, totp) => {
|
||||
try {
|
||||
const res = await this.request('/api/auth/totp/recovery-codes', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password, totp }),
|
||||
});
|
||||
const data = await readJson<{ success?: boolean; message?: string; recoveryCodes?: string[] }>(res);
|
||||
if (res.ok && data.success === true && Array.isArray(data.recoveryCodes)) {
|
||||
return { success: true, recoveryCodes: data.recoveryCodes };
|
||||
}
|
||||
return { success: false, message: data.message ?? '无法重新生成恢复码' };
|
||||
} catch (e) {
|
||||
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- HTTP helpers ----------
|
||||
@@ -388,20 +481,37 @@ class HttpApiClient implements ApiClient {
|
||||
|
||||
// ---------- auth ----------
|
||||
|
||||
async login(password: string): Promise<LoginResult> {
|
||||
async login(
|
||||
password: string,
|
||||
secondFactor?: { totp?: string; recoveryCode?: string },
|
||||
): Promise<LoginResult> {
|
||||
// Login deliberately bypasses fetchJson/onUnauthorized so a bad password
|
||||
// doesn't trigger a global sign-out side effect.
|
||||
try {
|
||||
const res = await this.fetchWithDeadline('/api/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
body: JSON.stringify({
|
||||
password,
|
||||
...(secondFactor?.totp ? { totp: secondFactor.totp } : {}),
|
||||
...(secondFactor?.recoveryCode ? { recoveryCode: secondFactor.recoveryCode } : {}),
|
||||
}),
|
||||
});
|
||||
const payload = await readJson<{
|
||||
token?: string;
|
||||
mustChangePassword?: boolean;
|
||||
needsTotp?: boolean;
|
||||
message?: string;
|
||||
}>(res);
|
||||
if (res.ok && payload.needsTotp === true) {
|
||||
return { ok: false, needsTotp: true };
|
||||
}
|
||||
if (!res.ok) {
|
||||
const payload = await readJson<ErrorPayload>(res);
|
||||
return { ok: false, message: extractErrorMessage(payload, '令牌错误') };
|
||||
}
|
||||
const payload = await readJson<{ token: string; mustChangePassword?: boolean }>(res);
|
||||
if (typeof payload.token !== 'string' || payload.token.length === 0) {
|
||||
return { ok: false, message: extractErrorMessage(payload, '令牌错误') };
|
||||
}
|
||||
this.setToken(payload.token);
|
||||
return { ok: true, mustChangePassword: !!payload.mustChangePassword };
|
||||
} catch (e) {
|
||||
|
||||
@@ -43,8 +43,28 @@ export class ApiError extends Error {
|
||||
|
||||
export type LoginResult =
|
||||
| { ok: true; mustChangePassword: boolean }
|
||||
| { ok: false; needsTotp: true }
|
||||
| { ok: false; message: string };
|
||||
|
||||
export type TotpStatus =
|
||||
| { enabled: false }
|
||||
| { enabled: true; remainingRecoveryCodes: number; label: string };
|
||||
|
||||
export type TotpEnrollment = {
|
||||
secret: string;
|
||||
otpauthUrl: string;
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
};
|
||||
|
||||
export type TotpBeginResult =
|
||||
| { success: true } & TotpEnrollment
|
||||
| { success: false; message: string };
|
||||
|
||||
export type TotpConfirmResult =
|
||||
| { success: true; recoveryCodes: string[] }
|
||||
| { success: false; message: string };
|
||||
|
||||
export type ChangePasswordResult = { success: boolean; message?: string };
|
||||
|
||||
export interface AgreementDoc {
|
||||
@@ -115,7 +135,7 @@ export interface StateStreamOptions {
|
||||
|
||||
export interface ApiClient {
|
||||
// ---- auth ----
|
||||
login(password: string): Promise<LoginResult>;
|
||||
login(password: string, secondFactor?: { totp?: string; recoveryCode?: string }): Promise<LoginResult>;
|
||||
logout(): Promise<void>;
|
||||
/** True if the current token is still valid. */
|
||||
status(): Promise<boolean>;
|
||||
@@ -123,6 +143,13 @@ export interface ApiClient {
|
||||
mustChangePassword(): Promise<boolean>;
|
||||
checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult>;
|
||||
totp: {
|
||||
status(): Promise<TotpStatus>;
|
||||
begin(options?: { issuer?: string; accountName?: string }): Promise<TotpBeginResult>;
|
||||
confirm(password: string, code: string): Promise<TotpConfirmResult>;
|
||||
disable(password: string, secondFactor: { totp?: string; recoveryCode?: string }): Promise<{ success: boolean; message?: string }>;
|
||||
regenerateRecoveryCodes(password: string, totp: string): Promise<TotpConfirmResult>;
|
||||
};
|
||||
|
||||
// ---- EULA / PRIVACY consent (shown after login, before set-password) ----
|
||||
agreements: {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
export function parseSecondFactor(value: string): { totp: string } | { recoveryCode: string } {
|
||||
const trimmed = value.trim();
|
||||
const digits = trimmed.replace(/\s/g, '');
|
||||
if (/^\d{6}$/.test(digits)) return { totp: digits };
|
||||
return { recoveryCode: trimmed };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createApiClient } from '../src/lib/api/client';
|
||||
|
||||
const tokenStore = {
|
||||
load: () => null as string | null,
|
||||
save: vi.fn(),
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
tokenStore.save.mockReset();
|
||||
});
|
||||
|
||||
describe('login 2FA client', () => {
|
||||
it('returns needsTotp without storing a session token', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
|
||||
success: false,
|
||||
needsTotp: true,
|
||||
}), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
|
||||
const client = createApiClient({ tokenStore });
|
||||
await expect(client.login('Correct-Horse-1!')).resolves.toEqual({ ok: false, needsTotp: true });
|
||||
expect(tokenStore.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends the TOTP on the second login request and stores the session', async () => {
|
||||
const fetchMock = vi.fn(async () => new Response(JSON.stringify({
|
||||
success: true,
|
||||
token: 'session-token',
|
||||
mustChangePassword: false,
|
||||
}), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const client = createApiClient({ tokenStore });
|
||||
await expect(client.login('Correct-Horse-1!', { totp: '287082' })).resolves.toEqual({
|
||||
ok: true,
|
||||
mustChangePassword: false,
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/login', expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password: 'Correct-Horse-1!', totp: '287082' }),
|
||||
}));
|
||||
expect(tokenStore.save).toHaveBeenCalledWith('session-token');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { LoginPage } from '../src/components/pages/login-page';
|
||||
|
||||
vi.mock('@/contexts/ThemeContext', () => ({
|
||||
useTheme: () => ({
|
||||
appearance: {
|
||||
background: { type: 'none' },
|
||||
reduceMotion: true,
|
||||
disableMotion: true,
|
||||
palette: 'default',
|
||||
},
|
||||
mode: 'light',
|
||||
setMode: () => undefined,
|
||||
}),
|
||||
paletteResolved: () => false,
|
||||
}));
|
||||
|
||||
describe('LoginPage 2FA step', () => {
|
||||
it('keeps the password form on its own screen', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<LoginPage onLogin={async () => ({ success: false, error: 'no' })} />,
|
||||
);
|
||||
expect(markup).toContain('输入访问令牌');
|
||||
expect(markup).toContain('进入控制台');
|
||||
expect(markup).toContain('max-w-md');
|
||||
expect(markup).not.toContain('max-w-2xl');
|
||||
expect(markup).not.toContain('character 1 of 6');
|
||||
expect(markup).not.toContain('验证并进入');
|
||||
});
|
||||
|
||||
it('shows a separate TOTP screen after the password factor succeeds', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<LoginPage
|
||||
initialPassword="Correct-Horse-1!"
|
||||
initialNeedsTotp
|
||||
onLogin={async () => ({ success: false, needsTotp: true })}
|
||||
/>,
|
||||
);
|
||||
expect(markup).not.toContain('输入访问令牌');
|
||||
expect(markup).toContain('输入 Authenticator 中的 6 位验证码');
|
||||
expect(markup).not.toContain('验证并进入');
|
||||
expect(markup).toContain('character 1 of 6');
|
||||
expect(markup).toContain('可以把完整验证码粘贴到任意一格。');
|
||||
expect(markup).toContain('使用恢复码');
|
||||
expect(markup).toContain('返回');
|
||||
expect(markup).toContain('max-w-md');
|
||||
expect(markup).not.toContain('max-w-2xl');
|
||||
expect(markup).not.toContain('h-[2px] w-3 rounded-full');
|
||||
});
|
||||
|
||||
it('uses the same cell UI for a recovery code instead of a single field', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<LoginPage
|
||||
initialPassword="Correct-Horse-1!"
|
||||
initialNeedsTotp
|
||||
initialUseRecovery
|
||||
onLogin={async () => ({ success: false, needsTotp: true })}
|
||||
/>,
|
||||
);
|
||||
expect(markup).toContain('输入保存的一次性恢复码');
|
||||
expect(markup).toContain('character 1 of 8');
|
||||
expect(markup).toContain('character 8 of 8');
|
||||
expect(markup).toContain('可以把完整恢复码粘贴到任意一格');
|
||||
expect(markup).toContain('改用验证码');
|
||||
expect(markup).toContain('max-w-2xl');
|
||||
expect(markup).toContain('h-[2px] w-3 rounded-full');
|
||||
expect(markup).not.toContain('XXXX-XXXX');
|
||||
expect(markup).not.toContain('验证并进入');
|
||||
expect(markup).not.toContain('输入访问令牌');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { OtpInput } from '../src/components/interior/otp-input';
|
||||
|
||||
describe('OtpInput official error/hint contract', () => {
|
||||
it('shows the hint while error is false', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<OtpInput
|
||||
label="验证码"
|
||||
hint="可以把完整验证码粘贴到任意一格。"
|
||||
error={false}
|
||||
errorMessage="验证码不正确,改错的那一位即可。"
|
||||
/>,
|
||||
);
|
||||
expect(markup).toContain('可以把完整验证码粘贴到任意一格。');
|
||||
expect(markup).not.toContain('验证码不正确,改错的那一位即可。');
|
||||
});
|
||||
|
||||
it('swaps to the error message when error is true', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<OtpInput
|
||||
label="验证码"
|
||||
hint="可以把完整验证码粘贴到任意一格。"
|
||||
error
|
||||
errorMessage="验证码不正确,改错的那一位即可。"
|
||||
/>,
|
||||
);
|
||||
expect(markup).toContain('验证码不正确,改错的那一位即可。');
|
||||
expect(markup).toContain('aria-invalid="true"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseSecondFactor } from '../src/lib/totp-second-factor';
|
||||
|
||||
describe('parseSecondFactor', () => {
|
||||
it('treats a 6-digit code as TOTP, ignoring spaces', () => {
|
||||
expect(parseSecondFactor('287 082')).toEqual({ totp: '287082' });
|
||||
});
|
||||
|
||||
it('treats a recovery code as a recovery code', () => {
|
||||
expect(parseSecondFactor('AB3D-K7MQ')).toEqual({ recoveryCode: 'AB3D-K7MQ' });
|
||||
});
|
||||
});
|
||||
Generated
+24
@@ -122,6 +122,9 @@ importers:
|
||||
'@snowluma/websocket':
|
||||
specifier: workspace:*
|
||||
version: link:../websocket
|
||||
otpauth:
|
||||
specifier: ^9.5.1
|
||||
version: 9.5.1
|
||||
devDependencies:
|
||||
'@hono/node-server':
|
||||
specifier: ^1.19.14
|
||||
@@ -428,6 +431,9 @@ importers:
|
||||
tw-animate-css:
|
||||
specifier: ^1.2.5
|
||||
version: 1.4.0
|
||||
uqr:
|
||||
specifier: ^0.1.3
|
||||
version: 0.1.3
|
||||
devDependencies:
|
||||
'@eslint/js':
|
||||
specifier: ^10.0.1
|
||||
@@ -853,6 +859,10 @@ packages:
|
||||
'@emnapi/core': ^1.7.1
|
||||
'@emnapi/runtime': ^1.7.1
|
||||
|
||||
'@noble/hashes@2.2.0':
|
||||
resolution: {integrity: sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==}
|
||||
engines: {node: '>= 20.19.0'}
|
||||
|
||||
'@oxc-project/types@0.137.0':
|
||||
resolution: {integrity: sha512-WT+Gb24i8hmvo85AIv2oEYouEXkRlKAlT9WaCa3TfLgNCN+GhrJOGZuIlMouAh38Qe4QOx26eUOVsq70qXrywA==}
|
||||
|
||||
@@ -2867,6 +2877,9 @@ packages:
|
||||
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
|
||||
engines: {node: '>= 0.8.0'}
|
||||
|
||||
otpauth@9.5.1:
|
||||
resolution: {integrity: sha512-fJmDAHc8wImfqqqOXIlBvT1dEKrZK0Cmb2VEgScpNTolCz0PHh6ExUZGv4sLtOsWNaHCQlD+rRqaPgnoxFoZjQ==}
|
||||
|
||||
p-limit@3.1.0:
|
||||
resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -3264,6 +3277,9 @@ packages:
|
||||
peerDependencies:
|
||||
browserslist: '>= 4.21.0'
|
||||
|
||||
uqr@0.1.3:
|
||||
resolution: {integrity: sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==}
|
||||
|
||||
uri-js@4.4.1:
|
||||
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
|
||||
|
||||
@@ -3759,6 +3775,8 @@ snapshots:
|
||||
'@tybys/wasm-util': 0.10.3
|
||||
optional: true
|
||||
|
||||
'@noble/hashes@2.2.0': {}
|
||||
|
||||
'@oxc-project/types@0.137.0': {}
|
||||
|
||||
'@parcel/watcher-android-arm64@2.5.6':
|
||||
@@ -5595,6 +5613,10 @@ snapshots:
|
||||
type-check: 0.4.0
|
||||
word-wrap: 1.2.5
|
||||
|
||||
otpauth@9.5.1:
|
||||
dependencies:
|
||||
'@noble/hashes': 2.2.0
|
||||
|
||||
p-limit@3.1.0:
|
||||
dependencies:
|
||||
yocto-queue: 0.1.0
|
||||
@@ -6011,6 +6033,8 @@ snapshots:
|
||||
escalade: 3.2.0
|
||||
picocolors: 1.1.1
|
||||
|
||||
uqr@0.1.3: {}
|
||||
|
||||
uri-js@4.4.1:
|
||||
dependencies:
|
||||
punycode: 2.3.1
|
||||
|
||||
+33
-8
@@ -13,7 +13,7 @@
|
||||
// auto-merges if the GitHub setting allows.
|
||||
// 4. Push to origin/dev.
|
||||
// 5. (Unless `--no-wait`) poll the Promote PR via `gh` until it
|
||||
// merges, then `git fetch && git checkout main && git pull`,
|
||||
// merges, then fetch and fast-forward `main` to `origin/main`,
|
||||
// create `vX.Y.Z` tag, push it — that triggers `release.yml`.
|
||||
// 6. Switch back to `dev` so the next `git log` view is back where
|
||||
// you were.
|
||||
@@ -81,6 +81,34 @@ function ok(msg) { console.log(`\x1b[32m✓\x1b[0m ${msg}`); }
|
||||
function info(msg) { console.log(`\x1b[36mi\x1b[0m ${msg}`); }
|
||||
function warn(msg) { console.log(`\x1b[33m!\x1b[0m ${msg}`); }
|
||||
|
||||
function printManualFinish() {
|
||||
info('Once the Promote PR merges, finish manually with:');
|
||||
info(' git fetch origin refs/heads/main:refs/remotes/origin/main');
|
||||
info(' git switch main');
|
||||
info(' git merge --ff-only origin/main');
|
||||
info(` git tag ${tag} && git push origin ${tag}`);
|
||||
}
|
||||
|
||||
function syncMain() {
|
||||
// Use a fully qualified refspec and an explicit fast-forward so release
|
||||
// behavior cannot be changed by the caller's pull/rebase configuration.
|
||||
sh('git fetch origin refs/heads/main:refs/remotes/origin/main --quiet');
|
||||
sh('git switch main');
|
||||
sh('git merge --ff-only origin/main');
|
||||
|
||||
if (dryRun) return;
|
||||
|
||||
const localMain = shCapture('git rev-parse refs/heads/main');
|
||||
const remoteMain = shCapture('git rev-parse refs/remotes/origin/main');
|
||||
if (localMain !== remoteMain) {
|
||||
throw new Error(
|
||||
`Refusing to tag: local main (${localMain.slice(0, 12)}) does not exactly match ` +
|
||||
`origin/main (${remoteMain.slice(0, 12)}).`,
|
||||
);
|
||||
}
|
||||
ok('main matches origin/main');
|
||||
}
|
||||
|
||||
// ───────────── step 1: preflight ─────────────
|
||||
|
||||
function preflightFail(msg) {
|
||||
@@ -145,8 +173,7 @@ function bumpAndPushDev() {
|
||||
async function waitAndTag() {
|
||||
if (!which('gh')) {
|
||||
warn('`gh` CLI not found — skipping auto-tag.');
|
||||
info('Once the Promote PR merges, run:');
|
||||
info(` git fetch && git checkout main && git pull && git tag ${tag} && git push origin ${tag}`);
|
||||
printManualFinish();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -196,13 +223,11 @@ async function waitAndTag() {
|
||||
|
||||
if (Date.now() - startedAt >= TIMEOUT_MS) {
|
||||
warn('30-minute timeout reached without seeing the PR merge.');
|
||||
info(`Once it does, finish manually: git checkout main && git pull && git tag ${tag} && git push origin ${tag}`);
|
||||
printManualFinish();
|
||||
return;
|
||||
}
|
||||
|
||||
sh('git fetch origin main --quiet');
|
||||
sh('git checkout main');
|
||||
sh('git pull origin main');
|
||||
syncMain();
|
||||
|
||||
// Sanity: package.json on main matches version
|
||||
const mainPkg = JSON.parse(await readFile(path.join(repoRoot, 'package.json'), 'utf-8'));
|
||||
@@ -229,7 +254,7 @@ async function waitAndTag() {
|
||||
|
||||
if (noWait) {
|
||||
info('--no-wait set; not polling for PR merge.');
|
||||
info(`Once it merges: git checkout main && git pull && git tag ${tag} && git push origin ${tag}`);
|
||||
printManualFinish();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user